基于TensorFlow的MNIST手写数字识别-深入
构建多层卷积神经网络时需要多组W和偏移项b,我们封装2个方法来产生W和b
初级MNIST中用0初始化W和b,这里用噪声初始化进行对称打破,防止产生梯度0,同时用一个小的正值来初始化b避免dead neurons。
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)
tf.truncated_normal()返回truncated normal distribution产生的随机值
def truncated_normal(shape,
mean=0.0,
stddev=1.0,
dtype=dtypes.float32,
seed=None,
name=None):
stddev:为标准差
mean:为均值
Convolution and Pooling(卷积和池化)
TensorFlow使得convolution和pooling operations具有更多的灵活性,我们怎么处理boundaries,stride size是多少,
这里stride用1,并用0填充使得输入和输出的大小相同。
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
卷积函数:
def conv2d(input, filter, strides, padding, use_cudnn_on_gpu=True, data_format="NHWC", name=None):
data_format:string变量,值有 "NHWC", "NCHW"。
默认为 "NHWC"表示 [batch, height, width, channels]
input:要求为一个4-D Tensor,维度顺序与data_format一样,
shape为[batch, in_height, in_width, in_channels]
类型为float32或half
filter:要求为一个4-D Tensor,维度顺序与data_format一样,
shape为[filter_height, filter_width, in_channels, out_channels]
类型与input一样 【 相当于卷积核 】
strides: A list of `ints`或1-D tensor of length 4。对应于input中每一维的滑动窗口
padding:string类型,变量值可取"SAME", "VALID",表示不同的卷积方式
SAME:采用填充的方式
VALID:采用丢弃的方式 具体含义请参考tensorflow conv2d的padding解释以及参数解释
【TensorFlow】tf.nn.conv2d是怎样实现卷积的?
此函数做了哪些事?
1 将filter reshape成2维 [filter_height * filter_weight * in_channels, output_channels]
2 从input中提取image patches,形成虚拟 tensor [batch, out_height, out_width, filter_height * filter_width * in_channels]
3 对于每个batch,右乘 filter matrix和image patch vector
示例: output[b, i, j, k] =
sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q] *
filter[di, dj, q, k] Must have `strides[0] = strides[3] = 1`. For the most common case of the same
horizontal and vertices strides, `strides = [1, stride, stride, 1]`.
用一个例子来说明:
input的维度为[2, 5, 5, 4]表示batch_size为2, 图片是5 * 5, 输入通道数为 4,
filter的维度为[3, 3, 4, 2]表示卷积核大小为3 * 3,输入通道数为4, 输出通道数为 2
步长为1,padding方式选用VALID
import tensorflow as tf input = tf.Variable(tf.random_normal([2, 5, 5, 4]))
filter = tf.Variable(tf.random_normal([3, 3, 4, 2]))
op = tf.nn.conv2d(input, filter, strides=[1, 1, 1, 1], padding='VALID')
sess = tf.InteractiveSession()
initializer = tf.global_variables_initializer()
sess.run(initializer)
print(op.shape)
print(sess.run(op))
输出:[batch_size, out_height, out_width, out_channels]

将VALID改为SAME,输出如下:

池化:
pooling通常在convolution 后面,降低卷积层输出的特征向量。
包括max_pool和mean_pool,先介绍max_pool
def max_pool(value, ksize, strides, padding, data_format="NHWC", name=None):
参数介绍:
value:输入通常是feature map(卷积层的输出),依然是一个4-D tensor [batch_size, height, width, channels]
ksize:池化窗口大小,对应value的每一维。一般不在batch_size和channels上池化,所以这2个维度上一般设为1
strides:和卷积类似,窗口在每一个维度上的滑动的步长
padding:和卷积类似,可以取 VALID、SAME
例子说明:
import tensorflow as tf
input = tf.Variable(tf.random_normal([3, 7, 7, 2]))
op = tf.nn.max_pool(input, ksize=[1, 2, 2, 1], strides=[1, 1, 1, 1], padding='VALID')
with tf.Session()as sess:
sess.run(tf.global_variables_initializer())
re = sess.run(op)
print(op.shape)
print(re)
输出:

