from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
from tensorflow.python.ops.rnn import dynamic_rnn
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
#设置种子
tf.set_random_seed(777)
#读取数据
mnist = input_data.read_data_sets("MNIST_data")
#定义占位符
x = tf.placeholder(tf.float32,shape=[None,28,28])
y = tf.placeholder(tf.int64,shape=[None])
#建立模型
cells = [tf.contrib.rnn.LSTMCell(num_units=32) for _ in range(2)]
multi_cell = tf.contrib.rnn.MultiRNNCell(cells,state_is_tuple=True)
outputs,states = dynamic_rnn(multi_cell,x,dtype=tf.float32)
#全连接
logits = tf.contrib.layers.fully_connected(outputs[:,-1],num_outputs=10,activation_fn=None)
#定义损失
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,labels=y))
#优化器
optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
#精度
y_pred = tf.argmax(logits,axis=1)
correct_pre = tf.equal(y,y_pred)
accuracy = tf.reduce_mean(tf.cast(correct_pre,tf.float32))
#定义参数
training_epoch = 2
batch_size = 100
#定义会话
sess = tf.Session()
sess.run(tf.global_variables_initializer())
#开始迭代
for epoch in range(training_epoch):
avg_cost = 0
total_batch = int(mnist.train.num_examples/batch_size)
for i in range(total_batch):
batch_x,batch_y = mnist.train.next_batch(batch_size)
batch_x = batch_x.reshape(batch_size,28,28)
l,_ = sess.run([loss,optimizer],feed_dict={x:batch_x,y:batch_y})
avg_cost += l/total_batch
print("epoch:",epoch+1,"acc:",sess.run(accuracy,feed_dict={x:mnist.train.images[:100].reshape(-1,28,28),y:mnist.train.labels[:100]}))
#测试集精度
print("测试集精度:",sess.run(accuracy,feed_dict={x:mnist.test.images[:100].reshape(-1,28,28),y:mnist.test.labels[:100]}))
#随机抽取样本检验
np.random.seed(100)
r = np.random.randint(0,mnist.test.num_examples-1)
print("实际标签:",mnist.test.labels[r])
print("预测值是:",sess.run(tf.argmax(logits,1),feed_dict={x:mnist.test.images[r:r+1].reshape(-1,28,28)}))
RNN-MNIST手写体识别
最新推荐文章于 2022-01-15 14:49:40 发布