这里使用的数据集仍然是CIFAR-10,由于之前写过一篇使用AlexNet对CIFAR数据集进行分类的文章,已经详细介绍了这个数据集,当时我们是直接把这些图片的数据文件下载下来,然后使用pickle进行反序列化获取数据的,具体内容可以参考这里:第十六节,卷积神经网络之AlexNet网络实现(六)

与MNIST类似,TensorFlow中也有一个下载和导入CIFAR数据集的代码文件,不同的是,自从TensorFlow1.0之后,将里面的Models模块分离了出来,分离和导入CIFAR数据集的代码在models中,所以要先去TensorFlow的GitHub网站将其下载下来。点击下载地址开始下载

一 描述

在该例子中,使用了全局平均池化层来代替传统的全连接层,使用了3个卷积层的同卷积网络,滤波器为5x5,每个卷积层后面跟有一个步长2x2的池化层,滤波器大小为2x2,最后一个池化层为全局平均池化层,输出后为batch_sizex1x1x10,我们对其进行形状变换为batch_sizex10,得到10个特征,再对这10个特征进行softmax计算,其结果代表最终分类。

  • 输入图片大小为24x24x3
  • 经过5x5的同卷积操作(步长为1),输出64个通道,得到24x24x64的输出
  • 经过f=2,s=2的池化层,得到大小为12x12x24的输出
  • 经过5x5的同卷积操作(步长为1),输出64个通道,得到12x12x64的输出
  • 经过f=2,s=2的池化层,得到大小为6x6x64的输出
  • 经过5x5的同卷积操作(步长为1),输出10个通道,得到6x6x10的输出
  • 经过一个全局平均池化层f=6,s=6,得到1x1x10的输出
  • 展开成1x10的形状,经过softmax函数计算,进行分类

二 导入数据集

  1. '''
  2. 一 引入数据集
  3. '''
  4. batch_size = 128
  5. learning_rate = 1e-4
  6. training_step = 15000
  7. display_step = 200
  8. #数据集目录
  9. data_dir = './cifar10_data/cifar-10-batches-bin'
  10. print('begin')
  11. #获取训练集数据
  12. images_train,labels_train = cifar10_input.inputs(eval_data=False,data_dir = data_dir,batch_size=batch_size)
  13. print('begin data')

注意这里调用了cifar10_input.inputs()函数,这个函数是专门获取数据的函数,返回数据集合对应的标签,但是这个函数会将图片裁切好,由原来的32x32x3变成24x24x3,该函数默认使用测试数据集,如果使用训练数据集,可以将第一个参数传入eval_data=False。另外再将batch_size和dir传入,就可以得到dir下面的batch_size个数据了。我们可以查看一下这个函数的实现:

  1. def inputs(eval_data, data_dir, batch_size):
  2. """Construct input for CIFAR evaluation using the Reader ops.
  3.  
  4. Args:
  5. eval_data: bool, indicating if one should use the train or eval data set.
  6. data_dir: Path to the CIFAR-10 data directory.
  7. batch_size: Number of images per batch.
  8.  
  9. Returns:
  10. images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.
  11. labels: Labels. 1D tensor of [batch_size] size.
  12. """
  13. if not eval_data:
  14. filenames = [os.path.join(data_dir, 'data_batch_%d.bin' % i)
  15. for i in xrange(1, 6)]
  16. num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN
  17. else:
  18. filenames = [os.path.join(data_dir, 'test_batch.bin')]
  19. num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_EVAL
  20.  
  21. for f in filenames:
  22. if not tf.gfile.Exists(f):
  23. raise ValueError('Failed to find file: ' + f)
  24.  
  25. with tf.name_scope('input'):
  26. # Create a queue that produces the filenames to read.
  27. filename_queue = tf.train.string_input_producer(filenames)
  28.  
  29. # Read examples from files in the filename queue.
  30. read_input = read_cifar10(filename_queue)
  31. reshaped_image = tf.cast(read_input.uint8image, tf.float32)
  32.  
  33. height = IMAGE_SIZE
  34. width = IMAGE_SIZE
  35.  
  36. # Image processing for evaluation.
  37. # Crop the central [height, width] of the image.
  38. resized_image = tf.image.resize_image_with_crop_or_pad(reshaped_image,
  39. height, width)
  40.  
  41. # Subtract off the mean and divide by the variance of the pixels.
  42. float_image = tf.image.per_image_standardization(resized_image)
  43.  
  44. # Set the shapes of tensors.
  45. float_image.set_shape([height, width, 3])
  46. read_input.label.set_shape([1])
  47.  
  48. # Ensure that the random shuffling has good mixing properties.
  49. min_fraction_of_examples_in_queue = 0.4
  50. min_queue_examples = int(num_examples_per_epoch *
  51. min_fraction_of_examples_in_queue)
  52.  
  53. # Generate a batch of images and labels by building up a queue of examples.
  54. return _generate_image_and_label_batch(float_image, read_input.label,
  55. min_queue_examples, batch_size,
  56. shuffle=False)

