Tensorflow深度学习笔记(五)--RNN手写数字识别

使用RNN模型在MNIST数据集上进行手写数字识别,通过迭代训练达到97.71%的测试准确率。模型采用基本LSTM单元,利用Adam优化器最小化交叉熵损失。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据集:MNIST
模型:RNN
损失函数:交叉熵


测试结果:
Iter 16, Testing Accuracy= 0.9745
Iter 17, Testing Accuracy= 0.9751
Iter 18, Testing Accuracy= 0.9753
Iter 19, Testing Accuracy= 0.9761
Iter 20, Testing Accuracy= 0.9771


代码如下:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib import rnn


#读取数据
mnist = input_data.read_data_sets('MNIST_data/',one_hot=True)
#设置batch size
batch_size = 50
n_batch = mnist.train.num_examples//batch_size

#定义输入占位符,调整输入数据格式
x = tf.placeholder(tf.float32,shape=[None,784],name='x-input')
y = tf.placeholder(tf.float32,shape=[None,10],name='y-input')
x_input = tf.reshape(x,shape=[-1,28,28])
x_tran = tf.transpose(x_input,[1,0,2])
x_re = tf.reshape(x_tran,[-1,28])




#初始化weight
def weight_variable(shape,name):
    initial = tf.truncated_normal(shape,stddev=0.1)
    return tf.Variable(initial,name=name)

#初始化bias
def bias_variable(shape,name):
    initial = tf.constant(0.1,shape=shape)
    return tf.Variable(initial,name=name)

#初始化隐层参数
w_hiden = weight_variable([28,128],name='w_hiden')
b_hiden = bias_variable([128],name='b_hiden')
#初始化输出层参数
w_output = weight_variable([128,10],name='w_output')
b_output = bias_variable([10],name='b_output')

#计算隐层输出结果
h_output = tf.matmul(x_re,w_hiden) + b_hiden
h_split = tf.split(h_output,28,axis=0)

#lstm计算单元
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(128,forget_bias=1.0,state_is_tuple=True,name='lstm-cell')
#为了节省时间,此处选择一层网络
mul_layer = tf.nn.rnn_cell.MultiRNNCell([lstm_cell]*1,state_is_tuple=True)
lstm_o,_lstm_s = rnn.static_rnn(mul_layer,h_split,dtype=tf.float32)

#输出结果
output = tf.matmul(lstm_o[-1],w_output) + b_output
prediction = tf.nn.softmax(output)

#设置学习率
lr = 1e-4

#交叉熵损失函数
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
train_step = tf.train.AdamOptimizer(lr).minimize(cross_entropy)

#预测结果
predict_result = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(predict_result,tf.float32))

#执行session
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for epoch in range(21):

        for batch in range(n_batch):
            batch_x,batch_y = mnist.train.next_batch(batch_size)
            sess.run(train_step,feed_dict={x:batch_x,y:batch_y})
        test_acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        print ("Iter " + str(epoch) + ", Testing Accuracy= " + str(test_acc))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值