类型错误:';tensorflow.python.framework.ops.tensor';对象不支持项分配

类型错误:';tensorflow.python.framework.ops.tensor';对象不支持项分配,python,tensorflow,Python,Tensorflow,在这种情况下,我取一个tf张量的切片,把它转换成numpy,我做一些计算,最后我想把这个切片放回它的来源,也就是tf张量。具体而言,这是小批量生产/变更程序的全部组成部分 mini_batch.shape 将产生以下张量形状 TensorShape([#samples, 640, 1152, 3]) 我处理的np_切片来自上面的张量 np_slice = mini_batch[sample_index][:, :, 2].numpy() 我试着重新插入它 mini_batch[sample

在这种情况下,我取一个tf张量的切片,把它转换成numpy,我做一些计算,最后我想把这个切片放回它的来源,也就是tf张量。具体而言,这是小批量生产/变更程序的全部组成部分

mini_batch.shape
将产生以下张量形状

TensorShape([#samples, 640, 1152, 3])
我处理的
np_切片
来自上面的张量

np_slice = mini_batch[sample_index][:, :, 2].numpy()
我试着重新插入它

mini_batch[sample_index][:, :, 2] = tf.convert_to_tensor(np_slice, dtype=tf.float32)
请注意,
np\u切片
具有形状
(6401152)
,即单通道图像

据我所知,tf不允许这种分配,因此我的错误

TypeError: 'tensorflow.python.framework.ops.EagerTensor' object does not support item assignment
看来我需要使用
tf.tensor\u scatter\u和\u update

这是我迄今为止尝试过的,但它并没有按照我的要求工作

indices = tf.constant([[sample_index]])
updates = tf.convert_to_tensor(np_slice, dtype=tf.float32)
mini_batch = tf.tensor_scatter_nd_update(mini_batch, indices, updates)
这会产生以下结果

tensorflow.python.framework.errors_impl.InvalidArgumentError: Outer dimensions of indices and update must match. Indices shape: [1,1], updates shape:[640,1152] [Op:TensorScatterUpdate]

Tensorflow张量是不可变的():

所有的张量都是不可变的,就像Python数字和字符串一样:您永远不能更新张量的内容,只能创建一个新的张量

您可以使用或在numpy数组中进行切片和计算,并在最后将其转换为张量:

mini_batch_np=mini_batch.numpy()
np_slice = mini_batch_np[sample_index][:, :, 2]

#some calculations with np_slice

mini_batch_np[sample_index][:, :, 2] = np_slice

#convert back to tensor
mini_batch=tf.convert_to_tensor(mini_batch_np, dtype=tf.float32)