Mxnet 网络可视化(MobileNetV2)

红太狼 2022-04-10 01:48 434阅读 0赞
  1. import matplotlib
  2. matplotlib.use('Agg')
  3. import argparse,time,logging
  4. import mxnet as mx
  5. import numpy as np
  6. from mxnet import gluon,nd
  7. from mxnet.gluon import nn
  8. from mxnet.gluon.data.vision import transforms
  9. from gluoncv.data import imagenet
  10. from gluoncv.utils import makedirs, TrainingHistory
  11. import os
  12. from mxnet.context import cpu
  13. from mxnet.gluon.block import HybridBlock
  14. from mxnet.gluon.contrib.nn import HybridConcurrent
  15. import multiprocessing
  16. import logging
  17. logging.basicConfig(level=logging.INFO)
  18. ##This block contains definition for Mobilenet v2
  19. # Helpers
  20. class RELU6(nn.HybridBlock):
  21. """Relu6 used in MobileNetV2."""
  22. def __init__(self, **kwargs):
  23. super(RELU6, self).__init__(**kwargs)
  24. def hybrid_forward(self, F, x):
  25. return F.clip(x, 0, 6, name="relu6")
  26. def _add_conv(out, channels=1, kernel=1, stride=1, pad=0,
  27. num_group=1, active=True, relu6=False):
  28. out.add(nn.Conv2D(channels, kernel, stride, pad, groups=num_group, use_bias=False))
  29. out.add(nn.BatchNorm(scale=True))
  30. if active:
  31. out.add(RELU6() if relu6 else nn.Activation('relu'))
  32. def _add_conv_dw(out, dw_channels, channels, stride, relu6=False):
  33. _add_conv(out, channels=dw_channels, kernel=3, stride=stride,
  34. pad=1, num_group=dw_channels, relu6=relu6)
  35. _add_conv(out, channels=channels, relu6=relu6)
  36. class LinearBottleneck(nn.HybridBlock):
  37. r"""LinearBottleneck used in MobileNetV2 model from the
  38. `"Inverted Residuals and Linear Bottlenecks:
  39. Mobile Networks for Classification, Detection and Segmentation"
  40. <https://arxiv.org/abs/1801.04381>`_ paper.
  41. Parameters
  42. ----------
  43. in_channels : int
  44. Number of input channels.
  45. channels : int
  46. Number of output channels.
  47. t : int
  48. Layer expansion ratio.
  49. stride : int
  50. stride
  51. """
  52. def __init__(self, in_channels, channels, t, stride, **kwargs):
  53. super(LinearBottleneck, self).__init__(**kwargs)
  54. self.use_shortcut = stride == 1 and in_channels == channels
  55. with self.name_scope():
  56. self.out = nn.HybridSequential()
  57. _add_conv(self.out, in_channels * t, relu6=True)
  58. _add_conv(self.out, in_channels * t, kernel=3, stride=stride,
  59. pad=1, num_group=in_channels * t, relu6=True)
  60. _add_conv(self.out, channels, active=False, relu6=True)
  61. def hybrid_forward(self, F, x):
  62. out = self.out(x)
  63. if self.use_shortcut:
  64. out = F.elemwise_add(out, x)
  65. return out
  66. # Net
  67. class MobileNetV2(nn.HybridBlock):
  68. r"""MobileNetV2 model from the
  69. `"Inverted Residuals and Linear Bottlenecks:
  70. Mobile Networks for Classification, Detection and Segmentation"
  71. <https://arxiv.org/abs/1801.04381>`_ paper.
  72. Parameters
  73. ----------
  74. multiplier : float, default 1.0
  75. The width multiplier for controling the model size. The actual number of channels
  76. is equal to the original channel size multiplied by this multiplier.
  77. classes : int, default 1000
  78. Number of classes for the output layer.
  79. """
  80. def __init__(self, multiplier=1.0, classes=1000, **kwargs):
  81. super(MobileNetV2, self).__init__(**kwargs)
  82. with self.name_scope():
  83. self.features = nn.HybridSequential(prefix='features_')
  84. with self.features.name_scope():
  85. _add_conv(self.features, int(32 * multiplier), kernel=3,
  86. stride=2, pad=1, relu6=True)
  87. in_channels_group = [int(x * multiplier) for x in [32] + [16] + [24] * 2
  88. + [32] * 3 + [64] * 4 + [96] * 3 + [160] * 3]
  89. channels_group = [int(x * multiplier) for x in [16] + [24] * 2 + [32] * 3
  90. + [64] * 4 + [96] * 3 + [160] * 3 + [320]]
  91. ts = [1] + [6] * 16
  92. strides = [1, 2] * 2 + [1, 1, 2] + [1] * 6 + [2] + [1] * 3
  93. for in_c, c, t, s in zip(in_channels_group, channels_group, ts, strides):
  94. self.features.add(LinearBottleneck(in_channels=in_c, channels=c,
  95. t=t, stride=s))
  96. last_channels = int(1280 * multiplier) if multiplier > 1.0 else 1280
  97. _add_conv(self.features, last_channels, relu6=True)
  98. self.features.add(nn.GlobalAvgPool2D())
  99. self.output = nn.HybridSequential(prefix='output_')
  100. with self.output.name_scope():
  101. self.output.add(
  102. nn.Conv2D(classes, 1, use_bias=False, prefix='pred_'),
  103. nn.Flatten()
  104. )
  105. def hybrid_forward(self, F, x):
  106. x = self.features(x)
  107. x = self.output(x)
  108. return x
  109. # Constructor
  110. def get_mobilenet_v2(multiplier, **kwargs):
  111. r"""MobileNetV2 model from the
  112. `"Inverted Residuals and Linear Bottlenecks:
  113. Mobile Networks for Classification, Detection and Segmentation"
  114. <https://arxiv.org/abs/1801.04381>`_ paper.
  115. Parameters
  116. ----------
  117. multiplier : float
  118. The width multiplier for controling the model size. Only multipliers that are no
  119. less than 0.25 are supported. The actual number of channels is equal to the original
  120. channel size multiplied by this multiplier.
  121. """
  122. net = MobileNetV2(multiplier, **kwargs)
  123. return net
  124. def mobilenet_v2_1_0(**kwargs):
  125. r"""MobileNetV2 model from the
  126. `"Inverted Residuals and Linear Bottlenecks:
  127. Mobile Networks for Classification, Detection and Segmentation"
  128. <https://arxiv.org/abs/1801.04381>`_ paper.
  129. """
  130. return get_mobilenet_v2(1.0, **kwargs)
  131. def mobilenet_v2_0_5(**kwargs):
  132. r"""MobileNetV2 model from the
  133. `"Inverted Residuals and Linear Bottlenecks:
  134. Mobile Networks for Classification, Detection and Segmentation"
  135. <https://arxiv.org/abs/1801.04381>`_ paper.
  136. """
  137. return get_mobilenet_v2(0.5, **kwargs)
  138. models = {
  139. 'mobilenetv2_1.0': mobilenet_v2_1_0,
  140. 'mobilenetv2_0.5': mobilenet_v2_0_5
  141. }
  142. kwargs={'classes':1000}
  143. # Retireve gluon model
  144. net = models['mobilenetv2_1.0'](**kwargs)
  145. ctx = mx.cpu(0)
  146. net.hybridize()
  147. net.initialize(mx.init.MSRAPrelu(), ctx=ctx)
  148. # 可视化网络
  149. x = mx.sym.var('data')
  150. sym = net(x)
  151. mx.viz.plot_network(sym,node_attrs={"shape":'oval',"fixedsize":'false'}).view() #pycharm使用必须加view()

发表评论

表情:
评论列表 (有 0 条评论,434人围观)

还没有评论,来说两句吧...

相关阅读

    相关 MobileNetV2

    什么是MobileNetV2模型 MobileNet模型是Google针对手机等嵌入式设备提出的一种轻量级的深层神经网络,其使用的核心思想便是depthwise sepa

    相关 基于PyCaffe实现网络

    前言 在进行深度学习网络调试参数的时候,往往是将整个训练过程完了之后查看训练的结果。但是除了这种办法之外还可以通过网络可视化来帮助进行参数调试,这里封装了一个小小的类,提