基于卷积神经网络的手写数字识别分类(Tensorflow)
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import os
%matplotlib inline
import matplotlib.pyplot as plt
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
class ConvModel(object):
def __init__(self, lr, batch_size, iter_num):
self.lr = lr
self.batch_size = batch_size
self.iter_num = iter_num
self.X_flat = tf.placeholder(tf.float32, [None, 784])
self.X = tf.reshape(self.X_flat, [-1, 28, 28, 1]) # 本次要用卷积进行运算,所以使用2维矩阵。从这个角度讲,利用了更多的位置信息。
self.y = tf.placeholder(tf.float32, [None, 10])
self.dropRate = tf.placeholder(tf.float32)
conv1 = tf.layers.conv2d(self.X, 32, 5, padding='same', activation=tf.nn.relu,
kernel_initializer=tf.truncated_normal_initializer(stddev=0.1, seed=0),
bias_initializer=tf.constant_initializer(0.1))
conv1 = tf.layers.max_pooling2d(conv1 , 2,2)
conv2 = tf.layers.conv2d(conv1, 64, 5, padding='same', activation=tf.nn.relu,
kernel_initializer=tf.truncated_normal_initializer(stddev=0.1, seed=0),
bias_initializer=tf.constant_initializer(0.1))
pool1 = tf.layers.max_pooling2d(conv2, 2,2)
flatten = tf.reshape(pool1 , [-1, 7*7*64])
dense1 = tf.layers.dense(flatten, 1024, activation=tf.nn.relu, use_bias=True,
kernel_initializer=tf.truncated_normal_initializer(stddev=0.1, seed=0),
bias_initializer=tf.constant_initializer(0.1))
dense1_ = tf.nn.dropout(dense1, self.dropRate)
dense2 = tf.layers.dense(dense1_, 10, activation=tf.nn.relu, use_bias=True,
kernel_initializer=tf.truncated_normal_initializer(stddev=0.1, seed=0),
bias_initializer=tf.constant_initializer(0.1))
self.loss = tf.losses.softmax_cross_entropy(onehot_labels=self.y, logits=dense2)
self.train_step = tf.train.AdamOptimizer(1e-4).minimize(self.loss )
# 用于模型训练
self.correct_prediction = tf.equal(tf.argmax(self.y, axis=1), tf.argmax(dense2, axis=1))
self.accuracy = tf.reduce_mean(tf.cast(self.correct_prediction, tf.float32))
# 用于保存训练好的模型
self.saver = tf.train.Saver()
def train(self):
with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) # 先初始化所有变量。
for i in range(self.iter_num):
batch_x, batch_y = mnist.train.next_batch(self.batch_size) # 读取一批数据
loss, _= sess.run([self.loss, self.train_step],
feed_dict={self.X_flat: batch_x, self.y: batch_y, self.dropRate: 0.5}) # 每调用一次sess.run,就像拧开水管一样,所有self.loss和self.train_step涉及到的运算都会被调用一次。
if i%1000 == 0:
train_accuracy = sess.run(self.accuracy, feed_dict={self.X_flat: batch_x, self.y: batch_y, self.dropRate: 1.}) # 把训练集数据装填进去
test_x, test_y = mnist.test.next_batch(self.batch_size)
test_accuracy = sess.run(self.accuracy, feed_dict={self.X_flat: test_x, self.y: test_y, self.dropRate: 1.}) # 把测试集数据装填进去
print ('iter\t%i\tloss\t%f\ttrain_accuracy\t%f\ttest_accuracy\t%f' % (i,loss,train_accuracy,test_accuracy))
self.saver.save(sess, 'model/mnistModel') # 保存模型
def test(self):
with tf.Session() as sess:
self.saver.restore(sess, 'model/mnistModel')
Accuracy = []
for i in range(int(10000/self.batch_size)):
test_x, test_y = mnist.test.next_batch(self.batch_size)
test_accuracy = sess.run(self.accuracy, feed_dict={self.X_flat: test_x, self.y: test_y, self.dropRate: 1.})
Accuracy.append(test_accuracy)
print('==' * 15)
print( 'Test Accuracy: ', np.mean(np.array(Accuracy)) )
model = ConvModel(0.001, 64, 30000) # 学习率为0.001,每批传入64张图,训练30000次
model.train() # 训练模型
model.test() # 预测
基于卷积神经网络的手写数字识别分类(Tensorflow)的更多相关文章
- TensorFlow卷积神经网络实现手写数字识别以及可视化
边学习边笔记 https://www.cnblogs.com/felixwang2/p/9190602.html # https://www.cnblogs.com/felixwang2/p/9190 ...
- 卷积神经网络CNN 手写数字识别
1. 知识点准备 在了解 CNN 网络神经之前有两个概念要理解,第一是二维图像上卷积的概念,第二是 pooling 的概念. a. 卷积 关于卷积的概念和细节可以参考这里,卷积运算有两个非常重要特性, ...
- TensorFlow(十):卷积神经网络实现手写数字识别以及可视化
上代码: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = inpu ...
- 莫烦pytorch学习笔记(八)——卷积神经网络(手写数字识别实现)
莫烦视频网址 这个代码实现了预测和可视化 import os # third-party library import torch import torch.nn as nn import torch ...
- BP神经网络的手写数字识别
BP神经网络的手写数字识别 ANN 人工神经网络算法在实践中往往给人难以琢磨的印象,有句老话叫“出来混总是要还的”,大概是由于具有很强的非线性模拟和处理能力,因此作为代价上帝让它“黑盒”化了.作为一种 ...
- 利用c++编写bp神经网络实现手写数字识别详解
利用c++编写bp神经网络实现手写数字识别 写在前面 从大一入学开始,本菜菜就一直想学习一下神经网络算法,但由于时间和资源所限,一直未展开比较透彻的学习.大二下人工智能课的修习,给了我一个学习的契机. ...
- [Python]基于CNN的MNIST手写数字识别
目录 一.背景介绍 1.1 卷积神经网络 1.2 深度学习框架 1.3 MNIST 数据集 二.方法和原理 2.1 部署网络模型 (1)权重初始化 (2)卷积和池化 (3)搭建卷积层1 (4)搭建卷积 ...
- 第二节,TensorFlow 使用前馈神经网络实现手写数字识别
一 感知器 感知器学习笔记:https://blog.csdn.net/liyuanbhu/article/details/51622695 感知器(Perceptron)是二分类的线性分类模型,其输 ...
- TensorFlow.NET机器学习入门【5】采用神经网络实现手写数字识别(MNIST)
从这篇文章开始,终于要干点正儿八经的工作了,前面都是准备工作.这次我们要解决机器学习的经典问题,MNIST手写数字识别. 首先介绍一下数据集.请首先解压:TF_Net\Asset\mnist_png. ...
随机推荐
- Visualise the Argyris basis functions
""" Author: kinnala Visualise the Argyris basis functions. """ from sk ...
- day04_雷神_函数
#day04 1.函数 1.1函数传参 函数定义的时候是形参:函数执行的时候是实参 实参: 位置参数.关键字参数.混合参数 位置参数:位置一一对应 关键字参数: 可以位置不对应 混合参数:关键字参数要 ...
- unigui作中间件使用
unigui作中间件使用 可返回string或者tstream数据. 如果返回JSON字符,则UNIGUI就是REST 中间件. procedure TUniServerModule.UniGUISe ...
- linux下java版本管理工具jenv使用介绍
不同的项目使用的java版本不同,每次切换时都需要手动去修改java的环境变量,麻烦至极. jenv可以管理java版本,轻松实现管理多个java的问题. 一.下载jenv $ git clone h ...
- 语音识别功能_微信小程序代办清单任务
最近想给自己的代办清单任务微信小程序想加个语音识别识别功能,废话不多说,直接说重点,语音识别使用的是百度语音识别api,因为微信小程序的录音输入文件目前只能是mp3或aac 但是百度语音识别不支持这两 ...
- .net图表之ECharts随笔05-不同01的语法步骤
找了好久,一直没找到可用的热力图heatmap.js. 应该说,使用01中的语法一直都无法实现热力图.只能说我太菜了... 现在急于求成,我找了另一种语法来调用ECharts.此种语法的js文件集是从 ...
- [leetcode.com]算法题目 - Pascal's Triangle
Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,Retur ...
- 【UML】:类图
1 实线/虚线 + 三角空心箭头: 继承extends:实线,三角空心箭头指向父类,子类指向父类,子类 is a 父类. 实现implements:虚线,三角空心箭头指向接口,类指向接口,类 实现 ...
- JavaScript 的 Async\/Await 完胜 Promise 的六
参考:http://www.10tiao.com/html/558/201705/2650964601/1.html Node 现在从版本 7.6 开始就支持 async/await 了. 简介: A ...
- Python之tkinter中的askyescancel窗口返回值
if messagebox.askokcancel(title="确认取消",message="您确认注册该账号吗?"): messagebox.showinf ...