You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mxnet.apache.org by jx...@apache.org on 2017/09/17 18:28:00 UTC

[incubator-mxnet] branch master updated: add mobilenet to gluon model zoo (#7875)

This is an automated email from the ASF dual-hosted git repository.

jxie pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-mxnet.git


The following commit(s) were added to refs/heads/master by this push:
     new 01ec708  add mobilenet to gluon model zoo (#7875)
01ec708 is described below

commit 01ec7084d3665fceae307451d843c8d18db68c68
Author: Sheng Zha <sz...@users.noreply.github.com>
AuthorDate: Sun Sep 17 11:27:57 2017 -0700

    add mobilenet to gluon model zoo (#7875)
    
    * add mobilenet to gluon model zoo
    
    * update
    
    * simplify
    
    * doc string for multiplier
    
    * rename variables
---
 python/mxnet/gluon/model_zoo/vision/__init__.py  |   6 +
 python/mxnet/gluon/model_zoo/vision/mobilenet.py | 157 +++++++++++++++++++++++
 tests/python/unittest/test_gluon_model_zoo.py    |   3 +-
 3 files changed, 165 insertions(+), 1 deletion(-)

diff --git a/python/mxnet/gluon/model_zoo/vision/__init__.py b/python/mxnet/gluon/model_zoo/vision/__init__.py
index 354236b..26d89f1 100644
--- a/python/mxnet/gluon/model_zoo/vision/__init__.py
+++ b/python/mxnet/gluon/model_zoo/vision/__init__.py
@@ -81,6 +81,8 @@ from .squeezenet import *
 
 from .vgg import *
 
+from .mobilenet import *
+
 def get_model(name, **kwargs):
     """Returns a pre-defined model by name
 
@@ -124,6 +126,10 @@ def get_model(name, **kwargs):
               'squeezenet1.0': squeezenet1_0,
               'squeezenet1.1': squeezenet1_1,
               'inceptionv3': inception_v3,
+              'mobilenet1.0': mobilenet1_0,
+              'mobilenet0.75': mobilenet0_75,
+              'mobilenet0.5': mobilenet0_5,
+              'mobilenet0.25': mobilenet0_25
              }
     name = name.lower()
     if name not in models:
diff --git a/python/mxnet/gluon/model_zoo/vision/mobilenet.py b/python/mxnet/gluon/model_zoo/vision/mobilenet.py
new file mode 100644
index 0000000..8511d2c
--- /dev/null
+++ b/python/mxnet/gluon/model_zoo/vision/mobilenet.py
@@ -0,0 +1,157 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# coding: utf-8
+# pylint: disable= arguments-differ
+"""MobileNet, implemented in Gluon."""
+__all__ = ['MobileNet', 'mobilenet1_0', 'mobilenet0_75', 'mobilenet0_5', 'mobilenet0_25',
+           'get_mobilenet']
+
+from ....context import cpu
+from ...block import HybridBlock
+from ... import nn
+
+# Helpers
+def _add_conv(out, channels=1, kernel=1, stride=1, pad=0, num_group=1):
+    out.add(nn.Conv2D(channels, kernel, stride, pad, groups=num_group, use_bias=False))
+    out.add(nn.BatchNorm(scale=False))
+    out.add(nn.Activation('relu'))
+
+def _add_conv_dw(out, dw_channels, channels, stride):
+    _add_conv(out, channels=dw_channels, kernel=3, stride=stride, pad=1, num_group=dw_channels)
+    _add_conv(out, channels=channels)
+
+
+# Net
+class MobileNet(HybridBlock):
+    r"""MobileNet model from the
+    `"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
+    <https://arxiv.org/abs/1704.04861>`_ paper.
+
+    Parameters
+    ----------
+    multiplier : float, default 1.0
+        The width multiplier for controling the model size. Only multipliers that are no
+        less than 0.25 are supported. The actual number of channels is equal to the original
+        channel size multiplied by this multiplier.
+    classes : int, default 1000
+        Number of classes for the output layer.
+    """
+    def __init__(self, multiplier=1.0, classes=1000, **kwargs):
+        super(MobileNet, self).__init__(**kwargs)
+        with self.name_scope():
+            self.features = nn.HybridSequential(prefix='')
+            with self.features.name_scope():
+                _add_conv(self.features, channels=int(32*multiplier), kernel=3, pad=1, stride=2)
+                dw_channels = [int(x*multiplier) for x in [32, 64]+[128]*2+[256]*2+[512]*6+[1024]]
+                channels = [int(x*multiplier) for x in [64]+[128]*2+[256]*2+[512]*6+[1024]*2]
+                strides = [1, 2] * 3 + [1] * 5 + [2, 1]
+                for dwc, c, s in zip(dw_channels, channels, strides):
+                    _add_conv_dw(self.features, dw_channels=dwc, channels=c, stride=s)
+                self.features.add(nn.GlobalAvgPool2D())
+                self.features.add(nn.Flatten())
+
+            self.classifier = nn.HybridSequential(prefix='')
+            with self.classifier.name_scope():
+                self.classifier.add(nn.Dense(classes))
+
+    def hybrid_forward(self, F, x):
+        x = self.features(x)
+        x = self.classifier(x)
+        return x
+
+# Constructor
+def get_mobilenet(multiplier, pretrained=False, ctx=cpu(), **kwargs):
+    r"""MobileNet model from the
+    `"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
+    <https://arxiv.org/abs/1704.04861>`_ paper.
+
+    Parameters
+    ----------
+    multiplier : float
+        The width multiplier for controling the model size. Only multipliers that are no
+        less than 0.25 are supported. The actual number of channels is equal to the original
+        channel size multiplied by this multiplier.
+    pretrained : bool, default False
+        Whether to load the pretrained weights for model.
+    ctx : Context, default CPU
+        The context in which to load the pretrained weights.
+    """
+    net = MobileNet(multiplier, **kwargs)
+    if pretrained:
+        from ..model_store import get_model_file
+        version_suffix = '{0:.2f}'.format(multiplier)
+        if version_suffix in ('1.00', '0.50'):
+            version_suffix = version_suffix[:-1]
+        net.load_params(get_model_file('mobilenet%s'%version_suffix), ctx=ctx)
+    return net
+
+def mobilenet1_0(**kwargs):
+    r"""MobileNet model from the
+    `"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
+    <https://arxiv.org/abs/1704.04861>`_ paper, with width multiplier 1.0.
+
+    Parameters
+    ----------
+    pretrained : bool, default False
+        Whether to load the pretrained weights for model.
+    ctx : Context, default CPU
+        The context in which to load the pretrained weights.
+    """
+    return get_mobilenet(1.0, **kwargs)
+
+def mobilenet0_75(**kwargs):
+    r"""MobileNet model from the
+    `"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
+    <https://arxiv.org/abs/1704.04861>`_ paper, with width multiplier 0.75.
+
+    Parameters
+    ----------
+    pretrained : bool, default False
+        Whether to load the pretrained weights for model.
+    ctx : Context, default CPU
+        The context in which to load the pretrained weights.
+    """
+    return get_mobilenet(0.75, **kwargs)
+
+def mobilenet0_5(**kwargs):
+    r"""MobileNet model from the
+    `"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
+    <https://arxiv.org/abs/1704.04861>`_ paper, with width multiplier 0.5.
+
+    Parameters
+    ----------
+    pretrained : bool, default False
+        Whether to load the pretrained weights for model.
+    ctx : Context, default CPU
+        The context in which to load the pretrained weights.
+    """
+    return get_mobilenet(0.5, **kwargs)
+
+def mobilenet0_25(**kwargs):
+    r"""MobileNet model from the
+    `"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
+    <https://arxiv.org/abs/1704.04861>`_ paper, with width multiplier 0.25.
+
+    Parameters
+    ----------
+    pretrained : bool, default False
+        Whether to load the pretrained weights for model.
+    ctx : Context, default CPU
+        The context in which to load the pretrained weights.
+    """
+    return get_mobilenet(0.25, **kwargs)
diff --git a/tests/python/unittest/test_gluon_model_zoo.py b/tests/python/unittest/test_gluon_model_zoo.py
index 756979d..61c1681 100644
--- a/tests/python/unittest/test_gluon_model_zoo.py
+++ b/tests/python/unittest/test_gluon_model_zoo.py
@@ -57,7 +57,8 @@ def test_models():
                   'vgg11_bn', 'vgg13_bn', 'vgg16_bn', 'vgg19_bn',
                   'alexnet', 'inceptionv3',
                   'densenet121', 'densenet161', 'densenet169', 'densenet201',
-                  'squeezenet1.0', 'squeezenet1.1']
+                  'squeezenet1.0', 'squeezenet1.1',
+                  'mobilenet1.0', 'mobilenet0.75', 'mobilenet0.5', 'mobilenet0.25']
     pretrained_to_test = set(['squeezenet1.1'])
 
     for model_name in all_models:

-- 
To stop receiving notification emails like this one, please contact
['"commits@mxnet.apache.org" <co...@mxnet.apache.org>'].