以上分别是卷积和池化的介绍,下面开始卷积神经网络的构建。
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
x = tf.placeholder(tf.float32, shape=(None, 784))
y_ = tf.placeholder(tf.float32, shape=(None, 10))
分别是数据集的下载,以及x,y_的占位
第一层卷积:
卷积会为每5 * 5 patch计算32维的feature
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1, 28, 28, 1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
x_image将x reshape为4-D tensor
max_pool操作将图片size缩为14 * 14
第二层卷积:
为构建深层网络,我们要堆叠多个这种类型的层。第二层每个5 * 5patch有64个feature。
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
现在图片size为7 * 7
密集连接层
# 密集连接层
W_fcl = weight_variable([7*7*64, 1024])
b_fcl = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fcl = tf.nn.relu(tf.matmul(h_pool2_flat, W_fcl) + b_fcl)
全连接层有1024个神经元,用于处理整个图片
Dropout
请参考理解dropout
为减少过拟合,我们在输出之前应用Dropout,创建一个占位符表示Dropout期间神经元的输出被保留的概率。一般我们可以在training期间打开Dropout,test期间关闭Dropout。
TensorFlow的tf.nn.dropout可以自动缩放神经元的输出并屛蔽它们。
#Dropout层
keep_prob = tf.placeholder(tf.float32)
h_fcl_drop = tf.nn.dropout(h_fcl, keep_prob)
输出层
#输出层
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.matmul(h_fcl_drop, W_fc2) + b_fc2
Train and Evaluate the Model
本节的模型与初级里面的一层softmax网络模型相比有以下不同:
1:用sophisticated ADAM optimizer代替梯度下降法进行优化
2:feed_dict中包含keep_prob来控制丢弃的概率
3:training过程中,每100次迭代输出一次日志
运行:
#loss
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_conv, labels=y_))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) #eval
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) #run
with tf.Session()as sess:
sess.run(tf.global_variables_initializer())
for i in range(20000):
batch = mnist.train.next_batch(50)
#train accuracy
if i % 100 == 0:
train_accuracy = sess.run(accuracy, feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
print('step %d,training accuracy %g' % (i, train_accuracy))
sess.run(train_step, feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
#test accuracy
print('test accuracy %g' % sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
最终test set上的准确率为0.992
完整代码:
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
x = tf.placeholder(tf.float32, shape=(None, 784))
y_ = tf.placeholder(tf.float32, shape=(None, 10)) 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) def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # 第一层卷积
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1, 28, 28, 1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1) # 第二层卷积
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2) # 密集连接层
W_fcl = weight_variable([7*7*64, 1024])
b_fcl = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fcl = tf.nn.relu(tf.matmul(h_pool2_flat, W_fcl) + b_fcl) # Dropout层
keep_prob = tf.placeholder(tf.float32)
h_fcl_drop = tf.nn.dropout(h_fcl, keep_prob) # 输出层
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.matmul(h_fcl_drop, W_fc2) + b_fc2 # loss
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y_conv, labels=y_))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) # eval
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # run
with tf.Session()as sess:
sess.run(tf.global_variables_initializer())
for i in range(20000):
batch = mnist.train.next_batch(50)
# train accuracy
if i % 100 == 0:
train_accuracy = sess.run(accuracy, feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
print('step %d,training accuracy %g' % (i, train_accuracy))
sess.run(train_step, feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
# test accuracy
print('test accuracy %g' % sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
运行结果:
基于TensorFlow的MNIST手写数字识别-深入的更多相关文章
- 基于tensorflow的MNIST手写数字识别(二)--入门篇
http://www.jianshu.com/p/4195577585e6 基于tensorflow的MNIST手写字识别(一)--白话卷积神经网络模型 基于tensorflow的MNIST手写数字识 ...
- 基于TensorFlow的MNIST手写数字识别-初级
一:MNIST数据集 下载地址 MNIST是一个包含很多手写数字图片的数据集,一共4个二进制压缩文件 分别是test set images,test set labels,training se ...
- Android+TensorFlow+CNN+MNIST 手写数字识别实现
Android+TensorFlow+CNN+MNIST 手写数字识别实现 SkySeraph 2018 Email:skyseraph00#163.com 更多精彩请直接访问SkySeraph个人站 ...
- Tensorflow之MNIST手写数字识别:分类问题(1)
一.MNIST数据集读取 one hot 独热编码独热编码是一种稀疏向量,其中:一个向量设为1,其他元素均设为0.独热编码常用于表示拥有有限个可能值的字符串或标识符优点: 1.将离散特征的取值扩展 ...
- Tensorflow实现MNIST手写数字识别
之前我们讲了神经网络的起源.单层神经网络.多层神经网络的搭建过程.搭建时要注意到的具体问题.以及解决这些问题的具体方法.本文将通过一个经典的案例:MNIST手写数字识别,以代码的形式来为大家梳理一遍神 ...
- [Python]基于CNN的MNIST手写数字识别
目录 一.背景介绍 1.1 卷积神经网络 1.2 深度学习框架 1.3 MNIST 数据集 二.方法和原理 2.1 部署网络模型 (1)权重初始化 (2)卷积和池化 (3)搭建卷积层1 (4)搭建卷积 ...
- Tensorflow之MNIST手写数字识别:分类问题(2)
整体代码: #数据读取 import tensorflow as tf import matplotlib.pyplot as plt import numpy as np from tensorfl ...
- TensorFlow——MNIST手写数字识别
MNIST手写数字识别 MNIST数据集介绍和下载:http://yann.lecun.com/exdb/mnist/ 一.数据集介绍: MNIST是一个入门级的计算机视觉数据集 下载下来的数据集 ...
- 持久化的基于L2正则化和平均滑动模型的MNIST手写数字识别模型
持久化的基于L2正则化和平均滑动模型的MNIST手写数字识别模型 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献Tensorflow实战Google深度学习框架 实验平台: Tens ...
随机推荐
- 「洛谷P1262」间谍网络 解题报告
P1262 间谍网络 题目描述 由于外国间谍的大量渗入,国家安全正处于高度的危机之中.如果A间谍手中掌握着关于B间谍的犯罪证据,则称A可以揭发B.有些间谍收受贿赂,只要给他们一定数量的美元,他们就愿意 ...
- 「洛谷P1231」教辅的组成 解题报告
P1231 教辅的组成 题目背景 滚粗了的HansBug在收拾旧语文书,然而他发现了什么奇妙的东西. 题目描述 蒟蒻HansBug在一本语文书里面发现了一本答案,然而他却明明记得这书应该还包含一份练习 ...
- Redis系列之----Redis的数据类型及使用场景
Redis是一个开源的.高性能的.基于键值对的缓存与存储系统,能够提供多种不同的键值数据类型来适应不同场景下的缓存和存储需求. Redis中所有的数据都存储在内存中,因此读写速度非常快,相 ...
- 变量键盘读取、数组与宣告:read,array,declare
1.read 2.declare/typeset 宣告变量的类型 3.数组(array)变量类型 4.与文件系统及程序的限制关系:ulimit 限制用户的某些系统资源,包括,可以开启的文件的数量,可以 ...
- vue 路由模块化
第一. 在 router 文件夹下 新建个个模块的文件夹,存放对应的路由js文件 如图1: 第二.修改router文件夹下的index.js 如图2 三.在main.js 修改如下代码 图3
- 恕我直言,牛逼哄哄的MongoDB你可能只会30%
MongoDB闪亮登场 自我介绍 MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关系数据库 ...
- Webpack实战(一):Webpack打包工具安装及参数配置
为什么要模块化 javascript跟其他开发语言有很多的区别,其中一个就是没有模块化概念,如果一个项目中有多个js文件,我们只能通过script标签引入的方式,把一个个js文件插入到页面,这种做法会 ...
- 19南京网络赛A 扫描线
题目链接:https://nanti.jisuanke.com/t/41298 扫描线的简单题,题目难在找宫殿的价值(°ー°"),比赛时将近100多行代码找价值,纯模拟,看到题解哭了. 存下 ...
- poj-1753题题解思路
今天天气很好! 首先题意是这样的:: 翻盖游戏是在一个长方形的4x4场上进行的,其16个方格中的每一个都放置了双面的棋子.每一块的一边是白色的,另一边是黑色的,每一块都是躺着的,要么是黑色的,要么是白 ...
- NOI2019滚粗记
Day -15 期末考完了,爆炸爆炸,就连数学和物理都错了好多傻*错误QwQ 哎呀管他的,NOI我来了! 跑到广附集训来了23333 Day -14 -- -2 做题,听题,哇和一群队爷在一个教室,真 ...