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

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

首先,下载并加载数据:

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

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

  1. #定义一个函数,用于初始化所有的权值 W
  2. def weight_variable(shape):
  3. initial = tf.truncated_normal(shape, stddev=0.1)
  4. return tf.Variable(initial)
  5.  
  6. #定义一个函数,用于初始化所有的偏置项 b
  7. def bias_variable(shape):
  8. initial = tf.constant(0.1, shape=shape)
  9. return tf.Variable(initial)
  10.  
  11. #定义一个函数,用于构建卷积层
  12. def conv2d(x, W):
  13. return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  14.  
  15. #定义一个函数,用于构建池化层
  16. def max_pool(x):
  17. return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')

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

  1. #构建网络
  2. x_image = tf.reshape(x, [-1,28,28,1]) #转换输入数据shape,以便于用于网络中
  3. W_conv1 = weight_variable([5, 5, 1, 32])
  4. b_conv1 = bias_variable([32])
  5. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) #第一个卷积层
  6. h_pool1 = max_pool(h_conv1) #第一个池化层
  7.  
  8. W_conv2 = weight_variable([5, 5, 32, 64])
  9. b_conv2 = bias_variable([64])
  10. h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) #第二个卷积层
  11. h_pool2 = max_pool(h_conv2) #第二个池化层
  12.  
  13. W_fc1 = weight_variable([7 * 7 * 64, 1024])
  14. b_fc1 = bias_variable([1024])
  15. h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) #reshape成向量
  16. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) #第一个全连接层
  17.  
  18. keep_prob = tf.placeholder("float")
  19. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) #dropout层
  20.  
  21. W_fc2 = weight_variable([1024, 10])
  22. b_fc2 = bias_variable([10])
  23. y_predict=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) #softmax层

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

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

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

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

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

