RNN探索(2)之手写数字识别

时间:2022-08-31 14:15:13

这篇博文不介绍基础的RNN理论知识,只是初步探索如何使用Tensorflow,之后会用笔推导RNN的公式和理论,现在时间紧迫所以先使用为主~~

RNN探索(2)之手写数字识别

RNN探索(2)之手写数字识别

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import tensorflow.examples.tutorials.mnist.input_data as input_data
from tensorflow.contrib import rnn mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
trainimgs, trainlabels, testimgs, testlabels \
= mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
ntrain, ntest, dim, nclasses \
= trainimgs.shape[0], testimgs.shape[0], trainimgs.shape[1], trainlabels.shape[1]
print ("MNIST loaded")
dim_input = 28 #28*1
dim_hidden = 128 #28*128
dim_output = 10 #
nsteps = 28
weight = {
"hidden":tf.Variable(tf.random_normal([dim_input,dim_hidden])),
"out" :tf.Variable(tf.random_normal([dim_hidden,dim_output]))
}
biases = {
"hidden":tf.Variable(tf.random_normal([dim_hidden])),
"out" :tf.Variable(tf.random_normal([dim_output]))
} def RNN(_X,_W,_b,_nsteps,_name):
#[batchsize,nsteps*dim_input]-->>[batchsize,nsteps,dim_input]=[num,28,28]
_X = tf.reshape(_X,[-1,28,28])
#-->>[nsteps,batchsize,dim_input]==[28,num,28]
_X = tf.transpose(_X,[1,0,2])
#-->>[nsteps*batchsize,input]==[28*num,28]
_X = tf.reshape(_X,[-1,28])
#这里是共享权重,nsteps个weights全部一样的.
_H = tf.matmul(_X,_W['hidden']) + _b["hidden"]
_Hsplit = tf.split(_H,num_or_size_splits=nsteps,axis=0)
with tf.variable_scope(_name,reuse=tf.AUTO_REUSE):#重复使用参数节约空间,防止报错
#版本更新弃用
#scop.reuse_variables()
#设计一个计算单元
lstm_cell = rnn.BasicLSTMCell(128,forget_bias=1.0)
#版本更新已经弃用
#lstm_cell = rnn_cell.BasicLSTMCell(dim_hidden,forget_bias=1.0)
#利用RNN单元搭建网络,这里用的最简单的,其它以后在说
_LSTM_0,_LSTM_S = rnn.static_rnn(lstm_cell,_Hsplit,dtype=tf.float32)
#版本更新已经弃用
#_LSTM_O, _LSTM_S = tf.nn.rnn(lstm_cell, _Hsplit,dtype=tf.float32)
return tf.matmul(_LSTM_0[-1],_W["out"])+_b["out"]
#使用GPU按需增长模式
config = tf.ConfigProto(allow_soft_placement=True)
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3)
config.gpu_options.allow_growth = True
if __name__== "__main__":
learning_rate = 0.001
x = tf.placeholder(dtype=tf.float32,shape=[None,28*28],name="input_x")
y = tf.placeholder(dtype=tf.float32,shape=[None,10],name="output_y")
pred = RNN(x,weight,biases,nsteps,"basic")
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
accr = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(pred,1),tf.argmax(y,1)),dtype=tf.float32))
init = tf.global_variables_initializer()
print("RNN Already") training_epochs = 50
batch_size = 16
display_step = 1
sess = tf.Session(config=config)
sess.run(init)
print("Start optimization")
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
#total_batch = 100
# Loop over all batches
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Fit training using batch data
feeds = {x: batch_xs, y: batch_ys}
sess.run(optm, feed_dict=feeds)
# Compute average loss
avg_cost += sess.run(cost, feed_dict=feeds) / total_batch
# Display logs per epoch step
if epoch % display_step == 0:
print("Epoch: %03d/%03d cost: %.9f" % (epoch, training_epochs, avg_cost))
feeds = {x: batch_xs, y: batch_ys}
train_acc = sess.run(accr, feed_dict=feeds)
print(" Training accuracy: %.3f" % (train_acc))
feeds = {x: testimgs, y: testlabels}
test_acc = sess.run(accr, feed_dict=feeds)
print(" Test accuracy: %.3f" % (test_acc))
print("Optimization Finished.")

RNN探索(2)之手写数字识别

  • 没有训练结束,使用的GTX1060训练了大概8分钟,如果训练结束感觉应该可以达到97%左右
  • 因为是单层网络,深度不够,也没处理数据~~
  • 这只是简单了解RNN工作流程,和如何用TF操作RNN
  • 以后会慢慢补上~~

参考:

  • 唐迪宇课程,因为版本问题会出现很多代码更新
  • 其它中间忘记记录了,如有侵权请联系博主,抱歉~

