我尝试运行以下代码:
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 似乎我无法分配张量,如何解决?
TypeError: 'Tensor' object does not support item assignment
通常,TensorFlow张量对象不可分配*,因此您不能在分配的左侧使用它。
做您想做的事情的最简单方法是构建张量的Python列表,并tf.stack()在循环结束时将它们在一起:
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对象外,使用Variable.assign()etc.方法。但是,rnn.rnn()可能返回tf.Tensor不支持此方法的对象。
tf.Variable
Variable.assign()
rnn.rnn()
tf.Tensor