TensorFlow+实战Google深度学习框架学习笔记(12)------Mnist识别和卷积神经网络LeNet
一、卷积神经网络的简述
卷积神经网络将一个图像变窄变长。原本【长和宽较大,高较小】变成【长和宽较小,高增加】
卷积过程需要用到卷积核【二维的滑动窗口】【过滤器】,每个卷积核由n*m(长*宽)个小格组成,每个小格都有自己的权重值,
长宽变窄:过滤器的长宽决定的
高度变高:过滤器的个数决定的

输入:55000 × 784 = 28*28
输出:55000 × 10
lenet:两层卷积层(卷积层 + 池化层)、两层全连接层

二、代码:
1、数据集:
下载好Mnist数据集加压到文件夹'MNIST_data’中。加载数据
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets('MNIST_data',one_hot = True)
#打印数据集大小
print('训练集大小:',mnist.train.num_examples)
print('验证集大小:',mnist.validation.num_examples)
print('测试集大小:',mnist.test.num_examples)
#打印样本
print(mnist.train.images[0])
print(mnist.train.labels[0])
2、卷积层:tf.nn.conv2d
(1)过滤器:【维度大小、权重w、偏正b、padding、stride】
设置过滤器的参数:
tf.nn.conv2d(输入矩阵,权重,strides,padding),其中strides的第一个1和最后一个1必须有,中间为输入矩阵尺寸的x和y的大小。padding有两种值,SAME和VALLD。
- input tensor shape:[batch, in_height, in_width, in_channels]
- filter tensor shape:[filter_height, filter_width, in_channels, out_channels]

#w,b
filter_w = tf.get_variable('weight',[5,5,3,16],initializer = tf.truncated_normal_initializer(stddev = 0.1))
filter_b = tf.get_variable('biases',[16],initializer = tf.constant_initializer(0.1)) #卷积的前向传播:将【32,32,3】输入通过 16个 【5,5,3】的过滤器得到【28,28,16】。w :【5,5,3,16】,b:【16】
conv = tf.nn.conv2d(input,filter_w,strides = [1,1,1,1],padding = 'SAME')
# tf.nn.bias_add表示【5,5,3】个数都要加上biases。
bias = tf.nn.bias_add(conv,biases) #结果通过Relu激活函数
actived_conv = tf.nn.relu(bias)
3、池化层:可加快计算速度也可防止过拟合。tf.nn.max_pool
卷积层之间加一个池化层,可缩小矩阵的尺寸,减少全连接层中的参数。
tf.nn.max_pool(传入当前层的节点矩阵,ksize = 池化层过滤器的尺寸,strides,padding),ksize的第一维和最后一维必须为1
实现了最大池化层的前向传播过程,参数和conv2d相似。

4、全部代码:
#加载模块和数据
import tensorflow as tf
from tensorflow.examplesamples.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 biase_variable(shape):
initial = tf.constant(0.1,shape = shape)
return tf.Variable(initial)
def conv2d(x,w):
conv = tf.nn.conv2d(x,w,strides=[1,1,1,1],padding='SAME')
return conv
def max_pool(x):
return tf.nn.max_pool(x,ksize = [1,2,2,1],strides = [1,2,2,1],padding = 'SAME') #训练
def train(mnist):
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(x,[-1,28,28,1]) #前向传播
#layer1
with tf.variable_scope('layer1'):
w = weight_variable([5,5,1,32])
b = biase_variable([32])
conv1 = tf.nn.bias_add(conv2d(x_image,w),b)
relu_conv1 = tf.nn.relu(conv1)
pool1 = max_pool(relu_conv1)
with tf.variable_scope('layer2'):
w = weight_variable([5,5,32,64])
b = biase_variable([64])
conv2 = tf.nn.bias_add(conv2d(pool1,w),b)
relu_conv2 = tf.nn.relu(conv2)
pool2 = max_pool(relu_conv2)
with tf.variable_scope('func1'):
w = weight_variable([7*7*64,1024])
b = biase_variable([1024])
pool2_reshape = tf.reshape(pool2,[-1,7*7*64])
func1 = tf.nn.relu(tf.matmul(pool2_reshape,w) + b)
func1_drop = tf.nn.dropout(func1,keep_prob)
with tf.variable_scope('func2'):
w = weight_variable([1024,10])
b = biase_variable([10])
prediction = tf.nn.softmax(tf.matmul(func1_drop,w) + b) #后向传播
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(prediction),
reduction_indices=[1])) # loss
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) #会话训练
sess = tf.Session()
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
init = tf.initialize_all_variables()
else:
init = tf.global_variables_initializer()
sess.run(init)
for i in range(1000):
batch_x, batch_y = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_x, y: batch_y, keep_prob: 0.5})
if i % 50 == 0:
correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={x: mnist.test.images[:1000], y: mnist.test.labels[:1000], keep_prob: 1})
print(result) if __name__ == '__main__':
train(mnist)
训练结果:迭代结束为95%的准确率。

