当前位置:   article > 正文

实战篇之——利用【Python+Tensorflow】搭建ResNet,实现对Cifar10数据集的分类_resnet分类 python

resnet分类 python

利用【Python+Tensorflow】搭建ResNet,实现对Cifar10数据集的分类

具体数据集介绍及下载地址:https://blog.csdn.net/weixin_44402973/article/details/96028312

2015年微软亚洲研究院何凯明团队提出了ResNet,在网络结构上使用了跳连来防止梯度消失,一定程度上加深网络层数。引入跳连,可以一定程度也解决网络深度加深,网络难优化问题。

RestNet中提出了残差连接,解释为:

假设有一个比较浅的网络达到了饱和的准确率,那么后面再加上几个y=x的全等映射层,起码误差不会增加,即更深的网络不应该带来训练集上误差上升。而这里提到的使用全等映射直接将前一层输出传到后面的思想,就是ResNet的灵感来源。假定某段神经网络的输入是x,期望输出是H(x),如果我们直接把输入x传到输出作为初始结果,那么此时我们需要学习的目标就是F(x) = H(x) - x。如图所示,这就是一个ResNet的残差学习单元(Residual Unit),ResNet相当于将学习目标改变了,不再是学习一个完整的输出H(x),只是输出和输入的差别H(x)-x,即残差,如图1。

  • ResNet使用了一种连接方式叫做“shortcut connection”,也是论文中提到identity mapping,如下图1:

                                                                                               图1. Shortcut Connection

  • 残差结构的两种设计,如下图2:

                                                                                   图2. 残差结构

由上图可知,实现残差块【上述残差结构】,可以使用上面两种结构:building block(左)和bottleneck block(右)。

A bottleneck building block提出为了目的是为了降低参数的数目,第一个1x1的卷积把256维channel降到64维,然后在最后通过1x1卷积进行恢复,整体上用的参数数目:1*1*256*64+3*3*64*64+1*1*64*256 = 69632,如果不使用bottleneck结构的话就是两个3x3x256的卷积,参数数目: 3x3x256x256x2 = 1179648,两者之间参数量相差了将近17倍。 

A “bottleneck building” block提出为了目的是为了降低计算量,考虑两种结构的输入和输出feature map大小为M*N相等,使用bottleneck结构计算量为:M*N*1*1*256*64+M*N*3*3*64*64+M*N*1*1*64*256=69632*M*N;使用building block结构计算量为:M*N*3*3*256*256*2=1179648*M*N,可以得出使用“building block”计算量大致减少了16.94倍。

RestNet网络结构(来自论文)

                                                                                             图3.网络结构图

本次代码实现

1.文件组织形式:

