tensorflow 15-RNN(lstm+mnist实现)

本文介绍了一种使用长短期记忆网络(LSTM)进行MNIST手写数字识别的方法。通过定义网络结构、训练过程和评估准确性,展示了如何在MNIST数据集上实现高效的手写数字识别。

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

参考视频: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))

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值