以下是一个示例:
import numpy as np
import tensorflow as tf
from tensorflow.python.ops import rnn, rnn_cell
if __name__ == '__main__':
embs = tf.Variable(np.random.random((40,5)),dtype=tf.float32)
X = np.array(np.array(range(1,25)).reshape(4, 6))
x0 = tf.placeholder(tf.int32, [None, None])
x1 = tf.nn.embedding_lookup(embs, x0)
lstm = tf.nn.rnn_cell.BasicLSTMCell(5,state_is_tuple=True)
outputs, states = tf.nn.dynamic_rnn(lstm, x1, dtype=tf.float32,time_major = True)
cost = tf.reduce_mean(outputs[:,-1,:])
optimizer = tf.train.AdagradOptimizer(learning_rate=0.12).minimize(cost)
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
result3, opt = sess.run([outputs, optimizer],{x0:X})
我只使用一片输出,即输出[:, - 1,:]来获得成本函数。当我运行代码时,我得到了结果 F ./tensorflow/core/framework/tensor.h:581]检查失败:new_num_elements == NumElements()(0 vs. 20)
如何解决这个问题?它只是一个样本。当我实现一个分层LSTM时,我遇到了这个问题,其中由LSTM计算的句子的表示被输入另一个LSTM。