2016-09-22 79 views
0

下面的代碼告訴我「輸入必須是一個列表」。在這。這是什麼意思「輸入必須是一個列表」?

outputs, states = rnn.rnn(lstm_cell, x, dtype=tf.float32) 

當我爲輸入定義佔位符x。我已經將形狀設置爲[None,None]。我認爲這個形狀是二維數組。但是,代碼不斷需要列表類型x

下面,我已經附加了我的所有代碼在訓練之前。這個代碼被插入到類的函數中。

x = tf.placeholder("float",[None,None]) 
y = tf.placeholder("float",[None]) 

lstm_cell = rnn_cell.BasicLSTMCell(self.n_hidden, forget_bias=1.0) 

outputs, states = rnn.rnn(lstm_cell, x, dtype=tf.float32) 

pred = tf.matmul(outpus[-1], self.weights['out']) + self.biases['out'] 
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y)) 
optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(cost) 

correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1)) 
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) 

init = tf.initialize_all_variables() 

self.sess = tf.Session() 

self.sess.run(init) 

此外,實際的輸入將是浮法形成爲x=[["aaa","aaa","aaa"],["bbb","bbb"]]y=["c1","c2"]單詞序列和浮子標籤的。

那麼,x的第一個元素數組標記爲「c1」,第二個元素數組爲「c2」。特別是,x的每個元素數組的大小不能確定。

回答

0

如上所述由documentation,所述參數的函數tf.nn.rnn()inputs是:

輸入:的輸入端A長度T列表,每個張量形狀[batch_size時,input_size],或嵌套元組的這些元素。

在你的代碼中,參數inputsx,一個張量佔位符形狀[None, None]的。爲了讓您的代碼正常工作,x必須是形狀爲[None, input_lenght]的T張量的列表。

以下代碼生成張量列表inputs,因此函數tf.nn.rnn有效。

import tensorflow as tf 

x = tf.placeholder("float",[None,16]) 
y = tf.placeholder("float",[None]) 

lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(256, forget_bias=1.0) 

inputs = [] 
for t in range(10): 
     inputs.append(x) 

print(len(inputs)) 

outputs, states = tf.nn.rnn(lstm_cell, inputs, dtype=tf.float32) 

pred = tf.matmul(outputs[-1], self.weights['out']) + self.biases['out'] 
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y)) 
optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(cost) 

correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1)) 
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) 

init = tf.initialize_all_variables() 

self.sess = tf.Session() 

self.sess.run(init) 

注意佔位符x如何具有限定的[None, input_shape]形狀。它不適用於形狀[None, None],因爲第一個維度是batch_size,它可以是None,但第二個維度是輸入序列中每個項目的大小,並且該值不能是None

+0

謝謝。如果訓練數據的最小長度和最大長度之間的距離較大,如何在算法的一個方面產生固定的輸入大小? – hackartist