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
不支持此方法的对象.
当您已经有了张量时,使用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