搭建一个卷积神经网络

虽然对机器学习算法、神经网络、深度学习的接触也已经有一年了,但是还没有认真搭建过一个网络。为了帮助自己更好地理解,同时提高实践能力,自己动手搭建一个卷积神经网络,以备后面的学习使用。

使用比较熟悉的MNIST数据集,下载地址

包含四个部分

Training set images: train-images-idx3-ubyte.gz

Training set labels: train-labels-idx1-ubyte.gz

Test set images: t10k-images-idx3-ubyte.gz

Test set labels: t10k-labels-idx1-ubyte.gz

参考博客1:手把手教你用 TensorFlow 实现卷积神经网络(附代码)

参考博文2:深度学习四:tensorflow-使用卷积神经网络识别手写数字

 

为了方便自己理解,所以加了很多的注释。

 
  1. # CNN.py

  2. import tensorflow as tf

  3. from tensorflow.examples.tutorials.mnist import input_data

  4. sess = tf.InteractiveSession()

  5.  
  6. # 读取数据集

  7. mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

  8.  
  9. # 函数申明

  10. def weight_variable(shape):

  11. # 正态分布,标准差为0.1,默认最大为1,最小为-1,均值为0

  12. initial = tf.truncated_normal(shape, stddev=0.1)

  13. return tf.Variable(initial)

  14. def bias_variable(shape):

  15. # 创建一个结构为shape矩阵也可以说是数组shape声明其行列,初始化所有值为0.1

  16. initial = tf.constant(0.1, shape == shape)

  17. return tf.Variable(initial)

  18. def conv2d(x, W):

  19. # 卷积遍历各方向步数为1,SAME:边缘外自动补0,遍历相乘

  20. # padding 一般只有两个值

  21. return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

  22. def max_pool_2x2(x):

  23. # 池化卷积结果(conv2d)池化层采用kernel大小为2*2,步数也为2,SAME:周围补0,取最大值。数据量缩小了4倍

  24. # x 是 CNN 第一步卷积的输出量,其shape必须为[batch, height, weight, channels];

  25. # ksize 是池化窗口的大小, shape为[batch, height, weight, channels]

  26. # stride 步长,一般是[1,stride, stride,1]

  27. return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

  28.  
  29.  
  30. # 定义输入输出结构

  31. # 可以理解为形参,用于定义过程,执行时再赋值

  32. # dtype 是数据类型,常用的是tf.float32,tf.float64等数值类型

  33. # shape是数据形状,默认None表示输入图片的数量不定,28*28图片分辨率

  34. xs = tf.placeholder(tf.float32, [None, 28*28])

  35. # 类别是0-9总共10个类别,对应输出分类结果

  36. ys = tf.placeholder(tf.float32, [None, 10])

  37.  
  38. keep_prob = tf.placeholder(tf.float32)

  39. # x_image又把xs reshape成了28*28*1的形状,灰色图片的通道是1.作为训练时的input,-1代表图片数量不定

  40. x_image = tf.reshape(xs, [-1, 28, 28, 1])

  41.  
  42.  
  43. # 搭建网络

  44. # 第一层卷积池化

  45. # 第一二参数值得卷积核尺寸大小,即patch

  46. w_conv1 = weight_variable([5, 5, 1, 32])

  47. b_conv1 = bias_variable([32]) # 32个偏置值

  48. h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1)+b_conv1) # 得到28*28*32

  49. h_pool1 = max_pool_2x2(h_conv1) # 得到14*14*32

  50.  
  51. # 第二层卷积池化

  52. # 第三个参数是图像通道数,第四个参数是卷积核的数目,代表会出现多少个卷积特征图像;

  53. w_conv2 = weight_variable([5, 5, 32, 64])

  54. b_conv2 = bias_variable([64])

  55. h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2)+b_conv2) # 得到14*14*64

  56. h_pool2 = max_pool_2x2(h_conv2) # 得到7*7*64

  57.  
  58. # 第三层全连接层

  59. w_fc1 = weight_variable([7*7*64, 1024])

  60. b_fc1 = bias_variable([1024])

  61. # 将第二层卷积池化结果reshape成只有一行7*7*64个数据

  62. # [n_samples, 7, 7, 64] == [n_samples, 7 * 7 * 64]

  63. h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])

  64. # 卷积操作,结果是1*1*1024,单行乘以单列等于1*1矩阵,matmul实现最基本的矩阵相乘

  65. # 不同于tf.nn.conv2d的遍历相乘,自动认为是前行向量后列向量

  66. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1)+ b_fc1)

  67.  
  68. # 对卷积结果执行dropout操作

  69. h_fc1_dropout = tf.nn.dropout(h_fc1, keep_prob)

  70.  
  71. # 第四层输出操作

  72. # 二维张量,1*1024矩阵卷积,共10个卷积,对应ys长度为10

  73. w_fc2 = weight_variable([1024, 10])

  74. b_fc2 = bias_variable([10])

  75. y_conv = tf.nn.softmax(tf.matmul(h_fc1_dropout, w_fc2)+b_fc2)

  76.  
  77. # 定义损失函数

  78. cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(y_conv), reduction_indices=[1]))

  79. # AdamOptimizer通过使用动量(参数的移动平均数)来改善传统梯度下降,促进超参数动态调整

  80. train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

  81.  
  82. # 训练验证

  83. tf.global_variables_initializer().run()

  84. # tf.equal(A, B)是对比这两个矩阵或者向量的相等的元素,如果相等返回True,否则返回False,返回的值的矩阵维度和A是一样的

  85. correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(ys, 1))

  86. # print(correct_prediction)

  87. # tf.arg_max(input, axis=None, name=None, dimension=None) 是对矩阵按行或列计算最大值(axis:0表示按列,1表示按行)

  88. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # 数据类型转换

  89.  
  90. for i in range(1500):

  91. batch_x, batch_y = mnist.train.next_batch(50)

  92. if i%100 == 0:

  93. train_accuracy = accuracy.eval(feed_dict={xs:batch_x, ys:batch_y, keep_prob: 1.0})

  94. print('step:%d, training accuracy %g' %(i, train_accuracy))

  95. train_step.run(feed_dict={xs:batch_x, ys:batch_y, keep_prob:0.5})

  96.  
  97. print(accuracy.eval({xs:mnist.test.images, ys:mnist.test.labels, keep_prob:1.0}))

 

