mnist的卷积神经网络例子和上一篇博文中的神经网络例子大部分是相同的。但是CNN层数要多一些,网络模型需要自己来构建。

程序比较复杂,我就分成几个部分来叙述。

首先,下载并加载数据:

import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)     #下载并加载mnist数据
x = tf.placeholder(tf.float32, [None, 784])                        #输入的数据占位符
y_actual = tf.placeholder(tf.float32, shape=[None, 10])            #输入的标签占位符

定义四个函数,分别用于初始化权值W,初始化偏置项b, 构建卷积层和构建池化层。

#定义一个函数,用于初始化所有的权值 W
def weight_variable(shape):initial = tf.truncated_normal(shape, stddev=0.1)return tf.Variable(initial)#定义一个函数,用于初始化所有的偏置项 b
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(x):return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')

接下来构建网络。整个网络由两个卷积层(包含激活层和池化层),一个全连接层,一个dropout层和一个softmax层组成。

#构建网络
x_image = tf.reshape(x, [-1,28,28,1])         #转换输入数据shape,以便于用于网络中
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)     #第一个卷积层
h_pool1 = max_pool(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(h_conv2)                                   #第二个池化层

W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])              #reshape成向量
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)    #第一个全连接层

keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)                  #dropout层

W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_predict=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)   #softmax层

网络构建好后,就可以开始训练了。

cross_entropy = -tf.reduce_sum(y_actual*tf.log(y_predict))     #交叉熵
train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy)    #梯度下降法
correct_prediction = tf.equal(tf.argmax(y_predict,1), tf.argmax(y_actual,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))                 #精确度计算
sess=tf.InteractiveSession()
sess.run(tf.initialize_all_variables())
for i in range(20000):batch = mnist.train.next_batch(50)if i%100 == 0:                  #训练100次,验证一次train_acc = accuracy.eval(feed_dict={x:batch[0], y_actual: batch[1], keep_prob: 1.0})print 'step %d, training accuracy %g'%(i,train_acc)train_step.run(feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 0.5})test_acc=accuracy.eval(feed_dict={x: mnist.test.images, y_actual: mnist.test.labels, keep_prob: 1.0})
print "test accuracy %g"%test_acc

Tensorflow依赖于一个高效的C++后端来进行计算。与后端的这个连接叫做session。一般而言,使用TensorFlow程序的流程是先创建一个图,然后在session中启动它。

这里,我们使用更加方便的InteractiveSession类。通过它,你可以更加灵活地构建你的代码。它能让你在运行图的时候,插入一些计算图,这些计算图是由某些操作(operations)构成的。这对于工作在交互式环境中的人们来说非常便利,比如使用IPython。

训练20000次后,再进行测试,测试精度可以达到99%。

完整代码:

# -*- coding: utf-8 -*-
"""
Created on Thu Sep  8 15:29:48 2016@author: root
"""
import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)     #下载并加载mnist数据
x = tf.placeholder(tf.float32, [None, 784])                        #输入的数据占位符
y_actual = tf.placeholder(tf.float32, shape=[None, 10])            #输入的标签占位符#定义一个函数,用于初始化所有的权值 W
def weight_variable(shape):initial = tf.truncated_normal(shape, stddev=0.1)return tf.Variable(initial)#定义一个函数,用于初始化所有的偏置项 b
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(x):return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')#构建网络
x_image = tf.reshape(x, [-1,28,28,1])         #转换输入数据shape,以便于用于网络中
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)     #第一个卷积层
h_pool1 = max_pool(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(h_conv2)                                   #第二个池化层

W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])              #reshape成向量
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)    #第一个全连接层

keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)                  #dropout层

W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_predict=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)   #softmax层

cross_entropy = -tf.reduce_sum(y_actual*tf.log(y_predict))     #交叉熵
train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy)    #梯度下降法
correct_prediction = tf.equal(tf.argmax(y_predict,1), tf.argmax(y_actual,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))                 #精确度计算
sess=tf.InteractiveSession()
sess.run(tf.initialize_all_variables())
for i in range(20000):batch = mnist.train.next_batch(50)if i%100 == 0:                  #训练100次,验证一次train_acc = accuracy.eval(feed_dict={x:batch[0], y_actual: batch[1], keep_prob: 1.0})print('step',i,'training accuracy',train_acc)train_step.run(feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 0.5})test_acc=accuracy.eval(feed_dict={x: mnist.test.images, y_actual: mnist.test.labels, keep_prob: 1.0})
print("test accuracy",test_acc)

View Code

转载于:https://www.cnblogs.com/denny402/p/5853538.html

