import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#载入数据集
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)
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
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])#正确的标签
weights=tf.Variable(tf.truncated_normal([lstm_size,n_classes],stddev=0.1))
biases=tf.Variable(tf.constant(0.1,shape=[n_classes]))
def RNN(X,weights,biases):
inputs=tf.reshape(X,[-1,max_time,n_inputs])
#lstm_cell=tf.contrib.rnn.core_rnn_cell.BasicLSTMCell(lstm_size)报错 版本问题
from tensorflow.contrib import rnn
lstm_cell = rnn.BasicLSTMCell(lstm_size)
outputs,final_state=tf.nn.dynamic_rnn(lstm_cell,inputs,dtype=tf.float32)
results=tf.nn.softmax(tf.matmul(final_state[1],weights)+biases)#final_state[1]是hidden state
return results
#计算RNN返回结果
prediction=RNN(x,weights,biases)
#交叉熵代价函数
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
#用AdamOptimizer进行优化
train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)
correct_prediction=tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))#cast是进行数据格式转换,把布尔型转为float32类型
with tf.Session() as sess:
#执行初始化
sess.run(tf.global_variables_initializer())
#迭代6个周期
for epoch in range(6):
#每个周期迭代n_batch个batch,每个batch为100
for batch in range(n_batch):
#获得一个batch的数据和标签
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
#通过feed喂到模型中进行训练
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))
|