这个函数主要包含以下几步:

  • 读取测试集文件名或者训练集文件名,并创建文件名队列。
  • 使用文件读取器读取一张图像的数据和标签,并返回一个存放这些张量数据的类对象。
  • 对图像进行裁切处理。
  • 归一化输入。
  • 读取batch_size个图像和标签。(返回的是一个张量,必须要在会话中执行才能得到数据)

三 定义网络结构

  1. '''
  2. 二 定义网络结构
  3. '''
  4. def weight_variable(shape):
  5. '''
  6. 初始化权重
  7.  
  8. args:
  9. shape:权重shape
  10. '''
  11. initial = tf.truncated_normal(shape=shape,mean=0.0,stddev=0.1)
  12. return tf.Variable(initial)
  13.  
  14. def bias_variable(shape):
  15. '''
  16. 初始化偏置
  17.  
  18. args:
  19. shape:偏置shape
  20. '''
  21. initial =tf.constant(0.1,shape=shape)
  22. return tf.Variable(initial)
  23.  
  24. def conv2d(x,W):
  25. '''
  26. 卷积运算 ,使用SAME填充方式 卷积层后
  27. out_height = in_hight / strides_height(向上取整)
  28. out_width = in_width / strides_width(向上取整)
  29.  
  30. args:
  31. x:输入图像 形状为[batch,in_height,in_width,in_channels]
  32. W:权重 形状为[filter_height,filter_width,in_channels,out_channels]
  33. '''
  34. return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
  35.  
  36. def max_pool_2x2(x):
  37. '''
  38. 最大池化层,滤波器大小为2x2,'SAME'填充方式 池化层后
  39. out_height = in_hight / strides_height(向上取整)
  40. out_width = in_width / strides_width(向上取整)
  41.  
  42. args:
  43. x:输入图像 形状为[batch,in_height,in_width,in_channels]
  44. '''
  45. return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
  46.  
  47. def avg_pool_6x6(x):
  48. '''
  49. 全局平均池化层,使用一个与原有输入同样尺寸的filter进行池化,'SAME'填充方式 池化层后
  50. out_height = in_hight / strides_height(向上取整)
  51. out_width = in_width / strides_width(向上取整)
  52.  
  53. args;
  54. x:输入图像 形状为[batch,in_height,in_width,in_channels]
  55. '''
  56. return tf.nn.avg_pool(x,ksize=[1,6,6,1],strides=[1,6,6,1],padding='SAME')
  57.  
  58. def print_op_shape(t):
  59. '''
  60. 输出一个操作op节点的形状
  61. '''
  62. print(t.op.name,'',t.get_shape().as_list())
  63.  
  64. #定义占位符
  65. input_x = tf.placeholder(dtype=tf.float32,shape=[None,24,24,3]) #图像大小24x24x
  66. input_y = tf.placeholder(dtype=tf.float32,shape=[None,10]) #0-9类别
  67.  
  68. x_image = tf.reshape(input_x,[-1,24,24,3])
  69.  
  70. #1.卷积层 ->池化层
  71. W_conv1 = weight_variable([5,5,3,64])
  72. b_conv1 = bias_variable([64])
  73.  
  74. h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1) + b_conv1) #输出为[-1,24,24,64]
  75. print_op_shape(h_conv1)
  76. h_pool1 = max_pool_2x2(h_conv1) #输出为[-1,12,12,64]
  77. print_op_shape(h_pool1)
  78.  
  79. #2.卷积层 ->池化层
  80. W_conv2 = weight_variable([5,5,64,64])
  81. b_conv2 = bias_variable([64])
  82.  
  83. h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2) #输出为[-1,12,12,64]
  84. print_op_shape(h_conv2)
  85. h_pool2 = max_pool_2x2(h_conv2) #输出为[-1,6,6,64]
  86. print_op_shape(h_pool2)
  87.  
  88. #3.卷积层 ->全局平均池化层
  89. W_conv3 = weight_variable([5,5,64,10])
  90. b_conv3 = bias_variable([10])
  91.  
  92. h_conv3 = tf.nn.relu(conv2d(h_pool2,W_conv3) + b_conv3) #输出为[-1,6,6,10]
  93. print_op_shape(h_conv3)
  94.  
  95. nt_hpool3 = avg_pool_6x6(h_conv3) #输出为[-1,1,1,10]
  96. print_op_shape(nt_hpool3)
  97. nt_hpool3_flat = tf.reshape(nt_hpool3,[-1,10])
  98.  
  99. y_conv = tf.nn.softmax(nt_hpool3_flat)

