tensorflow:LSTM单元格中变量的初始化程序

时间:2017-09-30 05:51:41

标签: python tensorflow neural-network lstm rnn

我正在尝试建立一个RNN来预测输入数据的情绪为正面还是负面。

tf.reset_default_graph()

input_data = tf.placeholder(tf.int32, [batch_size, 40])
labels = tf.placeholder(tf.int32, [batch_size, 40])

data = tf.Variable(tf.zeros([batch_size, 40, 50]), dtype=tf.float32)
data = tf.nn.embedding_lookup(glove_embeddings_arr, input_data)

lstm_cell = tf.contrib.rnn.BasicLSTMCell(lstm_units)
lstm_cell = tf.contrib.rnn.DropoutWrapper(cell = lstm_cell, output_keep_prob = 0.75)
value,state = tf.nn.dynamic_rnn(lstm_cell, data, dtype=tf.float32)

weight = tf.Variable(tf.truncated_normal([lstm_units, classes]))
bias = tf.Variable(tf.constant(0.1, shape = [classes]))
value = tf.transpose(value, [1,0,2])
last = tf.gather(value, int(value.get_shape()[0]) - 1)
prediction = (tf.matmul(last, weight) + bias)



true_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(labels,1))
accuracy = tf.reduce_mean(tf.cast(true_pred,tf.float32))

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=labels))
optimizer = tf.train.AdamOptimizer().minimize(loss)

解释器返回

ValueError: An initializer for variable rnn/basic_lstm_cell/kernel of <dtype: 'string'> is required

有人可以向我解释这个错误吗?

1 个答案:

答案 0 :(得分:1)

问题是您(很可能)将原始输入文本提供给网络。这不在您的代码段中,但错误表示 <dtype: 'string'>

  

ValueError:变量rnn / basic_lstm_cell / kernel的初始值设定项   &lt; dtype:&#39;字符串&#39;&gt; 是必需的

从LSTM单元获得的输入推断出类型。内部LSTM变量(kernelbias)使用默认初始化程序进行初始化,该初始化程序(至少现在)只能处理floating and integer types,但对其他类型则无效。在您的情况下,类型为tf.string,这就是您看到此错误的原因。

现在,您应该做的是将输入句子转换为实数向量。最好的方法是通过word embedding,例如word2vec,但也可以使用简单的单词索引。看看this post,特别是它们如何处理文本数据。还有一个完整的工作代码示例。