一、卷积神经网络的简述

卷积神经网络将一个图像变窄变长。原本【长和宽较大,高较小】变成【长和宽较小,高增加】

卷积过程需要用到卷积核【二维的滑动窗口】【过滤器】,每个卷积核由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])
训练集大小: 55000
验证集大小: 5000
测试集大小: 10000
x:[0.         0.         0.         0.         0.         0.……0.9960785,……0]
y:[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]

2、卷积层:tf.nn.conv2d

(1)过滤器:【维度大小、权重w、偏正b、padding、stride】

设置过滤器的参数:

tf.nn.conv2d(输入矩阵,权重,strides,padding),其中strides的第一个1和最后一个1必须有,中间为输入矩阵尺寸的x和y的大小。padding有两种值,SAME和VALLD。

  1. input tensor shape:[batch, in_height, in_width, in_channels]
  2. 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的更多相关文章

  1. [Tensorflow实战Google深度学习框架]笔记4

    本系列为Tensorflow实战Google深度学习框架知识笔记,仅为博主看书过程中觉得较为重要的知识点,简单摘要下来,内容较为零散,请见谅. 2017-11-06 [第五章] MNIST数字识别问题 ...

  2. TensorFlow+实战Google深度学习框架学习笔记(5)----神经网络训练步骤

    一.TensorFlow实战Google深度学习框架学习 1.步骤: 1.定义神经网络的结构和前向传播的输出结果. 2.定义损失函数以及选择反向传播优化的算法. 3.生成会话(session)并且在训 ...

  3. 1 如何使用pb文件保存和恢复模型进行迁移学习(学习Tensorflow 实战google深度学习框架)

    学习过程是Tensorflow 实战google深度学习框架一书的第六章的迁移学习环节. 具体见我提出的问题:https://www.tensorflowers.cn/t/5314 参考https:/ ...

  4. 学习《TensorFlow实战Google深度学习框架 (第2版) 》中文PDF和代码

    TensorFlow是谷歌2015年开源的主流深度学习框架,目前已得到广泛应用.<TensorFlow:实战Google深度学习框架(第2版)>为TensorFlow入门参考书,帮助快速. ...

  5. TensorFlow实战Google深度学习框架10-12章学习笔记

    目录 第10章 TensorFlow高层封装 第11章 TensorBoard可视化 第12章 TensorFlow计算加速 第10章 TensorFlow高层封装 目前比较流行的TensorFlow ...

  6. TensorFlow实战Google深度学习框架5-7章学习笔记

    目录 第5章 MNIST数字识别问题 第6章 图像识别与卷积神经网络 第7章 图像数据处理 第5章 MNIST数字识别问题 MNIST是一个非常有名的手写体数字识别数据集,在很多资料中,这个数据集都会 ...

  7. TensorFlow实战Google深度学习框架1-4章学习笔记

    目录 第1章 深度学习简介 第2章 TensorFlow环境搭建 第3章 TensorFlow入门 第4章 深层神经网络   第1章 深度学习简介 对于许多机器学习问题来说,特征提取不是一件简单的事情 ...

  8. 《TensorFlow实战Google深度学习框架》笔记——TensorFlow入门

    一.Tensorflow计算模型:计算图 计算图是Tensorflow中最基本的一个概念,Tensorflow中的所有计算都被被转化为计算图上的节点. Tensorflow是一个通过计算图的形式来描述 ...

  9. TensorFlow实战Google深度学习框架-人工智能教程-自学人工智能的第二天-深度学习

    自学人工智能的第一天 "TensorFlow 是谷歌 2015 年开源的主流深度学习框架,目前已得到广泛应用.本书为 TensorFlow 入门参考书,旨在帮助读者以快速.有效的方式上手 T ...

随机推荐

  1. CodeForces - 9B - Running Student

    先上题目: B. Running Student time limit per test 1 second memory limit per test 64 megabytes   And again ...

  2. [bzoj2600][Ioi2011]ricehub_二分

    ricehub bzoj-2600 Ioi-2011 题目大意:在数轴上有r块稻田,稻田坐标为整数.计划建造一个米仓,使得它可以收取尽量多的稻米.米仓的坐标仍需为整数.每一块权值为val的稻田距离米仓 ...

  3. Spring MVC-表单(Form)标签-密码框(Password)示例(转载实践)

    以下内容翻译自:https://www.tutorialspoint.com/springmvc/springmvc_password.htm 说明:示例基于Spring MVC 4.1.6. 以下示 ...

  4. (转载)Html解析工具Jsoup

    jsoup 简介Java 程序在解析 HTML 文档时,相信大家都接触过 htmlparser 这个开源项目,我曾经在 IBM DW 上发表过两篇关于 htmlparser 的文章,分别是:从 HTM ...

  5. pagex,screenx,clientx的差别

    screenX:參照物为电脑的屏幕左上角,距离电脑屏幕的水平距离 clientX:參照物是内容区域左上角,距离内容区域左上角的水平距离,会随着滚动栏的移动而移动 pageX:參照物也是内容区域的左上角 ...

  6. visual studio 开发工具SVN集成工具,测试可用,成功集成

    使用说明:https://www.xiazaiba.com/html/24864.html 下载地址:点击下载集成插件

  7. sikuli_ide打开提示没有对应的javaw

    对于sikuli,需要安装32位的jdk且不能高于1.7的版本 对于64位系统的C盘,Program Files文件夹是64位的,Program File(x86)文件夹是32位的 需要安装一个32位 ...

  8. 【cl】子查询应用场景

    有推荐人/没有推荐人的 recommender_id is null / is not null 谁是推荐人=他的id是别人的recommender_id=某个人的recommender_id是他的i ...

  9. 基于ArcGIS Flex API实现动态标绘(1.0)

    标绘作为一种数据展示形式,在多个行业都有需求. 基于ArcGIS Flex API(3.6)实现标绘API,当前版本号1.0 alpha,支持经常使用几种标绘符号,包含: 圆弧.曲线.圆形.椭圆.弓形 ...

  10. 总结一下这几节Java课的...重点!!!

    1.定义一个Person类,包含两个私有的属性(name.age).一个含参的方法setValue(int age,String name).一个不含参方法setValue()和一个普通方法tell( ...