TypeError:'Tensor' 对象不支持 TensorFlow 中的项目分配 [英] TypeError: 'Tensor' object does not support item assignment in TensorFlow

查看:36
本文介绍了TypeError:'Tensor' 对象不支持 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' 对象不支持项目分配似乎我无法分配给张量,我该如何解决?

But I get error on last line: TypeError: 'Tensor' object does not support item assignment It seems I can not assign to tensor, how can I fix it?

推荐答案

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

In general, a TensorFlow tensor object is not assignable*, so you cannot use it on the left-hand side of an assignment.

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

The easiest way to do what you're trying to do is to build a Python list of tensors, and tf.stack() them together at the end of the loop:

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() 等方法.但是,rnn.rnn() 可能会返回一个 tf.Tensor 不支持此方法的对象.


 * With the exception of tf.Variable objects, using the Variable.assign() etc. methods. However, rnn.rnn() likely returns a tf.Tensor object that does not support this method.

这篇关于TypeError:'Tensor' 对象不支持 TensorFlow 中的项目分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