resnet_model.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """ResNet model.
  16. Related papers:
  17. https://arxiv.org/pdf/1603.05027v2.pdf
  18. https://arxiv.org/pdf/1512.03385v1.pdf
  19. https://arxiv.org/pdf/1605.07146v1.pdf
  20. """
  21. from collections import namedtuple
  22. import numpy as np
  23. import tensorflow as tf
  24. from tensorflow.python.training import moving_averages
  25. HParams = namedtuple('HParams',
  26. 'batch_size, num_classes, min_lrn_rate, lrn_rate, '
  27. 'num_residual_units, use_bottleneck, weight_decay_rate, '
  28. 'relu_leakiness, optimizer')
  29. class ResNet(object):
  30. """ResNet model."""
  31. def __init__(self, hps, images, labels, mode):
  32. """ResNet constructor.
  33. Args:
  34. hps: Hyperparameters.
  35. images: Batches of images. [batch_size, image_size, image_size, 3]
  36. labels: Batches of labels. [batch_size, num_classes]
  37. mode: One of 'train' and 'eval'.
  38. """
  39. self.hps = hps
  40. self._images = images
  41. self.labels = labels
  42. self.mode = mode
  43. self._extra_train_ops = []
  44. def build_graph(self):
  45. """Build a whole graph for the model."""
  46. self.global_step = tf.Variable(0, name='global_step', trainable=False)
  47. self._build_model()
  48. if self.mode == 'train':
  49. self._build_train_op()
  50. self.summaries = tf.merge_all_summaries()
  51. def _stride_arr(self, stride):
  52. """Map a stride scalar to the stride array for tf.nn.conv2d."""
  53. return [1, stride, stride, 1]
  54. def _build_model(self):
  55. """Build the core model within the graph."""
  56. with tf.variable_scope('init'):
  57. x = self._images
  58. x = self._conv('init_conv', x, 3, 3, 16, self._stride_arr(1))
  59. strides = [1, 2, 2]
  60. activate_before_residual = [True, False, False]
  61. if self.hps.use_bottleneck:
  62. res_func = self._bottleneck_residual
  63. filters = [16, 64, 128, 256]
  64. else:
  65. res_func = self._residual
  66. filters = [16, 16, 32, 64]
  67. # Uncomment the following codes to use w28-10 wide residual network.
  68. # It is more memory efficient than very deep residual network and has
  69. # comparably good performance.
  70. # https://arxiv.org/pdf/1605.07146v1.pdf
  71. # filters = [16, 160, 320, 640]
  72. # Update hps.num_residual_units to 9
  73. with tf.variable_scope('unit_1_0'):
  74. x = res_func(x, filters[0], filters[1], self._stride_arr(strides[0]),
  75. activate_before_residual[0])
  76. for i in xrange(1, self.hps.num_residual_units):
  77. with tf.variable_scope('unit_1_%d' % i):
  78. x = res_func(x, filters[1], filters[1], self._stride_arr(1), False)
  79. with tf.variable_scope('unit_2_0'):
  80. x = res_func(x, filters[1], filters[2], self._stride_arr(strides[1]),
  81. activate_before_residual[1])
  82. for i in xrange(1, self.hps.num_residual_units):
  83. with tf.variable_scope('unit_2_%d' % i):
  84. x = res_func(x, filters[2], filters[2], self._stride_arr(1), False)
  85. with tf.variable_scope('unit_3_0'):
  86. x = res_func(x, filters[2], filters[3], self._stride_arr(strides[2]),
  87. activate_before_residual[2])
  88. for i in xrange(1, self.hps.num_residual_units):
  89. with tf.variable_scope('unit_3_%d' % i):
  90. x = res_func(x, filters[3], filters[3], self._stride_arr(1), False)
  91. with tf.variable_scope('unit_last'):
  92. x = self._batch_norm('final_bn', x)
  93. x = self._relu(x, self.hps.relu_leakiness)
  94. x = self._global_avg_pool(x)
  95. with tf.variable_scope('logit'):
  96. logits = self._fully_connected(x, self.hps.num_classes)
  97. self.predictions = tf.nn.softmax(logits)
  98. with tf.variable_scope('costs'):
  99. xent = tf.nn.softmax_cross_entropy_with_logits(
  100. logits, self.labels)
  101. self.cost = tf.reduce_mean(xent, name='xent')
  102. self.cost += self._decay()
  103. tf.scalar_summary('cost', self.cost)
  104. def _build_train_op(self):
  105. """Build training specific ops for the graph."""
  106. self.lrn_rate = tf.constant(self.hps.lrn_rate, tf.float32)
  107. tf.scalar_summary('learning rate', self.lrn_rate)
  108. trainable_variables = tf.trainable_variables()
  109. grads = tf.gradients(self.cost, trainable_variables)
  110. if self.hps.optimizer == 'sgd':
  111. optimizer = tf.train.GradientDescentOptimizer(self.lrn_rate)
  112. elif self.hps.optimizer == 'mom':
  113. optimizer = tf.train.MomentumOptimizer(self.lrn_rate, 0.9)
  114. apply_op = optimizer.apply_gradients(
  115. zip(grads, trainable_variables),
  116. global_step=self.global_step, name='train_step')
  117. train_ops = [apply_op] + self._extra_train_ops
  118. self.train_op = tf.group(*train_ops)
  119. # TODO(xpan): Consider batch_norm in contrib/layers/python/layers/layers.py
  120. def _batch_norm(self, name, x):
  121. """Batch normalization."""
  122. with tf.variable_scope(name):
  123. params_shape = [x.get_shape()[-1]]
  124. beta = tf.get_variable(
  125. 'beta', params_shape, tf.float32,
  126. initializer=tf.constant_initializer(0.0, tf.float32))
  127. gamma = tf.get_variable(
  128. 'gamma', params_shape, tf.float32,
  129. initializer=tf.constant_initializer(1.0, tf.float32))
  130. if self.mode == 'train':
  131. mean, variance = tf.nn.moments(x, [0, 1, 2], name='moments')
  132. moving_mean = tf.get_variable(
  133. 'moving_mean', params_shape, tf.float32,
  134. initializer=tf.constant_initializer(0.0, tf.float32),
  135. trainable=False)
  136. moving_variance = tf.get_variable(
  137. 'moving_variance', params_shape, tf.float32,
  138. initializer=tf.constant_initializer(1.0, tf.float32),
  139. trainable=False)
  140. self._extra_train_ops.append(moving_averages.assign_moving_average(
  141. moving_mean, mean, 0.9))
  142. self._extra_train_ops.append(moving_averages.assign_moving_average(
  143. moving_variance, variance, 0.9))
  144. else:
  145. mean = tf.get_variable(
  146. 'moving_mean', params_shape, tf.float32,
  147. initializer=tf.constant_initializer(0.0, tf.float32),
  148. trainable=False)
  149. variance = tf.get_variable(
  150. 'moving_variance', params_shape, tf.float32,
  151. initializer=tf.constant_initializer(1.0, tf.float32),
  152. trainable=False)
  153. tf.histogram_summary(mean.op.name, mean)
  154. tf.histogram_summary(variance.op.name, variance)
  155. # elipson used to be 1e-5. Maybe 0.001 solves NaN problem in deeper net.
  156. y = tf.nn.batch_normalization(
  157. x, mean, variance, beta, gamma, 0.001)
  158. y.set_shape(x.get_shape())
  159. return y
  160. def _residual(self, x, in_filter, out_filter, stride,
  161. activate_before_residual=False):
  162. """Residual unit with 2 sub layers."""
  163. if activate_before_residual:
  164. with tf.variable_scope('shared_activation'):
  165. x = self._batch_norm('init_bn', x)
  166. x = self._relu(x, self.hps.relu_leakiness)
  167. orig_x = x
  168. else:
  169. with tf.variable_scope('residual_only_activation'):
  170. orig_x = x
  171. x = self._batch_norm('init_bn', x)
  172. x = self._relu(x, self.hps.relu_leakiness)
  173. with tf.variable_scope('sub1'):
  174. x = self._conv('conv1', x, 3, in_filter, out_filter, stride)
  175. with tf.variable_scope('sub2'):
  176. x = self._batch_norm('bn2', x)
  177. x = self._relu(x, self.hps.relu_leakiness)
  178. x = self._conv('conv2', x, 3, out_filter, out_filter, [1, 1, 1, 1])
  179. with tf.variable_scope('sub_add'):
  180. if in_filter != out_filter:
  181. orig_x = tf.nn.avg_pool(orig_x, stride, stride, 'VALID')
  182. orig_x = tf.pad(
  183. orig_x, [[0, 0], [0, 0], [0, 0],
  184. [(out_filter-in_filter)//2, (out_filter-in_filter)//2]])
  185. x += orig_x
  186. tf.logging.info('image after unit %s', x.get_shape())
  187. return x
  188. def _bottleneck_residual(self, x, in_filter, out_filter, stride,
  189. activate_before_residual=False):
  190. """Bottleneck resisual unit with 3 sub layers."""
  191. if activate_before_residual:
  192. with tf.variable_scope('common_bn_relu'):
  193. x = self._batch_norm('init_bn', x)
  194. x = self._relu(x, self.hps.relu_leakiness)
  195. orig_x = x
  196. else:
  197. with tf.variable_scope('residual_bn_relu'):
  198. orig_x = x
  199. x = self._batch_norm('init_bn', x)
  200. x = self._relu(x, self.hps.relu_leakiness)
  201. with tf.variable_scope('sub1'):
  202. x = self._conv('conv1', x, 1, in_filter, out_filter/4, stride)
  203. with tf.variable_scope('sub2'):
  204. x = self._batch_norm('bn2', x)
  205. x = self._relu(x, self.hps.relu_leakiness)
  206. x = self._conv('conv2', x, 3, out_filter/4, out_filter/4, [1, 1, 1, 1])
  207. with tf.variable_scope('sub3'):
  208. x = self._batch_norm('bn3', x)
  209. x = self._relu(x, self.hps.relu_leakiness)
  210. x = self._conv('conv3', x, 1, out_filter/4, out_filter, [1, 1, 1, 1])
  211. with tf.variable_scope('sub_add'):
  212. if in_filter != out_filter:
  213. orig_x = self._conv('project', orig_x, 1, in_filter, out_filter, stride)
  214. x += orig_x
  215. tf.logging.info('image after unit %s', x.get_shape())
  216. return x
  217. def _decay(self):
  218. """L2 weight decay loss."""
  219. costs = []
  220. for var in tf.trainable_variables():
  221. if var.op.name.find(r'DW') > 0:
  222. costs.append(tf.nn.l2_loss(var))
  223. # tf.histogram_summary(var.op.name, var)
  224. return tf.mul(self.hps.weight_decay_rate, tf.add_n(costs))
  225. def _conv(self, name, x, filter_size, in_filters, out_filters, strides):
  226. """Convolution."""
  227. with tf.variable_scope(name):
  228. n = filter_size * filter_size * out_filters
  229. kernel = tf.get_variable(
  230. 'DW', [filter_size, filter_size, in_filters, out_filters],
  231. tf.float32, initializer=tf.random_normal_initializer(
  232. stddev=np.sqrt(2.0/n)))
  233. return tf.nn.conv2d(x, kernel, strides, padding='SAME')
  234. def _relu(self, x, leakiness=0.0):
  235. """Relu, with optional leaky support."""
  236. return tf.select(tf.less(x, 0.0), leakiness * x, x, name='leaky_relu')
  237. def _fully_connected(self, x, out_dim):
  238. """FullyConnected layer for final output."""
  239. x = tf.reshape(x, [self.hps.batch_size, -1])
  240. w = tf.get_variable(
  241. 'DW', [x.get_shape()[1], out_dim],
  242. initializer=tf.uniform_unit_scaling_initializer(factor=1.0))
  243. b = tf.get_variable('biases', [out_dim],
  244. initializer=tf.constant_initializer())
  245. return tf.nn.xw_plus_b(x, w, b)
  246. def _global_avg_pool(self, x):
  247. assert x.get_shape().ndims == 4
  248. return tf.reduce_mean(x, [1, 2])