运行结果

 

除了Adam算法的优化器外,tensorflow还提供了一些优化器,比如: 

class tf.train.GradientDescentOptimizer–梯度下降算法的优化器 

class tf.train.AdadeltaOptimizer – 使用adadelta算法的优化器 

class tf.train.AdagradOptimizer – 使用adagradOptimizer算法的优化器 

class tf.train.MomentumOptimizer – 使用Momentum算法的优化器 

 

激活函数换成sigmoid试了一下

可以看到sigmoid的效果没有ReLU好

 

添加一个卷积池化层

 
  1. # CNN.py

  2. import tensorflow as tf

  3. from tensorflow.examples.tutorials.mnist import input_data

  4. sess = tf.InteractiveSession()

  5.  
  6.  
  7. # 函数申明

  8. def weight_variable(shape):

  9. # 正态分布,标准差为0.1,默认最大为1,最小为-1,均值为0

  10. initial = tf.truncated_normal(shape, stddev=0.1)

  11. return tf.Variable(initial)

  12. def bias_variable(shape):

  13. # 创建一个结构为shape矩阵也可以说是数组shape声明其行列,初始化所有值为0.1

  14. initial = tf.constant(0.1, shape == shape)

  15. return tf.Variable(initial)

  16. def conv2d(x, W):

  17. # 卷积遍历各方向步数为1,SAME:边缘外自动补0,遍历相乘

  18. # padding 一般只有两个值

  19. return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

  20. def max_pool_2x2(x):

  21. # 池化卷积结果(conv2d)池化层采用kernel大小为2*2,步数也为2,SAME:周围补0,取最大值。数据量缩小了4倍

  22. # x 是 CNN 第一步卷积的输出量,其shape必须为[batch, height, weight, channels];

  23. # ksize 是池化窗口的大小, shape为[batch, height, weight, channels]

  24. # stride 步长,一般是[1,stride, stride,1]

  25. return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

  26.  
  27. def deep_CNN(xs):

  28. # x_image又把xs reshape成了28*28*1的形状,灰色图片的通道是1.作为训练时的input,-1代表图片数量不定

  29. x_image = tf.reshape(xs, [-1, 28, 28, 1])

  30.  
  31. # 搭建网络

  32. # 第一层卷积池化

  33. # 第一二参数值得卷积核尺寸大小,即patch

  34. w_conv1 = weight_variable([5, 5, 1, 32])

  35. b_conv1 = bias_variable([32]) # 32个偏置值

  36. h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1)+b_conv1) # 得到28*28*32

  37. #h_conv1 = tf.nn.sigmoid(conv2d(x_image, w_conv1)+b_conv1)

  38. h_pool1 = max_pool_2x2(h_conv1) # 得到14*14*32

  39.  
  40. # 第二层卷积池化

  41. # 第三个参数是图像通道数,第四个参数是卷积核的数目,代表会出现多少个卷积特征图像;

  42. w_conv2 = weight_variable([5, 5, 32, 64])

  43. b_conv2 = bias_variable([64])

  44. h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2)+b_conv2) # 得到14*14*64

  45. #h_conv2 = tf.nn.sigmoid(conv2d(h_pool1, w_conv2)+b_conv2)

  46. h_pool2 = max_pool_2x2(h_conv2) # 得到7*7*64

  47.  
  48. # 添加一层卷积池化层

  49. w_conv3 = weight_variable([5, 5, 64, 128])

  50. b_conv3 = bias_variable([128])

  51. h_conv3 = tf.nn.relu(conv2d(h_pool2, w_conv3)+b_conv3) # 得到7*7*128

  52. #h_conv3 = tf.nn.sigmoid(conv2d(h_pool1, w_conv2)+b_conv2)

  53. h_pool3 = max_pool_2x2(h_conv3) # 得到4*4*128

  54.  
  55. # 第四层全连接层

  56. w_fc1 = weight_variable([4*4*128, 1024])

  57. b_fc1 = bias_variable([1024])

  58. # 将第三层卷积池化结果reshape成只有一行7*7*128个数据

  59. # [n_samples, 4, 4, 128] == [n_samples, 4 * 4 * 128]

  60. h_pool3_flat = tf.reshape(h_pool3, [-1, 4*4*128])

  61. # -1 表示不知道该填什么数字合适的情况下,可以选择

  62. # 卷积操作,结果是1*1*1024,单行乘以单列等于1*1矩阵,matmul实现最基本的矩阵相乘

  63. # 不同于tf.nn.conv2d的遍历相乘,自动认为是前行向量后列向量

  64. h_fc1 = tf.nn.relu(tf.matmul(h_pool3_flat, w_fc1)+ b_fc1)

  65. #h_fc1 = tf.nn.sigmoid(tf.matmul(h_pool2_flat, w_fc1)+ b_fc1)

  66.  
  67. # 对卷积结果执行dropout操作

  68. keep_prob = tf.placeholder(tf.float32)

  69. h_fc1_dropout = tf.nn.dropout(h_fc1, keep_prob)

  70. # tf.nn.dropout(x, keep_prob, noise_shape=None, seed=None, name=None)

  71. # 第二个参数keep_prob: 设置神经元被选中的概率,在初始化时keep_prob是一个占位符

  72.  
  73. # 第四层输出操作

  74. # 二维张量,1*1024矩阵卷积,共10个卷积,对应ys长度为10

  75. w_fc2 = weight_variable([1024, 10])

  76. b_fc2 = bias_variable([10])

  77. y_conv = tf.nn.softmax(tf.matmul(h_fc1_dropout, w_fc2)+b_fc2)

  78.  
  79. return y_conv, keep_prob

  80.  
  81. def main():

  82. # 读取数据集

  83. mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

  84.  
  85. # 定义输入输出结构

  86. # tf.placeholder可以理解为形参,用于定义过程,执行时再赋值

  87. # dtype 是数据类型,常用的是tf.float32,tf.float64等数值类型

  88. # shape是数据形状,默认None表示输入图片的数量不定,28*28图片分辨率

  89. xs = tf.placeholder(tf.float32, [None, 28 * 28])

  90. # 类别是0-9总共10个类别,对应输出分类结果

  91. ys = tf.placeholder(tf.float32, [None, 10])

  92.  
  93. y_conv, keep_prob = deep_CNN(xs)

  94.  
  95. # 定义损失函数

  96. # cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(y_conv), reduction_indices=[1]))

  97. cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=ys, logits=y_conv))

  98. # AdamOptimizer通过使用动量(参数的移动平均数)来改善传统梯度下降,促进超参数动态调整

  99. train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

  100.  
  101. # 训练验证

  102. # tf.equal(A, B)是对比这两个矩阵或者向量的相等的元素,如果相等返回True,否则返回False,返回的值的矩阵维度和A是一样的

  103. correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(ys, 1))

  104. # print(correct_prediction)

  105. # tf.arg_max(input, axis=None, name=None, dimension=None) 是对矩阵按行或列计算最大值(axis:0表示按列,1表示按行)

  106. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # 数据类型转换

  107.  
  108. print("start train")

  109. sess.run(tf.global_variables_initializer())

  110.  
  111. for i in range(1500):

  112. batch_x, batch_y = mnist.train.next_batch(50)

  113. if i % 100 == 0:

  114. train_accuracy = accuracy.eval(feed_dict={xs: batch_x, ys: batch_y, keep_prob: 1.0})

  115. print('step:%d, training accuracy %g' % (i, train_accuracy))

  116. train_step.run(feed_dict={xs: batch_x, ys: batch_y, keep_prob: 0.5})

  117.  
  118. # 测试

  119. print(accuracy.eval({xs: mnist.test.images, ys: mnist.test.labels, keep_prob: 1.0}))

  120.  
  121. if __name__ == '__main__':

  122. main()

结果看来没太大差别,效果没有什么提升

 

接下来保存和恢复参数

为了方便调试,节省训练时间,我把迭代次数调到了1000

训练时

 
  1. saver = tf.train.Saver()

  2.  
  3. sess.run(tf.global_variables_initializer())

  4.  
  5. for i in range(1000):

  6. batch_x, batch_y = mnist.train.next_batch(50)

  7. if i % 100 == 0:

  8. train_accuracy = accuracy.eval(feed_dict={xs: batch_x, ys: batch_y, keep_prob: 1.0})

  9. print('step:%d, training accuracy %g' % (i, train_accuracy))

  10. train_step.run(feed_dict={xs: batch_x, ys: batch_y, keep_prob: 0.5})

  11. saver.save(sess, "input_data/model")

得到的文件

测试时

 
  1. saver = tf.train.Saver()

  2.  
  3. sess.run(tf.global_variables_initializer())

  4.  
  5. saver.restore(sess, "input_data/model")

  6. # 测试

  7. print(accuracy.eval({xs: mnist.test.images, ys: mnist.test.labels, keep_prob: 1.0}))

直接得到测试结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值