2.本次代码文件res_net.py中实现了building block结构残差卷积网络:

  1. # coding: utf-8
  2. import tensorflow as tf
  3. import os
  4. import pickle
  5. import numpy as np
  6. CIFAR_DIR = "./cifar-10-batches-py"
  7. print(os.listdir(CIFAR_DIR))
  8. def load_data(filename):
  9. """read data from data file."""
  10. with open(filename, 'rb') as f:
  11. data = pickle.load(f, encoding='latin1')
  12. return data['data'], data['labels']
  13. class CifarData:
  14. def __init__(self, filenames, need_shuffle):
  15. all_data = []
  16. all_labels = []
  17. for filename in filenames:
  18. data, labels = load_data(filename)
  19. all_data.append(data)
  20. all_labels.append(labels)
  21. self._data = np.vstack(all_data)
  22. self._data = self._data / 127.5 - 1
  23. self._labels = np.hstack(all_labels)
  24. print(self._data.shape)
  25. print(self._labels.shape)
  26. self._num_examples = self._data.shape[0]
  27. self._need_shuffle = need_shuffle
  28. self._indicator = 0
  29. if self._need_shuffle:
  30. self._shuffle_data()
  31. def _shuffle_data(self):
  32. # [0,1,2,3,4,5] -> [5,3,2,4,0,1]
  33. p = np.random.permutation(self._num_examples)
  34. self._data = self._data[p]
  35. self._labels = self._labels[p]
  36. def size(self):
  37. """获取数据总量"""
  38. return self._num_examples
  39. def next_batch(self, batch_size):
  40. """return batch_size examples as a batch."""
  41. if batch_size > self._num_examples:
  42. raise Exception("batch size is larger than all examples")
  43. end_indicator = self._indicator + batch_size
  44. if self._indicator < self._num_examples-1 and end_indicator >self._num_examples:
  45. end_indicator = self._num_examples
  46. elif self._indicator >= self._num_examples-1:
  47. self._indicator = 0
  48. end_indicator = batch_size
  49. batch_data = self._data[self._indicator: end_indicator]
  50. batch_labels = self._labels[self._indicator: end_indicator]
  51. self._indicator = end_indicator
  52. return batch_data, batch_labels
  53. def residual_block(x, output_channel):
  54. """
  55. desc:定义残差块,每经过一个残差块图像大小减少一半,并且通道数加倍
  56. Args:
  57. @param x:残差块的输入
  58. @param output_channel:输出通道数
  59. """
  60. input_channel = x.get_shape().as_list()[-1]
  61. if input_channel * 2 == output_channel:
  62. increase_dim = True
  63. strides = (2, 2)
  64. elif input_channel == output_channel:
  65. increase_dim = False
  66. strides = (1, 1)
  67. else:
  68. raise Exception("input channel can't match output channel")
  69. conv1 = tf.layers.conv2d(x,
  70. output_channel,
  71. (3,3),
  72. strides = strides,
  73. padding = 'same',
  74. activation = tf.nn.relu,
  75. name = 'conv1')
  76. conv2 = tf.layers.conv2d(conv1,
  77. output_channel,
  78. (3, 3),
  79. strides = (1, 1),
  80. padding = 'same',
  81. activation = None,
  82. name = 'conv2')
  83. if increase_dim:
  84. # 由于输入和输出feature map不一致,对输入进行均值池化
  85. pooled_x = tf.layers.average_pooling2d(x,
  86. (2, 2),
  87. (2, 2),
  88. padding = 'valid')
  89. # 对通道维度进行填充
  90. padded_x = tf.pad(pooled_x,
  91. [[0,0],
  92. [0,0],
  93. [0,0],
  94. [input_channel // 2, input_channel // 2]])
  95. else:
  96. padded_x = x
  97. output_x = tf.nn.relu(conv2 + padded_x)
  98. return output_x
  99. def res_net(num_residual_blocks, num_filter_base,class_num):
  100. """
  101. 定义带有残差块的网络结构模型
  102. Args:
  103. @param num_residual_blocks: eg: [3, 4, 6, 3]
  104. @param num_filter_base:开始对原图像进行卷积操作中卷积核个数
  105. @param class_num:类别数
  106. """
  107. x = tf.placeholder(tf.float32, [None,3072])
  108. y = tf.placeholder(tf.int64, [None])
  109. # [None], eg: [0,5,6,3]
  110. x_image = tf.reshape(x, [-1, 3, 32, 32])
  111. # 32*32
  112. x_new = tf.transpose(x_image, perm=[0, 2, 3, 1])
  113. num_subsampling = len(num_residual_blocks)
  114. layers = []
  115. # x: [None, width, height, channel] -> [width, height, channel]
  116. input_size = x_new.get_shape().as_list()[1:]
  117. with tf.variable_scope('conv0'):
  118. conv0 = tf.layers.conv2d(x_new,
  119. num_filter_base,
  120. (3, 3),
  121. strides = (1, 1),
  122. padding = 'same',
  123. activation = tf.nn.relu,
  124. name = 'conv0')
  125. layers.append(conv0)
  126. # eg:num_subsampling = 4, sample_id = [0,1,2,3]
  127. for sample_id in range(num_subsampling):
  128. for i in range(num_residual_blocks[sample_id]):
  129. with tf.variable_scope("conv%d_%d" % (sample_id, i)):
  130. conv = residual_block(
  131. layers[-1],
  132. num_filter_base * (2 ** sample_id))
  133. layers.append(conv)
  134. # 计算feature map下采样多少
  135. multiplier = 2 ** (num_subsampling - 1)
  136. # 判断经过残差层之后,维度是否正确
  137. assert layers[-1].get_shape().as_list()[1:] == [input_size[0] / multiplier,
  138. input_size[1] / multiplier,
  139. num_filter_base * multiplier]
  140. with tf.variable_scope('fc'):
  141. # layer[-1].shape : [None, width, height, channel]
  142. # kernal_size: image_width, image_height
  143. global_pool = tf.reduce_mean(layers[-1], [1,2])
  144. logits = tf.layers.dense(global_pool, class_num)
  145. layers.append(logits)
  146. y_ = layers[-1]
  147. loss = tf.losses.sparse_softmax_cross_entropy(labels=y, logits=y_)\
  148. # indices
  149. predict = tf.argmax(y_, 1)
  150. # [1,0,1,1,1,0,0,0]
  151. correct_prediction = tf.equal(predict, y)
  152. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float64))
  153. with tf.name_scope('train_op'):
  154. train_op = tf.train.AdamOptimizer(1e-3).minimize(loss)
  155. return x,y,accuracy,loss,train_op
  156. batch_size = 32
  157. #训练轮数
  158. num_epoch = 10
  159. train_filenames = [os.path.join(CIFAR_DIR, 'data_batch_%d' % i) for i in range(1, 6)]
  160. test_filenames = [os.path.join(CIFAR_DIR, 'test_batch')]
  161. x,y,accuracy,loss,train_op = res_net([2,3,2], 32, 10)
  162. best_test_acc = 0
  163. with tf.Session() as sess:
  164. init = tf.global_variables_initializer().run()
  165. iters = 0
  166. for epoch in range(num_epoch):
  167. train_data = CifarData(train_filenames, True)
  168. train_size = train_data.size()
  169. # 获取每个epoch中batch个数
  170. batch_num = np.ceil(train_size / batch_size)
  171. for i in range(int(batch_num)):
  172. batch_data, batch_labels = train_data.next_batch(batch_size)
  173. loss_val, acc_val, _ = sess.run([loss, accuracy, train_op],feed_dict={x: batch_data,y: batch_labels})
  174. if iters % 1000 == 0 and iters != 0:
  175. print('Epoch:%d, [Train] Step: %d, [Train] loss: %4.5f, [Train] acc: %4.5f' % (epoch,iters, loss_val, acc_val))
  176. iters += 1
  177. # 每个epoch之后对数据评估
  178. test_data = CifarData(test_filenames, False)
  179. test_size = test_data.size()
  180. test_all_acc = []
  181. test_all_loss = []
  182. test_batch_num = np.ceil(test_size / batch_size)
  183. for j in range(int(test_batch_num)):
  184. test_batch_data, test_batch_labels = test_data.next_batch(batch_size)
  185. test_acc,test_loss= sess.run([accuracy,loss],feed_dict = {x:test_batch_data, y: test_batch_labels})
  186. test_all_acc.append(test_acc)
  187. test_all_loss.append(test_loss)
  188. if best_test_acc < np.mean(test_all_acc):
  189. best_test_acc = np.mean(test_all_acc)
  190. print('[Test] loss: %4.5f, [Test] acc: %4.5f Flag:*' % (np.mean(test_all_loss), np.mean(test_all_acc)))
  191. else:
  192. print('[Test] loss: %4.5f, [Test] acc: %4.5f Flag:-' % (np.mean(test_all_loss), np.mean(test_all_acc)))

结果展示:

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/92754
推荐阅读
相关标签
  

闽ICP备14008679号