2016-06-08 21 views
10

provo a fare funzionare questo codice:TypeError: oggetto 'Tensor' non supporta l'assegnazione elemento in 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) 

Ma ottengo errore nell'ultima riga: TypeError: 'Tensor' object does not support item assignment Sembra che io non posso assegnare al tensore, come posso ripararlo?

risposta

17

In generale, un oggetto tensoriale TensorFlow non è assegnabile *, quindi non è possibile utilizzarlo sul lato sinistro di un'assegnazione.

Il modo più semplice per fare ciò che si sta cercando di fare è quello di costruire una lista Python dei tensori, e tf.stack() insieme alla fine del ciclo:

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) 

  * Con il eccezione degli oggetti tf.Variable, utilizzando i metodi Variable.assign() ecc. Tuttavia, rnn.rnn() restituisce probabilmente un oggetto tf.Tensor che non supporta questo metodo.

+1

WoW, grazie mille :) –

+0

Nota che 'tf.pack()' è stato sostituito da [tf.stack()] (https://www.tensorflow.org/api_docs/python/tf/stack) da TensorFlow 1.0. – CNugteren

+0

Ho aggiornato la risposta per riflettere la nuova API. – mrry

4

Un altro modo per farlo in questo modo.

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

allora l'uscita è:

array ([0, 0, 1], DTYPE = Int32)

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

+0

Sembra che si sia verificato un errore durante il tentativo di implementarlo in questo modo: 'x = tf.Variable (tf.ones ([1,2,2,3], tf.float32))' 'x = x [:,:,: 1] .assign (2.0) ' ' con tf.Session() come sess: ' ' sess.run (tf.global_variables_initializer()) ' ' x_data = sess.run (x) ' – Moondra