四 定义求解器

  1. '''
  2. 三 定义求解器
  3. '''
  4.  
  5. #softmax交叉熵代价函数
  6. cost = tf.reduce_mean(-tf.reduce_sum(input_y * tf.log(y_conv),axis=1))
  7.  
  8. #求解器
  9. train = tf.train.AdamOptimizer(learning_rate).minimize(cost)
  10.  
  11. #返回一个准确度的数据
  12. correct_prediction = tf.equal(tf.arg_max(y_conv,1),tf.arg_max(input_y,1))
  13. #准确率
  14. accuracy = tf.reduce_mean(tf.cast(correct_prediction,dtype=tf.float32))

五 开始测试

  1. '''
  2. 四 开始训练
  3. '''
  4. sess = tf.Session();
  5. sess.run(tf.global_variables_initializer())
  6. # 启动计算图中所有的队列线程 调用tf.train.start_queue_runners来将文件名填充到队列,否则read操作会被阻塞到文件名队列中有值为止。
  7. tf.train.start_queue_runners(sess=sess)
  8.  
  9. for step in range(training_step):
  10. #获取batch_size大小数据集
  11. image_batch,label_batch = sess.run([images_train,labels_train])
  12.  
  13. #one hot编码
  14. label_b = np.eye(10,dtype=np.float32)[label_batch]
  15.  
  16. #开始训练
  17. train.run(feed_dict={input_x:image_batch,input_y:label_b},session=sess)
  18.  
  19. if step % display_step == 0:
  20. train_accuracy = accuracy.eval(feed_dict={input_x:image_batch,input_y:label_b},session=sess)
  21. print('Step {0} tranining accuracy {1}'.format(step,train_accuracy))

我们可以看到这个模型准确率接近70%,这主要是因为我们在图像预处理是进行了输入归一化处理,导致比我们在第十六节,卷积神经网络之AlexNet网络实现(六)文章中使用传统神经网络训练准确度52%要提高了不少,并且比AlexNet的60%高了一些(AlexNet我迭代的轮数比较少,因为太耗时)。