RNN探索(2)之手写数字识别的更多相关文章

  1. 5 TensorFlow入门笔记之RNN实现手写数字识别

    ------------------------------------ 写在开头:此文参照莫烦python教程(墙裂推荐!!!) ---------------------------------- ...

  2. keras和tensorflow搭建DNN、CNN、RNN手写数字识别

    MNIST手写数字集 MNIST是一个由美国由美国邮政系统开发的手写数字识别数据集.手写内容是0~9,一共有60000个图片样本,我们可以到MNIST官网免费下载,总共4个.gz后缀的压缩文件,该文件 ...

  3. TensorFlow使用RNN实现手写数字识别

    学习,笔记,有时间会加注释以及函数之间的逻辑关系. # https://www.cnblogs.com/felixwang2/p/9190664.html # https://www.cnblogs. ...

  4. C#中调用Matlab人工神经网络算法实现手写数字识别

    手写数字识别实现 设计技术参数:通过由数字构成的图像,自动实现几个不同数字的识别,设计识别方法,有较高的识别率 关键字:二值化  投影  矩阵  目标定位  Matlab 手写数字图像识别简介: 手写 ...

  5. Android+TensorFlow+CNN+MNIST 手写数字识别实现

    Android+TensorFlow+CNN+MNIST 手写数字识别实现 SkySeraph 2018 Email:skyseraph00#163.com 更多精彩请直接访问SkySeraph个人站 ...

  6. 学习笔记CB009:人工神经网络模型、手写数字识别、多层卷积网络、词向量、word2vec

    人工神经网络,借鉴生物神经网络工作原理数学模型. 由n个输入特征得出与输入特征几乎相同的n个结果,训练隐藏层得到意想不到信息.信息检索领域,模型训练合理排序模型,输入特征,文档质量.文档点击历史.文档 ...

  7. Tensorflow实战 手写数字识别(Tensorboard可视化)

    一.前言 为了更好的理解Neural Network,本文使用Tensorflow实现一个最简单的神经网络,然后使用MNIST数据集进行测试.同时使用Tensorboard对训练过程进行可视化,算是打 ...

  8. kaggle 实战 (1): PCA + KNN 手写数字识别

    文章目录 加载package read data PCA 降维探索 选择50维度, 拆分数据为训练集,测试机 KNN PCA降维和K值筛选 分析k & 维度 vs 精度 预测 生成提交文件 本 ...

  9. 用tensorflow搭建RNN(LSTM)进行MNIST 手写数字辨识

    用tensorflow搭建RNN(LSTM)进行MNIST 手写数字辨识 循环神经网络RNN相比传统的神经网络在处理序列化数据时更有优势,因为RNN能够将加入上(下)文信息进行考虑.一个简单的RNN如 ...

随机推荐

  1. php知识分享

                                                                      PHP 获取ip地址代码汇总                     ...

  2. Android Volley获取json格式的数据

    为了让Android能够快速地访问网络和解析通用的数据格式Google专门推出了Volley库,用于Android系统的网络传输.volley库可以方便地获取远程服务器的图片.字符串.json对象和j ...

  3. psql: 致命错误: 用户 "postgres" Ident 认证失败

    RedHat: 问题: psql -U postgres 时出现:psql: 致命错误:  用户 "postgres" Ident 认证失败 解决: 修改 /var/lib/pgs ...

  4. Python小工具--删除svn文件

    有的时候我们需要删除项目下的svn相关文件,但是SVN会在所有的目录下都创建隐藏文件.svn,手工一个个目录查找然后删除显然比较麻烦.所以这里提供了一个Python小工具用于批量删除svn的相关文件: ...

  5. DbUtility-查询DataTable

    直接上源码 using System; using System.Data; using System.Threading.Tasks; using DbUtility; namespace Test ...

  6. php 解决乱码的通用方法

    一,出现乱码的原因分析 1,保存文件时候,文件有自己的文件编码,就是汉字,或者其他国语言,以什么编码来存储 2,输出的时候,要给内容指定编码,如以网页的形势输入时<meta http-equiv ...

  7. Python错误集

    1-->IndentationError:expected an indented block   >IndentationError: unindent does not match a ...

  8. jsp加java连接数据库,进行信息输入,并进行初步的拦截判断。

    图形大概这样 按照图片要求设计添加新课程界面.(0.5分) 在后台数据库中建立相应的表结构存储课程信息.(0.5分) 实现新课程添加的功能. 要求判断任课教师为王建民.刘立嘉.刘丹.王辉.杨子光五位教 ...

  9. JAVA高并发程序设计笔记

    第二章 Java并行程序基础 1.join()的本质是让调用线程wait()在当前线程的对象上 2.Thread.yiedl()会使当前线程让出CPU 3.volatile保证可见性,无法保证原子性( ...

  10. 转&colon;&sol;&sol;Oracle 单引号转义

    在ORACLE中,单引号有两个作用: 1:字符串是由单引号引用 2:转义. 单引号的使用是就近配对,即就近原则.而在单引号充当转义角色时相对不好理解 1.从第二个单引号开始被视为转义符,如果第二个单引 ...