Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I try to run this code:

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)

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?

like image 935
Nils Cao Avatar asked Jun 08 '16 08:06

Nils Cao


3 Answers

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

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)

 * 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.

like image 71
mrry Avatar answered Oct 20 '22 01:10

mrry


Another way you can do it is like this.

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

then the output is:

array([0, 0, 1], dtype=int32)

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

like image 36
xiangshu lin Avatar answered Oct 20 '22 01:10

xiangshu lin


When you have a tensor already, convert the tensor to a list using tf.unstack (TF2.0) and then use tf.stack like @mrry has mentioned. (when using a multi-dimensional tensor, be aware of the axis argument in unstack)

a_list = tf.unstack(a_tensor)

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

a_tensor = tf.stack(a_list)
like image 4
yuva-rajulu Avatar answered Oct 20 '22 00:10

yuva-rajulu