alexnet.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
  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. import math
  15. import paddle
  16. import paddle.nn.functional as F
  17. from paddle import nn
  18. from paddle.base.param_attr import ParamAttr
  19. from paddle.nn import Conv2D, Dropout, Linear, MaxPool2D, ReLU
  20. from paddle.nn.initializer import Uniform
  21. from paddle.utils.download import get_weights_path_from_url
  22. model_urls = {
  23. "alexnet": (
  24. "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/AlexNet_pretrained.pdparams",
  25. "7f0f9f737132e02732d75a1459d98a43",
  26. )
  27. }
  28. __all__ = []
  29. class ConvPoolLayer(nn.Layer):
  30. def __init__(
  31. self,
  32. input_channels,
  33. output_channels,
  34. filter_size,
  35. stride,
  36. padding,
  37. stdv,
  38. groups=1,
  39. act=None,
  40. ):
  41. super().__init__()
  42. self.relu = ReLU() if act == "relu" else None
  43. self._conv = Conv2D(
  44. in_channels=input_channels,
  45. out_channels=output_channels,
  46. kernel_size=filter_size,
  47. stride=stride,
  48. padding=padding,
  49. groups=groups,
  50. weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
  51. bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
  52. )
  53. self._pool = MaxPool2D(kernel_size=3, stride=2, padding=0)
  54. def forward(self, inputs):
  55. x = self._conv(inputs)
  56. if self.relu is not None:
  57. x = self.relu(x)
  58. x = self._pool(x)
  59. return x
  60. class AlexNet(nn.Layer):
  61. """AlexNet model from
  62. `"ImageNet Classification with Deep Convolutional Neural Networks"
  63. <https://proceedings.neurips.cc/paper/2012/file/c399862d3b9d6b76c8436e924a68c45b-Paper.pdf>`_.
  64. Args:
  65. num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer
  66. will not be defined. Default: 1000.
  67. Returns:
  68. :ref:`api_paddle_nn_Layer`. An instance of AlexNet model.
  69. Examples:
  70. .. code-block:: python
  71. >>> import paddle
  72. >>> from paddle.vision.models import AlexNet
  73. >>> alexnet = AlexNet()
  74. >>> x = paddle.rand([1, 3, 224, 224])
  75. >>> out = alexnet(x)
  76. >>> print(out.shape)
  77. [1, 1000]
  78. """
  79. def __init__(self, num_classes=1000):
  80. super().__init__()
  81. self.num_classes = num_classes
  82. stdv = 1.0 / math.sqrt(3 * 11 * 11)
  83. self._conv1 = ConvPoolLayer(3, 64, 11, 4, 2, stdv, act="relu")
  84. stdv = 1.0 / math.sqrt(64 * 5 * 5)
  85. self._conv2 = ConvPoolLayer(64, 192, 5, 1, 2, stdv, act="relu")
  86. stdv = 1.0 / math.sqrt(192 * 3 * 3)
  87. self._conv3 = Conv2D(
  88. 192,
  89. 384,
  90. 3,
  91. stride=1,
  92. padding=1,
  93. weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
  94. bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
  95. )
  96. stdv = 1.0 / math.sqrt(384 * 3 * 3)
  97. self._conv4 = Conv2D(
  98. 384,
  99. 256,
  100. 3,
  101. stride=1,
  102. padding=1,
  103. weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
  104. bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
  105. )
  106. stdv = 1.0 / math.sqrt(256 * 3 * 3)
  107. self._conv5 = ConvPoolLayer(256, 256, 3, 1, 1, stdv, act="relu")
  108. if self.num_classes > 0:
  109. stdv = 1.0 / math.sqrt(256 * 6 * 6)
  110. self._drop1 = Dropout(p=0.5, mode="downscale_in_infer")
  111. self._fc6 = Linear(
  112. in_features=256 * 6 * 6,
  113. out_features=4096,
  114. weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
  115. bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
  116. )
  117. self._drop2 = Dropout(p=0.5, mode="downscale_in_infer")
  118. self._fc7 = Linear(
  119. in_features=4096,
  120. out_features=4096,
  121. weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
  122. bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
  123. )
  124. self._fc8 = Linear(
  125. in_features=4096,
  126. out_features=num_classes,
  127. weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
  128. bias_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
  129. )
  130. def forward(self, inputs):
  131. x = self._conv1(inputs)
  132. x = self._conv2(x)
  133. x = self._conv3(x)
  134. x = F.relu(x)
  135. x = self._conv4(x)
  136. x = F.relu(x)
  137. x = self._conv5(x)
  138. if self.num_classes > 0:
  139. x = paddle.flatten(x, start_axis=1, stop_axis=-1)
  140. x = self._drop1(x)
  141. x = self._fc6(x)
  142. x = F.relu(x)
  143. x = self._drop2(x)
  144. x = self._fc7(x)
  145. x = F.relu(x)
  146. x = self._fc8(x)
  147. return x
  148. def _alexnet(arch, pretrained, **kwargs):
  149. model = AlexNet(**kwargs)
  150. if pretrained:
  151. assert (
  152. arch in model_urls
  153. ), f"{arch} model do not have a pretrained model now, you should set pretrained=False"
  154. weight_path = get_weights_path_from_url(
  155. model_urls[arch][0], model_urls[arch][1]
  156. )
  157. param = paddle.load(weight_path)
  158. model.load_dict(param)
  159. return model
  160. def alexnet(pretrained=False, **kwargs):
  161. """AlexNet model from
  162. `"ImageNet Classification with Deep Convolutional Neural Networks"
  163. <https://proceedings.neurips.cc/paper/2012/file/c399862d3b9d6b76c8436e924a68c45b-Paper.pdf>`_.
  164. Args:
  165. pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained
  166. on ImageNet. Default: False.
  167. **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`AlexNet <api_paddle_vision_AlexNet>`.
  168. Returns:
  169. :ref:`api_paddle_nn_Layer`. An instance of AlexNet model.
  170. Examples:
  171. .. code-block:: python
  172. >>> import paddle
  173. >>> from paddle.vision.models import alexnet
  174. >>> # Build model
  175. >>> model = alexnet()
  176. >>> # Build model and load imagenet pretrained weight
  177. >>> # model = alexnet(pretrained=True)
  178. >>> x = paddle.rand([1, 3, 224, 224])
  179. >>> out = model(x)
  180. >>> print(out.shape)
  181. [1, 1000]
  182. """
  183. return _alexnet('alexnet', pretrained, **kwargs)