TensorFlow+实战Google深度学习框架学习笔记(12)------Mnist识别和卷积神经网络LeNet的更多相关文章
- [Tensorflow实战Google深度学习框架]笔记4
本系列为Tensorflow实战Google深度学习框架知识笔记,仅为博主看书过程中觉得较为重要的知识点,简单摘要下来,内容较为零散,请见谅. 2017-11-06 [第五章] MNIST数字识别问题 ...
- TensorFlow+实战Google深度学习框架学习笔记(5)----神经网络训练步骤
一.TensorFlow实战Google深度学习框架学习 1.步骤: 1.定义神经网络的结构和前向传播的输出结果. 2.定义损失函数以及选择反向传播优化的算法. 3.生成会话(session)并且在训 ...
- 1 如何使用pb文件保存和恢复模型进行迁移学习(学习Tensorflow 实战google深度学习框架)
学习过程是Tensorflow 实战google深度学习框架一书的第六章的迁移学习环节. 具体见我提出的问题:https://www.tensorflowers.cn/t/5314 参考https:/ ...
- 学习《TensorFlow实战Google深度学习框架 (第2版) 》中文PDF和代码
TensorFlow是谷歌2015年开源的主流深度学习框架,目前已得到广泛应用.<TensorFlow:实战Google深度学习框架(第2版)>为TensorFlow入门参考书,帮助快速. ...
- TensorFlow实战Google深度学习框架10-12章学习笔记
目录 第10章 TensorFlow高层封装 第11章 TensorBoard可视化 第12章 TensorFlow计算加速 第10章 TensorFlow高层封装 目前比较流行的TensorFlow ...
- TensorFlow实战Google深度学习框架5-7章学习笔记
目录 第5章 MNIST数字识别问题 第6章 图像识别与卷积神经网络 第7章 图像数据处理 第5章 MNIST数字识别问题 MNIST是一个非常有名的手写体数字识别数据集,在很多资料中,这个数据集都会 ...
- TensorFlow实战Google深度学习框架1-4章学习笔记
目录 第1章 深度学习简介 第2章 TensorFlow环境搭建 第3章 TensorFlow入门 第4章 深层神经网络 第1章 深度学习简介 对于许多机器学习问题来说,特征提取不是一件简单的事情 ...
- 《TensorFlow实战Google深度学习框架》笔记——TensorFlow入门
一.Tensorflow计算模型:计算图 计算图是Tensorflow中最基本的一个概念,Tensorflow中的所有计算都被被转化为计算图上的节点. Tensorflow是一个通过计算图的形式来描述 ...
- TensorFlow实战Google深度学习框架-人工智能教程-自学人工智能的第二天-深度学习
自学人工智能的第一天 "TensorFlow 是谷歌 2015 年开源的主流深度学习框架,目前已得到广泛应用.本书为 TensorFlow 入门参考书,旨在帮助读者以快速.有效的方式上手 T ...
随机推荐
- Nginx学习总结(2)——Nginx手机版和PC电脑版网站配置
考虑到网站的在多种设备下的兼容性,有很多网站会有手机版和电脑版两个版本.访问同一个网站URL,当服务端识别出用户使用电脑访问,就打开电脑版的页面,用户如果使用手机访问,则会得到手机版的页面. 1.判断 ...
- Shallow Heap 和 Retained Heap的区别
http://blog.csdn.net/a740169405/article/details/53610689 Shallow Heap 和 Retained Heap的区别 https://i.c ...
- [bzoj3680]吊打XXX_模拟退火
吊打XXX bzoj-3680 题目大意:在平面上给定n个点,每个点有一个权值.请在平面上找出一个点(不一定在这n个点内找)使得这个点到n个点的距离*权值最小,即求这n个点的重心. 注释:$1\le ...
- Anton and Letters
Anton and Letters time limit per test 2 seconds memory limit per test 256 megabytes input standard i ...
- @RequiresPermissions 注解说明
@RequiresAuthentication验证用户是否登录,等同于方法subject.isAuthenticated() 结果为true时.@RequiresUser验证用户是否被记忆,user有 ...
- Activiti的简单入门样例(经典的请假样例)
经典的请假样例: 流程例如以下,首先须要部门经理审批.假设请假天数大于2天,则须要总经理审批,否则HR审批就可以 一:创建maven项目,项目结构例如以下: watermark/2/text/aHR0 ...
- UVA 1201 - Taxi Cab Scheme(二分图匹配+最小路径覆盖)
UVA 1201 - Taxi Cab Scheme 题目链接 题意:给定一些乘客.每一个乘客须要一个出租车,有一个起始时刻,起点,终点,行走路程为曼哈顿距离,每辆出租车必须在乘客一分钟之前到达.问最 ...
- 自己实现的一个 .net 缓存类(原创)
public class CacheContainer { private static Hashtable ht = new Hashtable(); /// <summary> /// ...
- Web进行压力测试的小工具
在Linux下对Web进行压力测试的小工具有很多,比较出名的有AB.虽然AB可以运行在windows下,但对于想简单界面操作的朋友有点不太习惯.其实vs.net也提供压力测试功能但显然显得太重了,在测 ...
- [计蒜客] tsy's number 解题报告 (莫比乌斯反演+数论分块)
interlinkage: https://nanti.jisuanke.com/t/38226 description: solution: 显然$\frac{\phi(j^2)}{\phi(j)} ...