You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

resnet.py 8.8 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. # Copyright 2019 Huawei Technologies Co., Ltd
  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. import numpy as np
  16. import mindspore.nn as nn
  17. from mindspore import Tensor
  18. from mindspore.ops import operations as P
  19. def weight_variable_0(shape):
  20. zeros = np.zeros(shape).astype(np.float32)
  21. return Tensor(zeros)
  22. def weight_variable_1(shape):
  23. ones = np.ones(shape).astype(np.float32)
  24. return Tensor(ones)
  25. def conv3x3(in_channels, out_channels, stride=1, padding=0):
  26. """3x3 convolution """
  27. return nn.Conv2d(in_channels, out_channels,
  28. kernel_size=3, stride=stride, padding=padding, weight_init='XavierUniform',
  29. has_bias=False, pad_mode="same")
  30. def conv1x1(in_channels, out_channels, stride=1, padding=0):
  31. """1x1 convolution"""
  32. return nn.Conv2d(in_channels, out_channels,
  33. kernel_size=1, stride=stride, padding=padding, weight_init='XavierUniform',
  34. has_bias=False, pad_mode="same")
  35. def conv7x7(in_channels, out_channels, stride=1, padding=0):
  36. """1x1 convolution"""
  37. return nn.Conv2d(in_channels, out_channels,
  38. kernel_size=7, stride=stride, padding=padding, weight_init='Uniform',
  39. has_bias=False, pad_mode="same")
  40. def bn_with_initialize(out_channels):
  41. shape = (out_channels)
  42. mean = weight_variable_0(shape)
  43. var = weight_variable_1(shape)
  44. beta = weight_variable_0(shape)
  45. bn = nn.BatchNorm2d(out_channels, momentum=0.99, eps=0.00001, gamma_init='Uniform',
  46. beta_init=beta, moving_mean_init=mean, moving_var_init=var)
  47. return bn
  48. def bn_with_initialize_last(out_channels):
  49. shape = (out_channels)
  50. mean = weight_variable_0(shape)
  51. var = weight_variable_1(shape)
  52. beta = weight_variable_0(shape)
  53. bn = nn.BatchNorm2d(out_channels, momentum=0.99, eps=0.00001, gamma_init='Uniform',
  54. beta_init=beta, moving_mean_init=mean, moving_var_init=var)
  55. return bn
  56. def fc_with_initialize(input_channels, out_channels):
  57. return nn.Dense(input_channels, out_channels, weight_init='XavierUniform', bias_init='Uniform')
  58. class ResidualBlock(nn.Cell):
  59. expansion = 4
  60. def __init__(self,
  61. in_channels,
  62. out_channels,
  63. stride=1):
  64. super(ResidualBlock, self).__init__()
  65. out_chls = out_channels // self.expansion
  66. self.conv1 = conv1x1(in_channels, out_chls, stride=stride, padding=0)
  67. self.bn1 = bn_with_initialize(out_chls)
  68. self.conv2 = conv3x3(out_chls, out_chls, stride=1, padding=0)
  69. self.bn2 = bn_with_initialize(out_chls)
  70. self.conv3 = conv1x1(out_chls, out_channels, stride=1, padding=0)
  71. self.bn3 = bn_with_initialize_last(out_channels)
  72. self.relu = P.ReLU()
  73. self.add = P.TensorAdd()
  74. def construct(self, x):
  75. identity = x
  76. out = self.conv1(x)
  77. out = self.bn1(out)
  78. out = self.relu(out)
  79. out = self.conv2(out)
  80. out = self.bn2(out)
  81. out = self.relu(out)
  82. out = self.conv3(out)
  83. out = self.bn3(out)
  84. out = self.add(out, identity)
  85. out = self.relu(out)
  86. return out
  87. class ResidualBlockWithDown(nn.Cell):
  88. expansion = 4
  89. def __init__(self,
  90. in_channels,
  91. out_channels,
  92. stride=1,
  93. down_sample=False):
  94. super(ResidualBlockWithDown, self).__init__()
  95. out_chls = out_channels // self.expansion
  96. self.conv1 = conv1x1(in_channels, out_chls, stride=stride, padding=0)
  97. self.bn1 = bn_with_initialize(out_chls)
  98. self.conv2 = conv3x3(out_chls, out_chls, stride=1, padding=0)
  99. self.bn2 = bn_with_initialize(out_chls)
  100. self.conv3 = conv1x1(out_chls, out_channels, stride=1, padding=0)
  101. self.bn3 = bn_with_initialize_last(out_channels)
  102. self.relu = P.ReLU()
  103. self.downSample = down_sample
  104. self.conv_down_sample = conv1x1(in_channels, out_channels, stride=stride, padding=0)
  105. self.bn_down_sample = bn_with_initialize(out_channels)
  106. self.add = P.TensorAdd()
  107. def construct(self, x):
  108. identity = x
  109. out = self.conv1(x)
  110. out = self.bn1(out)
  111. out = self.relu(out)
  112. out = self.conv2(out)
  113. out = self.bn2(out)
  114. out = self.relu(out)
  115. out = self.conv3(out)
  116. out = self.bn3(out)
  117. identity = self.conv_down_sample(identity)
  118. identity = self.bn_down_sample(identity)
  119. out = self.add(out, identity)
  120. out = self.relu(out)
  121. return out
  122. class MakeLayer0(nn.Cell):
  123. def __init__(self, block, in_channels, out_channels, stride):
  124. super(MakeLayer0, self).__init__()
  125. self.a = ResidualBlockWithDown(in_channels, out_channels, stride=1, down_sample=True)
  126. self.b = block(out_channels, out_channels, stride=stride)
  127. self.c = block(out_channels, out_channels, stride=1)
  128. def construct(self, x):
  129. x = self.a(x)
  130. x = self.b(x)
  131. x = self.c(x)
  132. return x
  133. class MakeLayer1(nn.Cell):
  134. def __init__(self, block, in_channels, out_channels, stride):
  135. super(MakeLayer1, self).__init__()
  136. self.a = ResidualBlockWithDown(in_channels, out_channels, stride=stride, down_sample=True)
  137. self.b = block(out_channels, out_channels, stride=1)
  138. self.c = block(out_channels, out_channels, stride=1)
  139. self.d = block(out_channels, out_channels, stride=1)
  140. def construct(self, x):
  141. x = self.a(x)
  142. x = self.b(x)
  143. x = self.c(x)
  144. x = self.d(x)
  145. return x
  146. class MakeLayer2(nn.Cell):
  147. def __init__(self, block, in_channels, out_channels, stride):
  148. super(MakeLayer2, self).__init__()
  149. self.a = ResidualBlockWithDown(in_channels, out_channels, stride=stride, down_sample=True)
  150. self.b = block(out_channels, out_channels, stride=1)
  151. self.c = block(out_channels, out_channels, stride=1)
  152. self.d = block(out_channels, out_channels, stride=1)
  153. self.e = block(out_channels, out_channels, stride=1)
  154. self.f = block(out_channels, out_channels, stride=1)
  155. def construct(self, x):
  156. x = self.a(x)
  157. x = self.b(x)
  158. x = self.c(x)
  159. x = self.d(x)
  160. x = self.e(x)
  161. x = self.f(x)
  162. return x
  163. class MakeLayer3(nn.Cell):
  164. def __init__(self, block, in_channels, out_channels, stride):
  165. super(MakeLayer3, self).__init__()
  166. self.a = ResidualBlockWithDown(in_channels, out_channels, stride=stride, down_sample=True)
  167. self.b = block(out_channels, out_channels, stride=1)
  168. self.c = block(out_channels, out_channels, stride=1)
  169. def construct(self, x):
  170. x = self.a(x)
  171. x = self.b(x)
  172. x = self.c(x)
  173. return x
  174. class ResNet(nn.Cell):
  175. def __init__(self, block, num_classes=100, batch_size=32):
  176. super(ResNet, self).__init__()
  177. self.batch_size = batch_size
  178. self.num_classes = num_classes
  179. self.conv1 = conv7x7(3, 64, stride=2, padding=0)
  180. self.bn1 = bn_with_initialize(64)
  181. self.relu = P.ReLU()
  182. self.maxpool = P.MaxPoolWithArgmax(kernel_size=3, strides=2, pad_mode="SAME")
  183. self.layer1 = MakeLayer0(block, in_channels=64, out_channels=256, stride=1)
  184. self.layer2 = MakeLayer1(block, in_channels=256, out_channels=512, stride=2)
  185. self.layer3 = MakeLayer2(block, in_channels=512, out_channels=1024, stride=2)
  186. self.layer4 = MakeLayer3(block, in_channels=1024, out_channels=2048, stride=2)
  187. self.pool = P.ReduceMean(keep_dims=True)
  188. self.squeeze = P.Squeeze(axis=(2, 3))
  189. self.fc = fc_with_initialize(512 * block.expansion, num_classes)
  190. def construct(self, x):
  191. x = self.conv1(x)
  192. x = self.bn1(x)
  193. x = self.relu(x)
  194. x = self.maxpool(x)[0]
  195. x = self.layer1(x)
  196. x = self.layer2(x)
  197. x = self.layer3(x)
  198. x = self.layer4(x)
  199. x = self.pool(x, (2, 3))
  200. x = self.squeeze(x)
  201. x = self.fc(x)
  202. return x
  203. def resnet50(batch_size, num_classes):
  204. return ResNet(ResidualBlock, num_classes, batch_size)