TypeError:'Tensor'对象不支持TensorFlow中的项目分配

Nil*_*Cao 20 python 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)
Run Code Online (Sandbox Code Playgroud)

但我在最后一行得到错误: TypeError: 'Tensor' object does not support item assignment 似乎我无法分配张量,我该如何解决?

mrr*_*rry 31

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

你要做的最简单的方法是建立一个张量的张量列表,并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)
Run Code Online (Sandbox Code Playgroud)

 *除了tf.Variable对象,使用Variable.assign()等方法.但是,rnn.rnn()可能会返回tf.Tensor不支持此方法的对象.


yuv*_*blr 8

当您已经有了张量时,使用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)
Run Code Online (Sandbox Code Playgroud)


小智 6

你可以这样做的另一种方式.

aa=tf.Variable(tf.zeros(3, tf.int32))
aa=aa[2].assign(1)
Run Code Online (Sandbox Code Playgroud)

然后输出是:

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

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

  • 在 TF2 中不起作用:EagerTensor 对象没有属性“分配” (3认同)
  • 在我所做的将一维向量分配给二维数组的所有速度测试中,这个答案的性能最差。不要使用这个方法!迄今为止最快的是 mrry 的答案,即附加到列表和堆叠。 (2认同)