TypeError: 'Tensor' object does not support item assignment in TensorFlow

TypeError: 'Tensor' object does not support item assignment in TensorFlow

我尝试运行这个代码:

outputs, states = rnn.rnn(lstm_cell, x, initial_state=initial_state, sequence_length=real_length)

tensor_shape = outputs.get_shape()
for step_index in range(tensor_shape[0]):
    word_index = self.x[:, step_index]
    word_index = tf.reshape(word_index, [-1,1])
    index_weight = tf.gather(word_weight, word_index)
    outputs[step_index,  :,  :]=tf.mul(outputs[step_index,  :,  :] , index_weight)

但最后一行出现错误: TypeError: 'Tensor' object does not support item assignment 我好像无法分配给张量,我该如何解决?

通常,TensorFlow 张量对象不可赋值*,因此您不能在赋值的左侧使用它。

最简单的方法是构建一个 Python 张量列表,并在循环结束时将它们 tf.stack() 在一起:

outputs, states = rnn.rnn(lstm_cell, x, initial_state=initial_state,
                          sequence_length=real_length)

output_list = []

tensor_shape = outputs.get_shape()
for step_index in range(tensor_shape[0]):
    word_index = self.x[:, step_index]
    word_index = tf.reshape(word_index, [-1,1])
    index_weight = tf.gather(word_weight, word_index)
    output_list.append(tf.mul(outputs[step_index, :, :] , index_weight))

outputs = tf.stack(output_list)

* 除了不支持此方法的 tf.Variable objects, using the Variable.assign() etc. methods. However, rnn.rnn() likely returns a tf.Tensor 对象。

另一种方法,你可以这样做。

aa=tf.Variable(tf.zeros(3, tf.int32))
aa=aa[2].assign(1)

那么输出是:

数组([0, 0, 1], dtype=int32)

参考:https://www.tensorflow.org/api_docs/python/tf/Variable#assign

当你已经有了张量时, 使用 tf.unstack (TF2.0) 将张量转换为列表,然后像@mrry 提到的那样使用 tf.stack 。 (使用多维张量时,注意 unstack 中的 axis 参数)

a_list = tf.unstack(a_tensor)

a_list[50:55] = [np.nan for i in range(6)]

a_tensor = tf.stack(a_list)

正如这个 comment 所说,解决方法是创建一个 NEW 张量,其中包含前一个张量和所需区域的新张量。

  1. 创建形状为 outputs 的遮罩,其中要替换的索引为 0,其他位置为 1(也可以使用 TrueFalse
  2. 使用新的期望值创建形状为 outputs 的新矩阵:new_values
  3. 仅将需要的索引替换为:outputs_new = outputs* mask + new_values * (1 - mask)

如果你能给我一个 MWE,我可以为你做代码。

这条注释是一个很好的参考:How to Replace Values by Index in a Tensor with TensorFlow-2.0