完整代码:

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Thu Sep 8 15:29:48 2016
  4.  
  5. @author: root
  6. """
  7. import tensorflow as tf
  8. import tensorflow.examples.tutorials.mnist.input_data as input_data
  9. mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) #下载并加载mnist数据
  10. x = tf.placeholder(tf.float32, [None, 784]) #输入的数据占位符
  11. y_actual = tf.placeholder(tf.float32, shape=[None, 10]) #输入的标签占位符
  12.  
  13. #定义一个函数,用于初始化所有的权值 W
  14. def weight_variable(shape):
  15. initial = tf.truncated_normal(shape, stddev=0.1)
  16. return tf.Variable(initial)
  17.  
  18. #定义一个函数,用于初始化所有的偏置项 b
  19. def bias_variable(shape):
  20. initial = tf.constant(0.1, shape=shape)
  21. return tf.Variable(initial)
  22.  
  23. #定义一个函数,用于构建卷积层
  24. def conv2d(x, W):
  25. return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  26.  
  27. #定义一个函数,用于构建池化层
  28. def max_pool(x):
  29. return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')
  30.  
  31. #构建网络
  32. x_image = tf.reshape(x, [-1,28,28,1]) #转换输入数据shape,以便于用于网络中
  33. W_conv1 = weight_variable([5, 5, 1, 32])
  34. b_conv1 = bias_variable([32])
  35. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) #第一个卷积层
  36. h_pool1 = max_pool(h_conv1) #第一个池化层
  37.  
  38. W_conv2 = weight_variable([5, 5, 32, 64])
  39. b_conv2 = bias_variable([64])
  40. h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) #第二个卷积层
  41. h_pool2 = max_pool(h_conv2) #第二个池化层
  42.  
  43. W_fc1 = weight_variable([7 * 7 * 64, 1024])
  44. b_fc1 = bias_variable([1024])
  45. h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) #reshape成向量
  46. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) #第一个全连接层
  47.  
  48. keep_prob = tf.placeholder("float")
  49. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) #dropout层
  50.  
  51. W_fc2 = weight_variable([1024, 10])
  52. b_fc2 = bias_variable([10])
  53. y_predict=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) #softmax层
  54.  
  55. cross_entropy = -tf.reduce_sum(y_actual*tf.log(y_predict)) #交叉熵
  56. train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy) #梯度下降法
  57. correct_prediction = tf.equal(tf.argmax(y_predict,1), tf.argmax(y_actual,1))
  58. accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) #精确度计算
  59. sess=tf.InteractiveSession()
  60. sess.run(tf.initialize_all_variables())
  61. for i in range(20000):
  62. batch = mnist.train.next_batch(50)
  63. if i%100 == 0: #训练100次,验证一次
  64. train_acc = accuracy.eval(feed_dict={x:batch[0], y_actual: batch[1], keep_prob: 1.0})
  65. print('step',i,'training accuracy',train_acc)
  66. train_step.run(feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 0.5})
  67.  
  68. test_acc=accuracy.eval(feed_dict={x: mnist.test.images, y_actual: mnist.test.labels, keep_prob: 1.0})
  69. print("test accuracy",test_acc)

tensorflow学习笔记五:mnist实例--卷积神经网络(CNN)的更多相关文章

  1. 深度学习-tensorflow学习笔记(1)-MNIST手写字体识别预备知识

    深度学习-tensorflow学习笔记(1)-MNIST手写字体识别预备知识 在tf第一个例子的时候需要很多预备知识. tf基本知识 香农熵 交叉熵代价函数cross-entropy 卷积神经网络 s ...

  2. 深度学习-tensorflow学习笔记(2)-MNIST手写字体识别

    深度学习-tensorflow学习笔记(2)-MNIST手写字体识别超级详细版 这是tf入门的第一个例子.minst应该是内置的数据集. 前置知识在学习笔记(1)里面讲过了 这里直接上代码 # -*- ...

  3. UFLDL深度学习笔记 (六)卷积神经网络

    UFLDL深度学习笔记 (六)卷积神经网络 1. 主要思路 "UFLDL 卷积神经网络"主要讲解了对大尺寸图像应用前面所讨论神经网络学习的方法,其中的变化有两条,第一,对大尺寸图像 ...

  4. 神经网络与深度学习笔记 Chapter 6之卷积神经网络

    深度学习 Introducing convolutional networks:卷积神经网络介绍 卷积神经网络中有三个基本的概念:局部感受野(local receptive fields), 共享权重 ...

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

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

  6. DeepLearning.ai学习笔记(四)卷积神经网络 -- week2深度卷积神经网络 实例探究

    一.为什么要进行实例探究? 通过他人的实例可以更好的理解如何构建卷积神经网络,本周课程主要会介绍如下网络 LeNet-5 AlexNet VGG ResNet (有152层) Inception 二. ...

  7. DeepLearning.ai学习笔记(四)卷积神经网络 -- week4 特殊应用:人力脸识别和神经风格转换

    一.什么是人脸识别 老实说这一节中的人脸识别技术的演示的确很牛bi,但是演技好尴尬,233333 啥是人脸识别就不用介绍了,下面笔记会介绍如何实现人脸识别. 二.One-shot(一次)学习 假设我们 ...

  8. TensorFlow学习笔记13-循环、递归神经网络

    循环神经网络(RNN) 卷积网络专门处理网格化的数据,而循环网络专门处理序列化的数据. 一般的神经网络结构为: 一般的神经网络结构的前提假设是:元素之间是相互独立的,输入.输出都是独立的. 现实世界中 ...

  9. DeepLearning.ai学习笔记(四)卷积神经网络 -- week1 卷积神经网络基础知识介绍

    一.计算机视觉 如图示,之前课程中介绍的都是64* 64 3的图像,而一旦图像质量增加,例如变成1000 1000 * 3的时候那么此时的神经网络的计算量会巨大,显然这不现实.所以需要引入其他的方法来 ...

随机推荐

  1. 软件开发流程 Software development process

    软件开发流程(Software development process)即软件设计思路和方法的一般过程,包括设计软件的功能和实现的算法和方法.软件的总体结构设计和模块设计.编程和调试.程序联调和测试以 ...

  2. [deviceone开发]-do_ImageView实现正圆的示例

    一.简介 我们经常需要用一个正圆形状的图片来设置头像,在do平台这个比较容易,就是通过设置圆角来实现,但是有几个小技巧需要解释一下 主要组件:do_ImageView 二.效果图 三.相关下载 htt ...

  3. 搭建基于 STM32 和 rt-thread 的开发平台

    我们需要平台 如果说,SharePoint 的价值之一在于提供了几乎开箱即用的 innovation 环境,那么,智能设备的开发平台也一样.不必每次都从头开始,所以需要固定的工作室和开发平台作为创新的 ...

  4. AngularJS在IE8的支持

    AngularJS一般不会选择IE8支持, 因为很多特性在IE8下效果很差, 性能也不好, 但是由于项目的需要, 客户的机器有些是XP, 只能够装IE8, 所以为了解决这个, 我查阅了相关的资料,发现 ...

  5. 用Kotlin开发Android应用(II):创建新项目

    这是关于Kotlin的第二篇.各位高手发现问题,请继续“拍砖”. 原文标题:Kotlin for Android(II): Create a new project 原文链接:http://anton ...

  6. Android开发学习——打电话应用

    打电话应用 system/app/phone.apk  这个是打电话应用,这个Java API 不允许应用级程序员改写,系统级才可以 system/app/dialer.apk  这个是拨号器应用,可 ...

  7. UIBezierPath-绘制基本图形

    步骤1:确定路径 步骤2:渲染 override func draw(_ rect: CGRect) { let path:UIBezierPath // 矩形 // path = UIBezierP ...

  8. spring.net (3)依赖注入基础2

    如何调用其他对象的成员 接上文例子: 现在Person有一个属性 name  静态属性 eye 域 gender public class Person { public string name { ...

  9. IOS开发基础知识--碎片7

    三十八:各个版本IPHONE分辨率及图片的实现原理 desert@2x : iPhone 4s ( x ) desert-568h@2x : iPhones , 5C and 5S ( x ) des ...

  10. Linux 通过sendmail 发邮件到外部邮箱

    最近在写自动化巡检脚本,想着怎么预警后自动发送邮件报警. 首先下载最新版本mailx-12.4.tar.bz2 # wget http://sourceforge.net/projects/heirl ...