我正在使用 Tensorflow 2.0,并试图更新我的张量中的切片。
使用像 PyTorch 中的普通项目分配,它不起作用。
import tensorflow as tf
tensor = tf.ones((10, 192, 85))
tensor[:, :, 0] = tf.math.sigmoid([:, :, 0])
>>> Output
TypeError: 'tensorflow.python.framework.ops.EagerTensor' object does not support item assignment
我看到可以使用
tf.tensor_scatter_nd_update
,但感觉太冗长而无法高效,因为我必须单独导出要更新的索引。因此,我不确定这是否是在热切张量中进行项目分配的最佳方法(我需要下面的代码块来实现上面更简单的“PyTorch 2-liner style”):import tensorflow as tf
def get_indices(tensor):
indices = []
for i in range(tensor.shape[0]):
for j in range(tensor.shape[1]):
indices.append([i, j, 0])
return tf.convert_to_tensor(indices)
tensor = tf.ones((10, 192, 85))
indices = get_indices(tensor)
updates = tf.reshape(tf.math.sigmoid(tensor[:, :, 0]), (-1,))
tensor = tf.tensor_scatter_nd_update(tensor, indices, updates)
是否有更简单/更有效的方式来分配
EagerTensor
的项目?在 Tensorflow 2.0 中?
最佳答案
你可以这样做:
tensor = tf.ones((10, 192, 85))
tensor = tf.concat([tf.math.sigmoid(tensor[:,:,0:1]), tensor[:,:,1:]], axis=2)
关于python - 项目分配 Tensorflow 2.0 - TypeError : 'tensorflow.python.framework.ops.EagerTensor' object does not support item assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58241663/