tensorflow学习笔记五:mnist实例--卷积神经网络(CNN)相关推荐

  1. 深度学习笔记其六:现代卷积神经网络和PYTORCH

    深度学习笔记其六:现代卷积神经网络和PYTORCH 1. 深度卷积神经网络(AlexNet) 1.1 学习表征 1.1 缺少的成分:数据 1.2 缺少的成分:硬件 1.2 AlexNet 1.2.1 ...

  2. 深度学习笔记(26) 卷积神经网络

    深度学习笔记(26) 卷积神经网络 1. CONV 2. POOL 3. Layer 4. FC 5. 卷积的优势 1. CONV 假设,有一张大小为32×32×3的输入图片,这是一张RGB模式的图片 ...

  3. 花书+吴恩达深度学习(十四)卷积神经网络 CNN 之经典案例(LetNet-5, AlexNet, VGG-16, ResNet, Inception Network)

    目录 0. 前言 1. LeNet-5 2. AlexNet 3. VGG-16 4. ResNet 残差网络 5. Inception Network 如果这篇文章对你有一点小小的帮助,请给个关注, ...

  4. 花书+吴恩达深度学习(十二)卷积神经网络 CNN 之全连接层

    目录 0. 前言 1. 全连接层(fully connected layer) 如果这篇文章对你有一点小小的帮助,请给个关注,点个赞喔~我会非常开心的~ 花书+吴恩达深度学习(十)卷积神经网络 CNN ...

  5. Tensorflow 学习笔记:Mnist 手写训练集调试,准确率变为0.1的解决办法及如何将准确率调高到98%以上

    学习笔记:Mnist 手写训练集 加入隐藏层后准确率变为0.1的解决办法 提高神经网络准确率的尝试 提高准确率:调小每次训练的批次大小 提高准确率:使用交叉熵 更改优化器及学习率 小结 提高神经网络准 ...

  6. 斯坦福大学深度学习公开课cs231n学习笔记(10)卷积神经网络

    前记:20世纪60年代,Hubel和Wiesel在研究猫脑皮层中用于局部敏感和方向选择的神经元时,发现其独特的网络结构可以有效地降低反馈神经网络的复杂性,继而提出了卷积神经网络(Convolution ...

  7. 深度学习方法(五):卷积神经网络CNN经典模型整理Lenet,Alexnet,Googlenet,VGG,Deep Residual Learning

    欢迎转载,转载请注明:本文出自Bin的专栏blog.csdn.net/xbinworld.  技术交流QQ群:433250724,欢迎对算法.技术感兴趣的同学加入. 关于卷积神经网络CNN,网络和文献 ...

  8. 深度学习方法(五):卷积神经网络CNN经典模型整理Lenet,Alexnet,Googlenet,VGG,Deep Residual Learning...

    欢迎转载,转载请注明:本文出自Bin的专栏blog.csdn.net/xbinworld. 技术交流QQ群:433250724,欢迎对算法.技术感兴趣的同学加入. 关于卷积神经网络CNN,网络和文献中 ...

  9. 深度学习(四):卷积神经网络(CNN)模型结构,前向传播算法和反向传播算法介绍。

    在前面我们讲述了DNN的模型与前向反向传播算法.而在DNN大类中,卷积神经网络(Convolutional Neural Networks,以下简称CNN)是最为成功的DNN特例之一.CNN广泛的应用 ...

最新文章

  1. 地图画指定区域_零基础学CAD绘制一张桌子为例,使亲们更好地熟悉三维绘图环境...
  2. 签入VSS中遇到UTF-8问题
  3. 体验C++20新特性的最简便方法
  4. Windws Server 2012 Server Backup(备份与还原)
  5. java web打印 闪退_tomcat闪退解决方案
  6. 在线光纤网速测试软件,光纤网速测试,宽带测试
  7. 百度商业推广php,百度“知心搜索”,背后商业协议
  8. uni-app实现android,ios打包过程详解
  9. python爬虫获取数据失败请稍后访问_Python爬取微博评论数据,竟被反爬封号了!...
  10. CUDA实现focal_loss
  11. 2021 新款苹果 iPad 真香,包邮送一个!
  12. 闲谈IPv6-Anycast以及在Linux/Win7系统上的Anycast配置
  13. Github各种账号密码错误的统一解决方案
  14. 用Python实现原生爬取某牙直播平台数据
  15. 单片机—外部中断与定时器 学习笔记
  16. 搭建ElasticSearch 强大的企业级的搜索引擎服务器
  17. 杂七杂八(5): 文件图标变白纸 解决方法(在Windows 10中修复损坏或丢失的图标和缩略图)
  18. sql获取group by最后一条记录
  19. simp服务器协议,几个常用网络协议的简单说明
  20. php+美拍地址+解析,美拍视频采集之视频地址解析下载

热门文章

  1. 简单工厂模式,抽象工厂模式,反射工厂模式的代码总结
  2. Python调用MongoDB使用心得
  3. Windows8 Metro开发 (02) : AppBar控件之TopAppBar
  4. HNCU1101:马的移动---BFS
  5. 最好最坏和平均情况下的性能分析
  6. Java虚拟机的研究与实现
  7. linux中ls命令
  8. 面试高频题:在数组中查找元素第一个和最后一个出现的位置
  9. 提升方法---提升树
  10. 《数据库技术原理与应用教程(第2版)》——习 题 1