完整代码:

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Thu May 3 12:29:16 2018
  4.  
  5. @author: zy
  6. """
  7.  
  8. '''
  9. 建立一个带有全局平均池化层的卷积神经网络 并对CIFAR-10数据集进行分类
  10. 1.使用3个卷积层的同卷积操作,滤波器大小为5x5,每个卷积层后面都会跟一个步长为2x2的池化层,滤波器大小为2x2
  11. 2.对输出的10个feature map进行全局平均池化,得到10个特征
  12. 3.对得到的10个特征进行softmax计算,得到分类
  13. '''
  14.  
  15. import cifar10_input
  16. import tensorflow as tf
  17. import numpy as np
  18.  
  19. '''
  20. 一 引入数据集
  21. '''
  22. batch_size = 128
  23. learning_rate = 1e-4
  24. training_step = 15000
  25. display_step = 200
  26. #数据集目录
  27. data_dir = './cifar10_data/cifar-10-batches-bin'
  28. print('begin')
  29. #获取训练集数据
  30. images_train,labels_train = cifar10_input.inputs(eval_data=False,data_dir = data_dir,batch_size=batch_size)
  31. print('begin data')
  32.  
  33. '''
  34. 二 定义网络结构
  35. '''
  36. def weight_variable(shape):
  37. '''
  38. 初始化权重
  39.  
  40. args:
  41. shape:权重shape
  42. '''
  43. initial = tf.truncated_normal(shape=shape,mean=0.0,stddev=0.1)
  44. return tf.Variable(initial)
  45.  
  46. def bias_variable(shape):
  47. '''
  48. 初始化偏置
  49.  
  50. args:
  51. shape:偏置shape
  52. '''
  53. initial =tf.constant(0.1,shape=shape)
  54. return tf.Variable(initial)
  55.  
  56. def conv2d(x,W):
  57. '''
  58. 卷积运算 ,使用SAME填充方式 池化层后
  59. out_height = in_hight / strides_height(向上取整)
  60. out_width = in_width / strides_width(向上取整)
  61.  
  62. args:
  63. x:输入图像 形状为[batch,in_height,in_width,in_channels]
  64. W:权重 形状为[filter_height,filter_width,in_channels,out_channels]
  65. '''
  66. return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
  67.  
  68. def max_pool_2x2(x):
  69. '''
  70. 最大池化层,滤波器大小为2x2,'SAME'填充方式 池化层后
  71. out_height = in_hight / strides_height(向上取整)
  72. out_width = in_width / strides_width(向上取整)
  73.  
  74. args:
  75. x:输入图像 形状为[batch,in_height,in_width,in_channels]
  76. '''
  77. return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
  78.  
  79. def avg_pool_6x6(x):
  80. '''
  81. 全局平均池化层,使用一个与原有输入同样尺寸的filter进行池化,'SAME'填充方式 池化层后
  82. out_height = in_hight / strides_height(向上取整)
  83. out_width = in_width / strides_width(向上取整)
  84.  
  85. args;
  86. x:输入图像 形状为[batch,in_height,in_width,in_channels]
  87. '''
  88. return tf.nn.avg_pool(x,ksize=[1,6,6,1],strides=[1,6,6,1],padding='SAME')
  89.  
  90. def print_op_shape(t):
  91. '''
  92. 输出一个操作op节点的形状
  93. '''
  94. print(t.op.name,'',t.get_shape().as_list())
  95.  
  96. #定义占位符
  97. input_x = tf.placeholder(dtype=tf.float32,shape=[None,24,24,3]) #图像大小24x24x
  98. input_y = tf.placeholder(dtype=tf.float32,shape=[None,10]) #0-9类别
  99.  
  100. x_image = tf.reshape(input_x,[-1,24,24,3])
  101.  
  102. #1.卷积层 ->池化层
  103. W_conv1 = weight_variable([5,5,3,64])
  104. b_conv1 = bias_variable([64])
  105.  
  106. h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1) + b_conv1) #输出为[-1,24,24,64]
  107. print_op_shape(h_conv1)
  108. h_pool1 = max_pool_2x2(h_conv1) #输出为[-1,12,12,64]
  109. print_op_shape(h_pool1)
  110.  
  111. #2.卷积层 ->池化层
  112. W_conv2 = weight_variable([5,5,64,64])
  113. b_conv2 = bias_variable([64])
  114.  
  115. h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2) #输出为[-1,12,12,64]
  116. print_op_shape(h_conv2)
  117. h_pool2 = max_pool_2x2(h_conv2) #输出为[-1,6,6,64]
  118. print_op_shape(h_pool2)
  119.  
  120. #3.卷积层 ->全局平均池化层
  121. W_conv3 = weight_variable([5,5,64,10])
  122. b_conv3 = bias_variable([10])
  123.  
  124. h_conv3 = tf.nn.relu(conv2d(h_pool2,W_conv3) + b_conv3) #输出为[-1,6,6,10]
  125. print_op_shape(h_conv3)
  126.  
  127. nt_hpool3 = avg_pool_6x6(h_conv3) #输出为[-1,1,1,10]
  128. print_op_shape(nt_hpool3)
  129. nt_hpool3_flat = tf.reshape(nt_hpool3,[-1,10])
  130.  
  131. y_conv = tf.nn.softmax(nt_hpool3_flat)
  132.  
  133. '''
  134. 三 定义求解器
  135. '''
  136.  
  137. #softmax交叉熵代价函数
  138. cost = tf.reduce_mean(-tf.reduce_sum(input_y * tf.log(y_conv),axis=1))
  139.  
  140. #求解器
  141. train = tf.train.AdamOptimizer(learning_rate).minimize(cost)
  142.  
  143. #返回一个准确度的数据
  144. correct_prediction = tf.equal(tf.arg_max(y_conv,1),tf.arg_max(input_y,1))
  145. #准确率
  146. accuracy = tf.reduce_mean(tf.cast(correct_prediction,dtype=tf.float32))
  147.  
  148. '''
  149. 四 开始训练
  150. '''
  151. sess = tf.Session();
  152. sess.run(tf.global_variables_initializer())
  153. tf.train.start_queue_runners(sess=sess)
  154.  
  155. for step in range(training_step):
  156. image_batch,label_batch = sess.run([images_train,labels_train])
  157. label_b = np.eye(10,dtype=np.float32)[label_batch]
  158.  
  159. train.run(feed_dict={input_x:image_batch,input_y:label_b},session=sess)
  160.  
  161. if step % display_step == 0:
  162. train_accuracy = accuracy.eval(feed_dict={input_x:image_batch,input_y:label_b},session=sess)
  163. print('Step {0} tranining accuracy {1}'.format(step,train_accuracy))

第十三节,使用带有全局平均池化层的CNN对CIFAR10数据集分类的更多相关文章

  1. 全连接层(FC)与全局平均池化层(GAP)

    在卷积神经网络的最后,往往会出现一两层全连接层,全连接一般会把卷积输出的二维特征图转化成一维的一个向量,全连接层的每一个节点都与上一层每个节点连接,是把前一层的输出特征都综合起来,所以该层的权值参数是 ...

  2. 【深度学习篇】--神经网络中的池化层和CNN架构模型

    一.前述 本文讲述池化层和经典神经网络中的架构模型. 二.池化Pooling 1.目标 降采样subsample,shrink(浓缩),减少计算负荷,减少内存使用,参数数量减少(也可防止过拟合)减少输 ...

  3. 图像处理池化层pooling和卷积核

    1.池化层的作用 在卷积神经网络中,卷积层之间往往会加上一个池化层.池化层可以非常有效地缩小参数矩阵的尺寸,从而减少最后全连层中的参数数量.使用池化层即可以加快计算速度也有防止过拟合的作用. 2.为什 ...

  4. 『TensorFlow』卷积层、池化层详解

    一.前向计算和反向传播数学过程讲解

  5. CNN-卷积层和池化层学习

    卷积神经网络(CNN)由输入层.卷积层.激活函数.池化层.全连接层组成,即INPUT-CONV-RELU-POOL-FC (1)卷积层:用它来进行特征提取,如下: 输入图像是32*32*3,3是它的深 ...

  6. [DeeplearningAI笔记]卷积神经网络1.9-1.11池化层/卷积神经网络示例/优点

    4.1卷积神经网络 觉得有用的话,欢迎一起讨论相互学习~Follow Me 1.9池化层 优点 池化层可以缩减模型的大小,提高计算速度,同时提高所提取特征的鲁棒性. 池化层操作 池化操作与卷积操作类似 ...

  7. ubuntu之路——day17.3 简单的CNN和CNN的常用结构池化层

    来看上图的简单CNN: 从39x39x3的原始图像 不填充且步长为1的情况下经过3x3的10个filter卷积后 得到了 37x37x10的数据 不填充且步长为2的情况下经过5x5的20个filter ...

  8. TensorFlow池化层-函数

    池化层的作用如下-引用<TensorFlow实践>: 池化层的作用是减少过拟合,并通过减小输入的尺寸来提高性能.他们可以用来对输入进行降采样,但会为后续层保留重要的信息.只使用tf.nn. ...

  9. 学习笔记TF014:卷积层、激活函数、池化层、归一化层、高级层

    CNN神经网络架构至少包含一个卷积层 (tf.nn.conv2d).单层CNN检测边缘.图像识别分类,使用不同层类型支持卷积层,减少过拟合,加速训练过程,降低内存占用率. TensorFlow加速所有 ...

随机推荐

  1. jackson使用问题:mapper.readValue()将JSON字符串转反序列化为对象失败或异常

    问题根源:转化目标实体类的属性要与被转JSON字符串总的字段 一 一对应!字符串里可以少字段,但绝对不能多字段. 先附上我这段出现了问题的源码: // 1.接收并转化相应的参数.需要在pom.xml中 ...

  2. 浅谈WPF中的PreviewTextInput

    今天在使用TextBox的TextInput事件的时候,发现无论如何都不能触发该事件,然后百思不得其解,最后在MSDN上找到了答案:TextInput 事件可能已被标记为由复合控件的内部实现进行处理. ...

  3. MySQL系列:数据表基本操作(2)

    1. 指定数据库 mysql> use portal; 2. 数据库表基本操作 2.1 查看数据表 mysql> show tables; +------------------+ | T ...

  4. 微服务架构中APIGateway原理

    背景 我们知道在微服务架构风格中,一个大应用被拆分成为了多个小的服务系统提供出来,这些小的系统他们可以自成体系,也就是说这些小系统可以拥有自己的数据库,框架甚至语言等,这些小系统通常以提供 Rest ...

  5. Membership 介绍

    ASP.NET成员资格为您提供了验证和存储用户凭据的内置方式.因此,ASP.NET成员可以帮助您管理网站中的用户身份验证.您可以使用ASP.NET表单身份验证使用ASP.NET成员身份,方法是使用AS ...

  6. 洛谷 P1126 机器人搬重物

    题目描述 机器人移动学会(RMI)现在正尝试用机器人搬运物品.机器人的形状是一个直径 $1.6 米的球.在试验阶段,机器人被用于在一个储藏室中搬运货物.储藏室是一个 N×MN \times MN×M ...

  7. 自定义django-admin命令

    我们可以通过manage.py编写和注册自定义的命令. 自定义的管理命令对于独立脚本非常有用,特别是那些使用Linux的crontab服务,或者Windows的调度任务执行的脚本.比如,你有个需求,需 ...

  8. java 转义字符"\u0010" "\010" "\2"等

    java转义字符 \xxx                八进制转义符 \uxxxx          十六进制转义符 像"\010","\u0010"这种字符 ...

  9. WebAPI和WebService的区别

    WebAPI和WebService的区别 WebAPI用的是http协议,WebService用的是soap协议 WebAPI无状态,相对WebService更轻量级.WebAPI支持如get,pos ...

  10. CentOS 部署.net core 2.0 项目

    上传项目到服务器 安装Nginx(反向代理服务器),配置文件 https://www.cnblogs.com/xiaonangua/p/9176137.html 安装supervisor https: ...