jggybf 2019-10-04 20:43 采纳率: 0%

# tensorflow RNN LSTM代码运行不正确？

``````#7.2 RNN
import tensorflow as tf
#tf.reset_default_graph()
from tensorflow.examples.tutorials.mnist import input_data

#载入数据集
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)

#输入图片是28*28
n_inputs = 28  #输入一行，一行有28个数据
max_time = 28  #一共28行
lstm_size = 100  #隐层单元
n_classes = 10  #10个分量
batch_size = 50  #每批次50个样本
n_batch = mnist.train.num_examples//batch_size #计算共由多少个批次

#这里的none表示第一个维度可以是任意长度
x = tf.placeholder(tf.float32, [batch_size, 784])
#正确的标签
y = tf.placeholder(tf.float32, [batch_size, 10])

#初始化权值
weights = tf.Variable(tf.truncated_normal([lstm_size, n_classes], stddev = 0.1))
#初始化偏置
biases = tf.Variable(tf.constant(0.1, shape = [n_classes]))

#定义RNN网络
def RNN(X, weights, biases):
#input = [batch_size, max_size, n_inputs]
inputs = tf.reshape(X, [-1, max_time, n_inputs])
#定义LSTM基本CELL
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(lstm_size)
#final_state[0]是cell_state
#final_state[1]是hidden_state
outputs, final_state = tf.nn.dynamic_rnn(lstm_cell, inputs, dtype = tf.float32)
results = tf.nn.softmax(tf.matmul(final_state[1], weights) + biases)

#计算RNN的返回结果
prediction = RNN(x, weights, biases)
#损失函数
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels = y,logits = prediction))

#结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y, 1),tf.argmax(prediction, 1))
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_precdition,tf.float32))

#初始化
init = tf.global_variable_initializer()

with tf.Session() as sess:
sess.run(init)
for epoch in range(6):
for batch in range(n_batch):
batch_xs,batch_ys=mnist.train.next_batch(batch_size)
sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})

acc = sess.run(accuracy, feed_dict={x:mnist.test.images,y:mnist.test.labels})
print('Iter' + str(epoch) + ',Testing Accuracy = ' + str(acc))
``````
• 写回答

#### 2条回答默认 最新

• lmw0320 2019-10-17 14:44
关注

试着把X和Y定义placeholder时的维度，由batch_size换成None.
因为你这样是固定了传入的数据集大小，在测试集时的维度是10000个，而不是batch-size个

本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥15 关于网上一个easyx制作的见缝插针小游戏(c++)
• ¥15 开地址法双散列函数处理碰撞
• ¥15 想问一下这个是什么情况 虚拟机Linux打不开了
• ¥15 联通光猫掉注册了怎么重新注册上去
• ¥15 关于unity开发steamvr程序遇到的问题