首页 > 解决方案 > TypeError:“tensorflow.python.framework.ops.EagerTensor”对象不支持项目分配

问题描述

我有一种情况,我取一个 tf 张量,我将它转换为 numpy,我做了一些计算,最后我想把这个切片放回它来自的地方,即 tf 张量。具体来说,这都是小批量生成/更改过程的一部分。

mini_batch.shape

将产生以下张量形状

TensorShape([#samples, 640, 1152, 3])

我处理的np_slice来自上面的张量

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

我尝试重新插入它

mini_batch[sample_index][:, :, 2] = tf.convert_to_tensor(np_slice, dtype=tf.float32)

请注意,np_slice具有形状,(640, 1152)即单通道图像

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

TypeError: 'tensorflow.python.framework.ops.EagerTensor' object does not support item assignment

看来我需要利用tf.tensor_scatter_nd_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]

标签: pythontensorflow

解决方案


Tensorflow 张量是不可变的(文档):

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

您可以使用Tensorflow 变量或在 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)

推荐阅读