python - 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]
解决方案
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)
推荐阅读
- css - 元素落在边界之外
- python - 使用 for 循环缩放列
- arkit - 如何在服务器上保存 ARKIT 扫描的资源?
- javascript - 找不到模块:错误:无法解析“/home/user/Desktop/my_app/src”中的“./app”
- android - Xamarin 文本转语音总时间
- javascript - 删除画布中特定坐标的对象
- c++ - 服务器端事件 C++ 实现?
- javascript - 滚动到顶部元素不会在滚动后出现 - 它固定在底部
- c# - 解决温莎城堡中的依赖关系时如何将一种类型转换为另一种类型
- sql-server - 使用 SQL Server 将字符插入 INT 字段