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.

vgg.py 5.4 kB

5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. # Copyright 2020 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. """
  16. Image classifiation.
  17. """
  18. import math
  19. import mindspore.nn as nn
  20. import mindspore.common.dtype as mstype
  21. from mindspore.common import initializer as init
  22. from mindspore.common.initializer import initializer
  23. from .utils.var_init import default_recurisive_init, KaimingNormal
  24. def _make_layer(base, args, batch_norm):
  25. """Make stage network of VGG."""
  26. layers = []
  27. in_channels = 3
  28. for v in base:
  29. if v == 'M':
  30. layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
  31. else:
  32. weight_shape = (v, in_channels, 3, 3)
  33. weight = initializer('XavierUniform', shape=weight_shape, dtype=mstype.float32).to_tensor()
  34. if args.initialize_mode == "KaimingNormal":
  35. weight = 'normal'
  36. conv2d = nn.Conv2d(in_channels=in_channels,
  37. out_channels=v,
  38. kernel_size=3,
  39. padding=args.padding,
  40. pad_mode=args.pad_mode,
  41. has_bias=args.has_bias,
  42. weight_init=weight)
  43. if batch_norm:
  44. layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU()]
  45. else:
  46. layers += [conv2d, nn.ReLU()]
  47. in_channels = v
  48. return nn.SequentialCell(layers)
  49. class Vgg(nn.Cell):
  50. """
  51. VGG network definition.
  52. Args:
  53. base (list): Configuration for different layers, mainly the channel number of Conv layer.
  54. num_classes (int): Class numbers. Default: 1000.
  55. batch_norm (bool): Whether to do the batchnorm. Default: False.
  56. batch_size (int): Batch size. Default: 1.
  57. Returns:
  58. Tensor, infer output tensor.
  59. Examples:
  60. >>> Vgg([64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
  61. >>> num_classes=1000, batch_norm=False, batch_size=1)
  62. """
  63. def __init__(self, base, num_classes=1000, batch_norm=False, batch_size=1, args=None, phase="train"):
  64. super(Vgg, self).__init__()
  65. _ = batch_size
  66. self.layers = _make_layer(base, args, batch_norm=batch_norm)
  67. self.flatten = nn.Flatten()
  68. dropout_ratio = 0.5
  69. if not args.has_dropout or phase == "test":
  70. dropout_ratio = 1.0
  71. self.classifier = nn.SequentialCell([
  72. nn.Dense(512 * 7 * 7, 4096),
  73. nn.ReLU(),
  74. nn.Dropout(dropout_ratio),
  75. nn.Dense(4096, 4096),
  76. nn.ReLU(),
  77. nn.Dropout(dropout_ratio),
  78. nn.Dense(4096, num_classes)])
  79. if args.initialize_mode == "KaimingNormal":
  80. default_recurisive_init(self)
  81. self.custom_init_weight()
  82. def construct(self, x):
  83. x = self.layers(x)
  84. x = self.flatten(x)
  85. x = self.classifier(x)
  86. return x
  87. def custom_init_weight(self):
  88. """
  89. Init the weight of Conv2d and Dense in the net.
  90. """
  91. for _, cell in self.cells_and_names():
  92. if isinstance(cell, nn.Conv2d):
  93. cell.weight.default_input = init.initializer(
  94. KaimingNormal(a=math.sqrt(5), mode='fan_out', nonlinearity='relu'),
  95. cell.weight.shape, cell.weight.dtype)
  96. if cell.bias is not None:
  97. cell.bias.default_input = init.initializer(
  98. 'zeros', cell.bias.shape, cell.bias.dtype)
  99. elif isinstance(cell, nn.Dense):
  100. cell.weight.default_input = init.initializer(
  101. init.Normal(0.01), cell.weight.shape, cell.weight.dtype)
  102. if cell.bias is not None:
  103. cell.bias.default_input = init.initializer(
  104. 'zeros', cell.bias.shape, cell.bias.dtype)
  105. cfg = {
  106. '11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
  107. '13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
  108. '16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
  109. '19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
  110. }
  111. def vgg16(num_classes=1000, args=None, phase="train"):
  112. """
  113. Get Vgg16 neural network with batch normalization.
  114. Args:
  115. num_classes (int): Class numbers. Default: 1000.
  116. args(namespace): param for net init.
  117. phase(str): train or test mode.
  118. Returns:
  119. Cell, cell instance of Vgg16 neural network with batch normalization.
  120. Examples:
  121. >>> vgg16(num_classes=1000, args=args)
  122. """
  123. net = Vgg(cfg['16'], num_classes=num_classes, args=args, batch_norm=args.batch_norm, phase=phase)
  124. return net