环境:tensorflow 1.1 , python 3 , matplotlib 2.02
"""
tensorflow 1.1
python 3
matplotlib 2.02
"""
import tensorflow as tf
import input_data
import numpy as np
import matplotlib.pyplot as plt
tf.set_random_seed(100)
np.random.seed(100)
BATCH_SIZE = 64
TIME_STEP = 28
INPUT_SIZE = 28
learning_rate = 0.01
mnist = input_data.read_data_sets('mnist/',one_hot=True)
test_x = mnist.test.images[:2000]
test_y = mnist.test.labels[:2000]
plt.imshow(mnist.test.images[3].reshape((28,28)))
plt.title('the picture is %i' %np.argmax(mnist.test.labels[3]),fontdict={'size':16,'color':'red'})
plt.show()
xs = tf.placeholder(tf.float32,[None,TIME_STEP*INPUT_SIZE])
ys = tf.placeholder(tf.int32,[None,10])
x = tf.reshape(xs,[-1,TIME_STEP,INPUT_SIZE])
rnn_cell = tf.contrib.rnn.BasicLSTMCell(num_units=64)
outputs,states = tf.nn.dynamic_rnn(rnn_cell,x,initial_state=None,dtype=tf.float32,time_major=False)
output = tf.layers.dense(outputs[:,-1,:],10)
loss = tf.losses.softmax_cross_entropy(onehot_labels=ys,logits=output)
train = tf.train.AdamOptimizer(learning_rate).minimize(loss)
accuracy = tf.metrics.accuracy(labels=tf.argmax(ys,axis=1),predictions=tf.argmax(output,axis=1))[1]
with tf.Session() as sess:
init = tf.group(tf.global_variables_initializer(),tf.local_variables_initializer())
sess.run(init)
for step in range(1000):
batch_x,batch_y = mnist.train.next_batch(BATCH_SIZE)
_,c = sess.run([train,loss],feed_dict={xs:batch_x,ys:batch_y})
if step % 100 == 0:
acc = sess.run(accuracy,feed_dict={xs:test_x,ys:test_y})
print('= = = = = = > > > > > >','epoch: ',int(step/100),'train loss : %.4f' %c,'test accuracy: %.3f' %acc)
结果
![这里写图片描述](https://img-blog.csdn.net/20170707111500358?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc3pqX2h1aHU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
![这里写图片描述](https://img-blog.csdn.net/20170707111517512?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc3pqX2h1aHU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)