参考视频:https://www.bilibili.com/video/av20542427?p=23
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets('MNIST_data',one_hot=True)
#初始化权值
def weight_variable(shape):
initial = tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(initial)
#初始化偏量
def bias_variable(shape):
initial = tf.constant(0.1,shape=shape)
return tf.Variable(initial)
n_inputs = 28
max_time = 28
lstm_size = 100
n_classes = 10
batch_size = 4
lr = 0.1
n_batch = mnist.train.num_examples // batch_size
#定义两个占位符,784是28*28的size,把图像拉长为784的向量,None是批次
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
weights = weight_variable([lstm_size,n_classes])
biases = bias_variable([n_classes])
def RNN(X,weight,biases):
inputs = tf.reshape(X,[-1,max_time,n_inputs])
lstm_cell = tf.nn.rnn_cell.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)
return results
prediction = RNN(x,weights,biases)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
train = tf.train.AdadeltaOptimizer(lr).minimize(loss)
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
acc = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
#每一个epoch都要把所有的图片喂到网络里面
for epoch in range(11):
#每次喂多少个图片
for k in range(n_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
sess.run(train,feed_dict={x:batch_xs,y:batch_ys})
#train_accuracy = sess.run(acc,feed_dict={x:mnist.train.images,y:mnist.train.labels,keep_prob:1.0})
#print("iter = " + str(epoch) + ",train_acc = " + str(train_accuracy))
#每个epoch结束看下准确率
#if epoch%10 ==0:
test_accuracy = sess.run(acc,feed_dict={x:mnist.test.images,y:mnist.test.labels})
print("iter = " + str(epoch) + ",test_acc = " + str(test_accuracy))
运行结果: