Skip to content
This repository has been archived by the owner on Nov 17, 2023. It is now read-only.

MobileNetV2 #9614

Merged
merged 24 commits into from
Feb 21, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
code reformat use autopep8 and isort.
fix pylint style check error.
add docstring, disable some check.
delete duplicate code in example.
  • Loading branch information
dwSun authored and dwSun committed Feb 21, 2018
commit d91f56218c11345c17a8af9b906e5b2891e94c24
127 changes: 22 additions & 105 deletions example/image-classification/symbols/mobilenetv2.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,132 +14,44 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

# -*- coding:utf-8 -*-
'''
MobileNetV2, implemented in Gluon.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

delete duplicate and load from gluon model zoo instead.


Reference:
Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation
Inverted Residuals and Linear Bottlenecks:
Mobile Networks for Classification, Detection and Segmentation
https://arxiv.org/abs/1801.04381
'''
__author__ = 'dwSun'
__date__ = '18/1/29'
__date__ = '18/1/31'

import mxnet as mx
import mxnet.gluon.nn as nn

__all__ = ['MobileNetV2', 'get_symbol']


class BottleNeck(nn.HybridBlock):
def __init__(self, c_in, c_out, t, s, **kwargs):
super(BottleNeck, self).__init__(**kwargs)
self.use_shortcut = s == 1 and c_in == c_out
with self.name_scope():
self.out = nn.HybridSequential()
self.out.add(
nn.Conv2D(c_in * t, 1, padding=0, use_bias=False),
nn.BatchNorm(scale=True),
nn.Activation('relu'),

nn.Conv2D(c_in * t, 3, strides=s, padding=1, groups=c_in * t, use_bias=False),
nn.BatchNorm(scale=True),
nn.Activation('relu'),

nn.Conv2D(c_out, 1, padding=0, use_bias=False),
nn.BatchNorm(scale=True),
)

def hybrid_forward(self, F, x):
out = self.out(x)
if self.use_shortcut:
out = F.elemwise_add(out, x)
return out


class MobileNetV2(nn.HybridBlock):
r"""MobileNetV2 model from the
`"Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation"
<https://arxiv.org/abs/1801.04381>`_ paper.

Parameters
----------
num_classes : int, default 1000
Number of classes for the output layer.
w : float, default 1.0
The width multiplier for controling the model size. The actual number of channels
is equal to the original channel size multiplied by this multiplier.
"""
def __init__(self, num_classes=1000, w=1.0, **kwargs):
super(MobileNetV2, self).__init__(**kwargs)
with self.name_scope():
self.features = nn.HybridSequential(prefix='features_')
with self.features.name_scope():
self.features.add(
nn.Conv2D(int(32 * w), 3, strides=2, padding=1, use_bias=False),
nn.BatchNorm(scale=True),
nn.Activation('relu')
)
from mxnet.gluon.model_zoo.vision.mobilenet import MobileNetV2

self.features.add(BottleNeck(c_in=int(32 * w), c_out=int(16 * w), t=1, s=1))

self.features.add(BottleNeck(c_in=int(16 * w), c_out=int(24 * w), t=6, s=2))
self.features.add(BottleNeck(c_in=int(24 * w), c_out=int(24 * w), t=6, s=1))

self.features.add(BottleNeck(c_in=int(24 * w), c_out=int(32 * w), t=6, s=2))
self.features.add(BottleNeck(c_in=int(32 * w), c_out=int(32 * w), t=6, s=1))
self.features.add(BottleNeck(c_in=int(32 * w), c_out=int(32 * w), t=6, s=1))

self.features.add(BottleNeck(c_in=int(32 * w), c_out=int(64 * w), t=6, s=2))
self.features.add(BottleNeck(c_in=int(64 * w), c_out=int(64 * w), t=6, s=1))
self.features.add(BottleNeck(c_in=int(64 * w), c_out=int(64 * w), t=6, s=1))
self.features.add(BottleNeck(c_in=int(64 * w), c_out=int(64 * w), t=6, s=1))

self.features.add(BottleNeck(c_in=int(64 * w), c_out=int(96 * w), t=6, s=1))
self.features.add(BottleNeck(c_in=int(96 * w), c_out=int(96 * w), t=6, s=1))
self.features.add(BottleNeck(c_in=int(96 * w), c_out=int(96 * w), t=6, s=1))

self.features.add(BottleNeck(c_in=int(96 * w), c_out=int(160 * w), t=6, s=2))
self.features.add(BottleNeck(c_in=int(160 * w), c_out=int(160 * w), t=6, s=1))
self.features.add(BottleNeck(c_in=int(160 * w), c_out=int(160 * w), t=6, s=1))

self.features.add(BottleNeck(c_in=int(160 * w), c_out=int(320 * w), t=6, s=1))

last_channels = int(1280 * w) if w > 1.0 else 1280

self.features.add(
nn.Conv2D(last_channels, 1, strides=1, padding=0, use_bias=False),
nn.BatchNorm(scale=True),
nn.Activation('relu'),
)
self.features.add(nn.GlobalAvgPool2D())

self.output = nn.Conv2D(channels=num_classes, kernel_size=1, strides=1, padding=0, use_bias=False, prefix='pred_')
self.flatten = nn.Flatten(prefix='flat_')

def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
x = self.flatten(x)
return x
__all__ = ['MobileNetV2', 'get_symbol']


def get_symbol(num_classes=1000, w=1.0, ctx=mx.cpu()):
def get_symbol(num_classes=1000, multiplier=1.0, ctx=mx.cpu(), **kwargs):
r"""MobileNetV2 model from the
`"Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation"
`"Inverted Residuals and Linear Bottlenecks:
Mobile Networks for Classification, Detection and Segmentation"
<https://arxiv.org/abs/1801.04381>`_ paper.

Parameters
----------
num_classes : int, default 1000
Number of classes for the output layer.
w : float, default 1.0
multiplier : float, default 1.0
The width multiplier for controling the model size. The actual number of channels
is equal to the original channel size multiplied by this multiplier.
ctx : Context, default CPU
The context in which to initialize the model weights.
"""
net = MobileNetV2(num_classes, w)
net = MobileNetV2(multiplier=multiplier, classes=num_classes, **kwargs)
net.initialize(ctx=ctx, init=mx.init.Xavier())
net.hybridize()

Expand All @@ -149,11 +61,16 @@ def get_symbol(num_classes=1000, w=1.0, ctx=mx.cpu()):
return sym


if __name__ == '__main__':
net = MobileNetV2(1000, prefix='mob_')

data = mx.sym.var('data')
sym = net(data)
def plot_net():
"""
Visualize the network.
"""
sym = get_symbol(1000, prefix='mob_')

# plot network graph
mx.viz.plot_network(sym, shape={'data': (8, 3, 224, 224)}, node_attrs={'shape': 'oval', 'fixedsize': 'fasl==false'}).view()
mx.viz.plot_network(sym, shape={'data': (8, 3, 224, 224)},
node_attrs={'shape': 'oval', 'fixedsize': 'fasl==false'}).view()


if __name__ == '__main__':
plot_net()
5 changes: 2 additions & 3 deletions python/mxnet/gluon/model_zoo/vision/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,8 @@ def get_model(name, **kwargs):
'mobilenet1.0': mobilenet1_0,
'mobilenet0.75': mobilenet0_75,
'mobilenet0.5': mobilenet0_5,
'mobilenet0.25': mobilenet0_25,
'mobilenetv2_1.0': mobilenetv2_1_0
}
'mobilenet0.25': mobilenet0_25
}
name = name.lower()
if name not in models:
raise ValueError(
Expand Down
Loading