构建多层卷积神经网络时需要多组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手写数字识别-深入的更多相关文章

  1. 基于tensorflow的MNIST手写数字识别(二)--入门篇

    http://www.jianshu.com/p/4195577585e6 基于tensorflow的MNIST手写字识别(一)--白话卷积神经网络模型 基于tensorflow的MNIST手写数字识 ...

  2. 基于TensorFlow的MNIST手写数字识别-初级

    一:MNIST数据集    下载地址 MNIST是一个包含很多手写数字图片的数据集,一共4个二进制压缩文件 分别是test set images,test set labels,training se ...

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

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

  4. Tensorflow之MNIST手写数字识别:分类问题(1)

    一.MNIST数据集读取 one hot 独热编码独热编码是一种稀疏向量,其中:一个向量设为1,其他元素均设为0.独热编码常用于表示拥有有限个可能值的字符串或标识符优点:   1.将离散特征的取值扩展 ...

  5. Tensorflow实现MNIST手写数字识别

    之前我们讲了神经网络的起源.单层神经网络.多层神经网络的搭建过程.搭建时要注意到的具体问题.以及解决这些问题的具体方法.本文将通过一个经典的案例:MNIST手写数字识别,以代码的形式来为大家梳理一遍神 ...

  6. [Python]基于CNN的MNIST手写数字识别

    目录 一.背景介绍 1.1 卷积神经网络 1.2 深度学习框架 1.3 MNIST 数据集 二.方法和原理 2.1 部署网络模型 (1)权重初始化 (2)卷积和池化 (3)搭建卷积层1 (4)搭建卷积 ...

  7. Tensorflow之MNIST手写数字识别:分类问题(2)

    整体代码: #数据读取 import tensorflow as tf import matplotlib.pyplot as plt import numpy as np from tensorfl ...

  8. TensorFlow——MNIST手写数字识别

    MNIST手写数字识别 MNIST数据集介绍和下载:http://yann.lecun.com/exdb/mnist/   一.数据集介绍: MNIST是一个入门级的计算机视觉数据集 下载下来的数据集 ...

  9. 持久化的基于L2正则化和平均滑动模型的MNIST手写数字识别模型

    持久化的基于L2正则化和平均滑动模型的MNIST手写数字识别模型 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献Tensorflow实战Google深度学习框架 实验平台: Tens ...

随机推荐

  1. PHP 经典面试题集

    这篇文章介绍的内容是关于PHP 经典面试题集 PHP 经典面试题集,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下 结合我自己面试情况,面对的一些php面试题列举出来,基本上结合自己的看 ...

  2. Elasticsearch调优篇-慢查询分析笔记

    前言 elasticsearch提供了非常灵活的搜索条件给我们使用,在使用复杂表达式的同时,如果使用不当,可能也会为我们带来了潜在的风险,因为影响查询性能的因素很多很多,这篇笔记主要记录一下慢查询可能 ...

  3. Windows安装EMQ服务器(mqtt)

    先去EMQ官网下载安装包 https://www.emqx.io/downloads#broker 注意:此处一定不能下错成企业版的,不然EMQ会由于缺少企业license无法启动服务 解压到任意路径 ...

  4. 【转】VS2017缺少文件

    在VS工程中,添加c/c++工程中外部头文件及库的基本步骤: 1.添加工程的头文件目录:工程---属性---配置属性---c/c++---常规---附加包含目录:加上头文件存放目录. 2.添加文件引用 ...

  5. [转载] Windows系统批处理延迟方法

    小贴士:方法四 亲测有效,因为当时对于精确度要求不是很高,所以没有具体测试它的精确度.其他方法没有测过,用到的时候再测吧! 批处理延时启动的几个方法 方法一:ping 缺点:时间精度为1秒,不够精确 ...

  6. Sentinel :微服务哨兵

    1. Sentinel 是什么? 随着微服务的流行,服务和服务之间的稳定性变得越来越重要.Sentinel 以流量为切入点,从流量控制.熔断降级.系统负载保护等多个维度保护服务的稳定性. Sentin ...

  7. UGUI源码之Selectable

    Selectable是Button.InputField.Toggle.ScrollBar.Slider.Dropdown的基类. Selectable的继承的类与接口如下: public class ...

  8. python中property和setter装饰器

    property和setter装饰器 作用:调用方法改为调用对象, 比如 : p.set_name()     改为   p.set_name 区别:  前者改变get方法,后者改变set方法 效果图 ...

  9. 深夜话题boot2docker还有那些隐藏MENU

    马克思的博士论文:自由意识的集中表达 --字体我设为5(18pt),你们懂的 总有人埋汰,终于我想起一个负负得正的话题 为什么放在深夜,因为希望看到的人越少越好,深夜是时差党的乐园 本篇作为之前几篇围 ...

  10. 秦皇岛 I 题

    有 n 个数字,你可以挑选其中任意个数字代表一个背包的体积,其余的数字表示的物品的体积,所挑选的背包必选完全装满,询问最终的方案数 思路分析 : 定义dp[i] 表示挑选 i 状态下的物品的方案数,f ...