RNN-MNIST手写体识别

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)}))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值