repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/crunet.py | """
CRU-Net, implemented in Gluon.
Original paper: 'Sharing Residual Units Through Collective Tensor Factorization To Improve Deep Neural Networks,'
https://www.ijcai.org/proceedings/2018/88.
"""
__all__ = ['CRUNet', 'crunet56', 'crunet116']
import os
import math
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import pre_conv1x1_block, pre_conv3x3_block
from .resnet import ResInitBlock
from .preresnet import PreResActivation
def cru_conv3x3(in_channels,
out_channels,
strides=1,
padding=1,
groups=1,
use_bias=False,
conv_params=None):
"""
CRU-Net specific convolution 3x3 layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
"""
return nn.Conv2D(
channels=out_channels,
kernel_size=3,
strides=strides,
padding=padding,
groups=groups,
use_bias=use_bias,
in_channels=in_channels,
params=conv_params)
class CRUConvBlock(HybridBlock):
"""
CRU-Net specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
groups : int, default 1
Number of groups.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
return_preact : bool, default False
Whether return pre-activation. It's used by PreResNet.
conv_params : ParameterDict, default None
Weights for the convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
groups=1,
bn_use_global_stats=False,
return_preact=False,
conv_params=None,
**kwargs):
super(CRUConvBlock, self).__init__(**kwargs)
self.return_preact = return_preact
with self.name_scope():
self.bn = nn.BatchNorm(
in_channels=in_channels,
use_global_stats=bn_use_global_stats)
self.activ = nn.Activation("relu")
self.conv = nn.Conv2D(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
groups=groups,
use_bias=False,
in_channels=in_channels,
params=conv_params)
def hybrid_forward(self, F, x):
x = self.bn(x)
x = self.activ(x)
if self.return_preact:
x_pre_activ = x
x = self.conv(x)
if self.return_preact:
return x, x_pre_activ
else:
return x
def cru_conv1x1_block(in_channels,
out_channels,
strides=1,
bn_use_global_stats=False,
return_preact=False,
conv_params=None):
"""
1x1 version of the CRU-Net specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
return_preact : bool, default False
Whether return pre-activation.
conv_params : ParameterDict, default None
Weights for the convolution layer.
"""
return CRUConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
strides=strides,
padding=0,
bn_use_global_stats=bn_use_global_stats,
return_preact=return_preact,
conv_params=conv_params)
class ResBottleneck(HybridBlock):
"""
Pre-ResNeXt bottleneck block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
cardinality,
bottleneck_width,
bn_use_global_stats,
**kwargs):
super(ResBottleneck, self).__init__(**kwargs)
mid_channels = out_channels // 4
D = int(math.floor(mid_channels * (bottleneck_width / 64.0)))
group_width = cardinality * D
with self.name_scope():
self.conv1 = pre_conv1x1_block(
in_channels=in_channels,
out_channels=group_width,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = pre_conv3x3_block(
in_channels=group_width,
out_channels=group_width,
strides=strides,
groups=cardinality,
bn_use_global_stats=bn_use_global_stats)
self.conv3 = pre_conv1x1_block(
in_channels=group_width,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class CRUBottleneck(HybridBlock):
"""
CRU-Net bottleneck block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
group_width: int
Group width parameter.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
conv1_params : ParameterDict, default None
Weights for the convolution layer #1.
conv2_params : ParameterDict, default None
Weights for the convolution layer #2.
"""
def __init__(self,
in_channels,
out_channels,
strides,
group_width,
bn_use_global_stats,
conv1_params=None,
conv2_params=None,
**kwargs):
super(CRUBottleneck, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = cru_conv1x1_block(
in_channels=in_channels,
out_channels=group_width,
bn_use_global_stats=bn_use_global_stats,
conv_params=conv1_params)
self.conv2 = cru_conv3x3(
in_channels=group_width,
out_channels=group_width,
strides=strides,
groups=group_width,
conv_params=conv2_params)
self.conv3 = pre_conv1x1_block(
in_channels=group_width,
out_channels=group_width,
bn_use_global_stats=bn_use_global_stats)
self.conv4 = pre_conv1x1_block(
in_channels=group_width,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.conv4(x)
return x
class ResUnit(HybridBlock):
"""
CRU-Net residual unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
cardinality,
bottleneck_width,
bn_use_global_stats,
**kwargs):
super(ResUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
self.body = ResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
bn_use_global_stats=bn_use_global_stats)
if self.resize_identity:
self.identity_conv = pre_conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
return x
class CRUUnit(HybridBlock):
"""
CRU-Net collective residual unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
group_width: int
Group width parameter.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
conv1_params : ParameterDict, default None
Weights for the convolution layer #1.
conv2_params : ParameterDict, default None
Weights for the convolution layer #2.
"""
def __init__(self,
in_channels,
out_channels,
strides,
group_width,
bn_use_global_stats,
conv1_params=None,
conv2_params=None,
**kwargs):
super(CRUUnit, self).__init__(**kwargs)
assert (strides == 1) or ((conv1_params is None) and (conv2_params is None))
self.resize_input = (in_channels != out_channels)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
if self.resize_input:
self.input_conv = pre_conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
self.body = CRUBottleneck(
in_channels=out_channels,
out_channels=out_channels,
strides=strides,
group_width=group_width,
bn_use_global_stats=bn_use_global_stats,
conv1_params=conv1_params,
conv2_params=conv2_params)
if self.resize_identity:
self.identity_conv = cru_conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
conv_params=self.input_conv.conv.params)
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
if self.resize_input:
x = self.input_conv(x)
x = self.body(x)
x = x + identity
return x
class CRUNet(HybridBlock):
"""
CRU-Net model from 'Sharing Residual Units Through Collective Tensor Factorization To Improve Deep Neural Networks,'
https://www.ijcai.org/proceedings/2018/88.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
group_widths: list of int
List of group width parameters.
refresh_steps: list of int
List of refresh step parameters.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
cardinality,
bottleneck_width,
group_widths,
refresh_steps,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(CRUNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
group_width = group_widths[i]
refresh_step = refresh_steps[i]
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
if group_width != 0:
if ((refresh_step == 0) and (j == 0)) or ((refresh_step != 0) and (j % refresh_step == 0)):
conv1_params = None
conv2_params = None
unit = CRUUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
group_width=group_width,
bn_use_global_stats=bn_use_global_stats,
conv1_params=conv1_params,
conv2_params=conv2_params)
if conv1_params is None:
conv1_params = unit.body.conv1.conv.params
conv2_params = unit.body.conv2.params
stage.add(unit)
else:
stage.add(ResUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(PreResActivation(
in_channels=in_channels,
bn_use_global_stats=bn_use_global_stats))
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_crunet(blocks,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create CRU-Net model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
cardinality = 32
bottleneck_width = 4
if blocks == 56:
layers = [3, 4, 6, 3]
group_widths = [0, 0, 640, 0]
refresh_steps = [0, 0, 0, 0]
elif blocks == 116:
layers = [3, 6, 18, 3]
group_widths = [0, 352, 704, 0]
refresh_steps = [0, 0, 6, 0]
else:
raise ValueError("Unsupported CRU-Net with number of blocks: {}".format(blocks))
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = CRUNet(
channels=channels,
init_block_channels=init_block_channels,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
group_widths=group_widths,
refresh_steps=refresh_steps,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def crunet56(**kwargs):
"""
CRU-Net-56 model from 'Sharing Residual Units Through Collective Tensor Factorization To Improve Deep Neural
Networks,' https://www.ijcai.org/proceedings/2018/88.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_crunet(blocks=56, model_name="crunet56", **kwargs)
def crunet116(**kwargs):
"""
CRU-Net-116 model from 'Sharing Residual Units Through Collective Tensor Factorization To Improve Deep Neural
Networks,' https://www.ijcai.org/proceedings/2018/88.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_crunet(blocks=116, model_name="crunet116", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
crunet56,
crunet116,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != crunet56 or weight_count == 25609384)
assert (model != crunet116 or weight_count == 43656136)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 21,164 | 32.436019 | 120 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/fbnet.py | """
FBNet for ImageNet-1K, implemented in Gluon.
Original paper: 'FBNet: Hardware-Aware Efficient ConvNet Design via Differentiable Neural Architecture Search,'
https://arxiv.org/abs/1812.03443.
"""
__all__ = ['FBNet', 'fbnet_cb']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv5x5_block
class FBNetUnit(HybridBlock):
"""
FBNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the second convolution layer.
bn_epsilon : float
Small float added to variance in Batch norm.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
use_kernel3 : bool
Whether to use 3x3 (instead of 5x5) kernel.
exp_factor : int
Expansion factor for each unit.
activation : str, default 'relu'
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_epsilon,
bn_use_global_stats,
use_kernel3,
exp_factor,
activation="relu",
**kwargs):
super(FBNetUnit, self).__init__(**kwargs)
assert (exp_factor >= 1)
self.residual = (in_channels == out_channels) and (strides == 1)
self.use_exp_conv = True
mid_channels = exp_factor * in_channels
with self.name_scope():
if self.use_exp_conv:
self.exp_conv = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
activation=activation)
if use_kernel3:
self.conv1 = dwconv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
strides=strides,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
activation=activation)
else:
self.conv1 = dwconv5x5_block(
in_channels=mid_channels,
out_channels=mid_channels,
strides=strides,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
activation=activation)
self.conv2 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
activation=None)
def hybrid_forward(self, F, x):
if self.residual:
identity = x
if self.use_exp_conv:
x = self.exp_conv(x)
x = self.conv1(x)
x = self.conv2(x)
if self.residual:
x = x + identity
return x
class FBNetInitBlock(HybridBlock):
"""
FBNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_epsilon : float
Small float added to variance in Batch norm.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_epsilon,
bn_use_global_stats,
**kwargs):
super(FBNetInitBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
strides=2,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = FBNetUnit(
in_channels=out_channels,
out_channels=out_channels,
strides=1,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
use_kernel3=True,
exp_factor=1)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class FBNet(HybridBlock):
"""
FBNet model from 'FBNet: Hardware-Aware Efficient ConvNet Design via Differentiable Neural Architecture Search,'
https://arxiv.org/abs/1812.03443.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final block of the feature extractor.
kernels3 : list of list of int/bool
Using 3x3 (instead of 5x5) kernel for each unit.
exp_factors : list of list of int
Expansion factor for each unit.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
kernels3,
exp_factors,
bn_epsilon=1e-5,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(FBNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(FBNetInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) else 1
use_kernel3 = kernels3[i][j] == 1
exp_factor = exp_factors[i][j]
stage.add(FBNetUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
use_kernel3=use_kernel3,
exp_factor=exp_factor))
in_channels = out_channels
self.features.add(stage)
self.features.add(conv1x1_block(
in_channels=in_channels,
out_channels=final_block_channels,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
in_channels = final_block_channels
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_fbnet(version,
bn_epsilon=1e-5,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create FBNet model with specific parameters.
Parameters:
----------
version : str
Version of MobileNetV3 ('a', 'b' or 'c').
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if version == "c":
init_block_channels = 16
final_block_channels = 1984
channels = [[24, 24, 24], [32, 32, 32, 32], [64, 64, 64, 64, 112, 112, 112, 112], [184, 184, 184, 184, 352]]
kernels3 = [[1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1]]
exp_factors = [[6, 1, 1], [6, 3, 6, 6], [6, 3, 6, 6, 6, 6, 6, 3], [6, 6, 6, 6, 6]]
else:
raise ValueError("Unsupported FBNet version {}".format(version))
net = FBNet(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
kernels3=kernels3,
exp_factors=exp_factors,
bn_epsilon=bn_epsilon,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def fbnet_cb(**kwargs):
"""
FBNet-Cb model (bn_epsilon=1e-3) from 'FBNet: Hardware-Aware Efficient ConvNet Design via Differentiable Neural
Architecture Search,' https://arxiv.org/abs/1812.03443.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_fbnet(version="c", bn_epsilon=1e-3, model_name="fbnet_cb", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
fbnet_cb,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != fbnet_cb or weight_count == 5572200)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 11,752 | 33.567647 | 116 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/visemenet.py | """
VisemeNet for speech-driven facial animation, implemented in Gluon.
Original paper: 'VisemeNet: Audio-Driven Animator-Centric Speech Animation,' https://arxiv.org/abs/1805.09488.
"""
__all__ = ['VisemeNet', 'visemenet20']
import os
from mxnet import cpu
from mxnet.gluon import nn, rnn, HybridBlock
from .common import DenseBlock
class VisemeDenseBranch(HybridBlock):
"""
VisemeNet dense branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of int
Number of middle/output channels.
"""
def __init__(self,
in_channels,
out_channels_list,
**kwargs):
super(VisemeDenseBranch, self).__init__(**kwargs)
with self.name_scope():
self.branch = nn.HybridSequential(prefix="")
with self.branch.name_scope():
for out_channels in out_channels_list[:-1]:
self.branch.add(DenseBlock(
in_channels=in_channels,
out_channels=out_channels,
use_bias=True,
use_bn=True))
in_channels = out_channels
self.final_fc = nn.Dense(
units=out_channels_list[-1],
in_units=in_channels)
def hybrid_forward(self, F, x):
x = self.branch(x)
y = self.final_fc(x)
return y, x
class VisemeRnnBranch(HybridBlock):
"""
VisemeNet RNN branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of int
Number of middle/output channels.
rnn_num_layers : int
Number of RNN layers.
dropout_rate : float
Dropout rate.
"""
def __init__(self,
in_channels,
out_channels_list,
rnn_num_layers,
dropout_rate,
**kwargs):
super(VisemeRnnBranch, self).__init__(**kwargs)
with self.name_scope():
self.rnn = rnn.LSTM(
hidden_size=out_channels_list[0],
num_layers=rnn_num_layers,
dropout=dropout_rate,
input_size=in_channels)
self.fc_branch = VisemeDenseBranch(
in_channels=out_channels_list[0],
out_channels_list=out_channels_list[1:])
def hybrid_forward(self, F, x):
x = self.rnn(x)
x = x[:, -1, :]
y, _ = self.fc_branch(x)
return y
class VisemeNet(HybridBlock):
"""
VisemeNet model from 'VisemeNet: Audio-Driven Animator-Centric Speech Animation,' https://arxiv.org/abs/1805.09488.
Parameters:
----------
audio_features : int, default 195
Number of audio features (characters/sounds).
audio_window_size : int, default 8
Size of audio window (for time related audio features).
stage2_window_size : int, default 64
Size of window for stage #2.
num_face_ids : int, default 76
Number of face IDs.
num_landmarks : int, default 76
Number of landmarks.
num_phonemes : int, default 21
Number of phonemes.
num_visemes : int, default 20
Number of visemes.
dropout_rate : float, default 0.5
Dropout rate for RNNs.
"""
def __init__(self,
audio_features=195,
audio_window_size=8,
stage2_window_size=64,
num_face_ids=76,
num_landmarks=76,
num_phonemes=21,
num_visemes=20,
dropout_rate=0.5,
**kwargs):
super(VisemeNet, self).__init__(**kwargs)
stage1_rnn_hidden_size = 256
stage1_fc_mid_channels = 256
stage2_rnn_in_features = (audio_features + num_landmarks + stage1_fc_mid_channels) * \
stage2_window_size // audio_window_size
self.audio_window_size = audio_window_size
self.stage2_window_size = stage2_window_size
with self.name_scope():
self.stage1_rnn = rnn.LSTM(
hidden_size=stage1_rnn_hidden_size,
num_layers=3,
dropout=dropout_rate,
input_size=audio_features)
self.lm_branch = VisemeDenseBranch(
in_channels=(stage1_rnn_hidden_size + num_face_ids),
out_channels_list=[stage1_fc_mid_channels, num_landmarks])
self.ph_branch = VisemeDenseBranch(
in_channels=(stage1_rnn_hidden_size + num_face_ids),
out_channels_list=[stage1_fc_mid_channels, num_phonemes])
self.cls_branch = VisemeRnnBranch(
in_channels=stage2_rnn_in_features,
out_channels_list=[256, 200, num_visemes],
rnn_num_layers=1,
dropout_rate=dropout_rate)
self.reg_branch = VisemeRnnBranch(
in_channels=stage2_rnn_in_features,
out_channels_list=[256, 200, 100, num_visemes],
rnn_num_layers=3,
dropout_rate=dropout_rate)
self.jali_branch = VisemeRnnBranch(
in_channels=stage2_rnn_in_features,
out_channels_list=[128, 200, 2],
rnn_num_layers=3,
dropout_rate=dropout_rate)
def hybrid_forward(self, F, x, pid):
y = self.stage1_rnn(x)
y = y[:, -1, :]
y = F.concat(y, pid, dim=1)
lm, _ = self.lm_branch(y)
lm += pid
ph, ph1 = self.ph_branch(y)
z = F.concat(lm, ph1, dim=1)
z2 = F.concat(z, x[:, self.audio_window_size // 2, :], dim=1)
n_net2_input = z2.shape[1]
z2 = F.concat(
F.zeros((self.stage2_window_size // 2, n_net2_input)),
z2,
dim=0)
z = F.stack(
*[z2[i:i + self.stage2_window_size].reshape(
(self.audio_window_size, n_net2_input * self.stage2_window_size // self.audio_window_size))
for i in range(z2.shape[0] - self.stage2_window_size)],
axis=0)
cls = self.cls_branch(z)
reg = self.reg_branch(z)
jali = self.jali_branch(z)
return cls, reg, jali
def get_visemenet(model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create VisemeNet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
net = VisemeNet(
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def visemenet20(**kwargs):
"""
VisemeNet model for 20 visemes (without co-articulation rules) from 'VisemeNet: Audio-Driven Animator-Centric
Speech Animation,' https://arxiv.org/abs/1805.09488.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_visemenet(model_name="visemenet20", **kwargs)
def _calc_width(net):
import numpy as np
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
return weight_count
def _test():
import mxnet as mx
pretrained = False
models = [
visemenet20,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != visemenet20 or weight_count == 14574303)
batch = 34
audio_window_size = 8
audio_features = 195
num_face_ids = 76
num_visemes = 20
x = mx.nd.random.normal(shape=(batch, audio_window_size, audio_features), ctx=ctx)
pid = mx.nd.full(shape=(batch, num_face_ids), val=3, ctx=ctx)
y1, y2, y3 = net(x, pid)
assert (y1.shape[0] == y2.shape[0] == y3.shape[0])
assert (y1.shape[1] == y2.shape[1] == num_visemes)
assert (y3.shape[1] == 2)
if __name__ == "__main__":
_test()
| 9,324 | 31.155172 | 119 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/fractalnet_cifar.py | """
FractalNet for CIFAR, implemented in Gluon.
Original paper: 'FractalNet: Ultra-Deep Neural Networks without Residuals,' https://arxiv.org/abs/1605.07648.
"""
__all__ = ['CIFARFractalNet', 'fractalnet_cifar10', 'fractalnet_cifar100']
import os
import numpy as np
import mxnet as mx
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import ParametricSequential
class DropConvBlock(HybridBlock):
"""
Convolution block with Batch normalization, ReLU activation, and Dropout layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
use_bias : bool, default False
Whether the layer uses a bias vector.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
dropout_rate : float, default 0.0
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
use_bias=False,
bn_use_global_stats=False,
dropout_prob=0.0,
**kwargs):
super(DropConvBlock, self).__init__(**kwargs)
self.use_dropout = (dropout_prob != 0.0)
with self.name_scope():
self.conv = nn.Conv2D(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
use_bias=use_bias,
in_channels=in_channels)
self.bn = nn.BatchNorm(
in_channels=out_channels,
use_global_stats=bn_use_global_stats)
self.activ = nn.Activation("relu")
if self.use_dropout:
self.dropout = nn.Dropout(rate=dropout_prob)
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.bn(x)
x = self.activ(x)
if self.use_dropout:
x = self.dropout(x)
return x
def drop_conv3x3_block(in_channels,
out_channels,
strides=1,
padding=1,
use_bias=False,
bn_use_global_stats=False,
dropout_prob=0.0,
**kwargs):
"""
3x3 version of the convolution block with dropout.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
use_bias : bool, default False
Whether the layer uses a bias vector.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
dropout_rate : float, default 0.0
Parameter of Dropout layer. Faction of the input units to drop.
"""
return DropConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
strides=strides,
padding=padding,
use_bias=use_bias,
bn_use_global_stats=bn_use_global_stats,
dropout_prob=dropout_prob,
**kwargs)
class FractalBlock(HybridBlock):
"""
FractalNet block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
num_columns : int
Number of columns in each block.
loc_drop_prob : float
Local drop path probability.
dropout_prob : float
Probability of dropout.
"""
def __init__(self,
in_channels,
out_channels,
num_columns,
loc_drop_prob,
dropout_prob,
**kwargs):
super(FractalBlock, self).__init__(**kwargs)
assert (num_columns >= 1)
self.num_columns = num_columns
self.loc_drop_prob = loc_drop_prob
with self.name_scope():
self.blocks = nn.HybridSequential(prefix="")
depth = 2 ** (num_columns - 1)
for i in range(depth):
level_block_i = nn.HybridSequential(prefix='block{}_'.format(i + 1))
for j in range(self.num_columns):
column_step_j = 2 ** j
if (i + 1) % column_step_j == 0:
in_channels_ij = in_channels if (i + 1 == column_step_j) else out_channels
level_block_i.add(drop_conv3x3_block(
in_channels=in_channels_ij,
out_channels=out_channels,
dropout_prob=dropout_prob))
self.blocks.add(level_block_i)
@staticmethod
def calc_drop_mask(batch_size,
glob_num_columns,
curr_num_columns,
max_num_columns,
loc_drop_prob):
"""
Calculate drop path mask.
Parameters:
----------
batch_size : int
Size of batch.
glob_num_columns : int
Number of columns in global drop path mask.
curr_num_columns : int
Number of active columns in the current level of block.
max_num_columns : int
Number of columns for all network.
loc_drop_prob : float
Local drop path probability.
Returns:
-------
np.array
Resulted mask.
"""
glob_batch_size = glob_num_columns.shape[0]
glob_drop_mask = np.zeros((curr_num_columns, glob_batch_size), dtype=np.float32)
glob_drop_num_columns = glob_num_columns - (max_num_columns - curr_num_columns)
glob_drop_indices = np.where(glob_drop_num_columns >= 0)[0]
glob_drop_mask[glob_drop_num_columns[glob_drop_indices], glob_drop_indices] = 1.0
loc_batch_size = batch_size - glob_batch_size
loc_drop_mask = np.random.binomial(
n=1,
p=(1.0 - loc_drop_prob),
size=(curr_num_columns, loc_batch_size)).astype(np.float32)
alive_count = loc_drop_mask.sum(axis=0)
dead_indices = np.where(alive_count == 0.0)[0]
loc_drop_mask[np.random.randint(0, curr_num_columns, size=dead_indices.shape), dead_indices] = 1.0
drop_mask = np.concatenate((glob_drop_mask, loc_drop_mask), axis=1)
return drop_mask
@staticmethod
def join_outs(F,
raw_outs,
glob_num_columns,
num_columns,
loc_drop_prob,
training):
"""
Join outputs for current level of block.
Parameters:
----------
F : namespace
Symbol or NDArray namespace.
raw_outs : list of Tensor
Current outputs from active columns.
glob_num_columns : int
Number of columns in global drop path mask.
num_columns : int
Number of columns for all network.
loc_drop_prob : float
Local drop path probability.
training : bool
Whether training mode for network.
Returns:
-------
NDArray
Joined output.
"""
curr_num_columns = len(raw_outs)
out = F.stack(*raw_outs, axis=0)
assert (out.shape[0] == curr_num_columns)
if training:
batch_size = out.shape[1]
batch_mask = FractalBlock.calc_drop_mask(
batch_size=batch_size,
glob_num_columns=glob_num_columns,
curr_num_columns=curr_num_columns,
max_num_columns=num_columns,
loc_drop_prob=loc_drop_prob)
batch_mask = mx.nd.array(batch_mask, ctx=out.context)
assert (batch_mask.shape[0] == curr_num_columns)
assert (batch_mask.shape[1] == batch_size)
batch_mask = batch_mask.expand_dims(2).expand_dims(3).expand_dims(4)
masked_out = out * batch_mask
num_alive = batch_mask.sum(axis=0).asnumpy()
num_alive[num_alive == 0.0] = 1.0
num_alive = mx.nd.array(num_alive, ctx=out.context)
out = masked_out.sum(axis=0) / num_alive
else:
out = out.mean(axis=0)
return out
def hybrid_forward(self, F, x, glob_num_columns):
outs = [x] * self.num_columns
for level_block_i in self.blocks._children.values():
outs_i = []
for j, block_ij in enumerate(level_block_i._children.values()):
input_i = outs[j]
outs_i.append(block_ij(input_i))
joined_out = FractalBlock.join_outs(
F=F,
raw_outs=outs_i[::-1],
glob_num_columns=glob_num_columns,
num_columns=self.num_columns,
loc_drop_prob=self.loc_drop_prob,
training=mx.autograd.is_training())
len_level_block_i = len(level_block_i._children.values())
for j in range(len_level_block_i):
outs[j] = joined_out
return outs[0]
class FractalUnit(HybridBlock):
"""
FractalNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
num_columns : int
Number of columns in each block.
loc_drop_prob : float
Local drop path probability.
dropout_prob : float
Probability of dropout.
"""
def __init__(self,
in_channels,
out_channels,
num_columns,
loc_drop_prob,
dropout_prob,
**kwargs):
super(FractalUnit, self).__init__(**kwargs)
with self.name_scope():
self.block = FractalBlock(
in_channels=in_channels,
out_channels=out_channels,
num_columns=num_columns,
loc_drop_prob=loc_drop_prob,
dropout_prob=dropout_prob)
self.pool = nn.MaxPool2D(
pool_size=2,
strides=2)
def hybrid_forward(self, F, x, glob_num_columns):
x = self.block(x, glob_num_columns)
x = self.pool(x)
return x
class CIFARFractalNet(HybridBlock):
"""
FractalNet model for CIFAR from 'FractalNet: Ultra-Deep Neural Networks without Residuals,'
https://arxiv.org/abs/1605.07648.
Parameters:
----------
channels : list of int
Number of output channels for each unit.
num_columns : int
Number of columns in each block.
dropout_probs : list of float
Probability of dropout in each block.
loc_drop_prob : float
Local drop path probability.
glob_drop_ratio : float
Global drop part fraction.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
num_columns,
dropout_probs,
loc_drop_prob,
glob_drop_ratio,
in_channels=3,
in_size=(32, 32),
classes=10,
**kwargs):
super(CIFARFractalNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
self.glob_drop_ratio = glob_drop_ratio
self.num_columns = num_columns
with self.name_scope():
self.features = ParametricSequential(prefix="")
for i, out_channels in enumerate(channels):
dropout_prob = dropout_probs[i]
self.features.add(FractalUnit(
in_channels=in_channels,
out_channels=out_channels,
num_columns=num_columns,
loc_drop_prob=loc_drop_prob,
dropout_prob=dropout_prob))
in_channels = out_channels
self.output = nn.Dense(
units=classes,
in_units=in_channels)
def hybrid_forward(self, F, x):
glob_batch_size = int(x.shape[0] * self.glob_drop_ratio)
glob_num_columns = np.random.randint(0, self.num_columns, size=(glob_batch_size,))
x = self.features(x, glob_num_columns)
x = self.output(x)
return x
def get_fractalnet_cifar(num_classes,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create WRN model for CIFAR with specific parameters.
Parameters:
----------
num_classes : int
Number of classification classes.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
dropout_probs = (0.0, 0.1, 0.2, 0.3, 0.4)
channels = [64 * (2 ** (i if i != len(dropout_probs) - 1 else i - 1)) for i in range(len(dropout_probs))]
num_columns = 3
loc_drop_prob = 0.15
glob_drop_ratio = 0.5
net = CIFARFractalNet(
channels=channels,
num_columns=num_columns,
dropout_probs=dropout_probs,
loc_drop_prob=loc_drop_prob,
glob_drop_ratio=glob_drop_ratio,
classes=num_classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def fractalnet_cifar10(num_classes=10, **kwargs):
"""
FractalNet model for CIFAR-10 from 'FractalNet: Ultra-Deep Neural Networks without Residuals,'
https://arxiv.org/abs/1605.07648.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_fractalnet_cifar(num_classes=num_classes, model_name="fractalnet_cifar10", **kwargs)
def fractalnet_cifar100(num_classes=100, **kwargs):
"""
FractalNet model for CIFAR-100 from 'FractalNet: Ultra-Deep Neural Networks without Residuals,'
https://arxiv.org/abs/1605.07648.
Parameters:
----------
num_classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_fractalnet_cifar(num_classes=num_classes, model_name="fractalnet_cifar100", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
(fractalnet_cifar10, 10),
(fractalnet_cifar100, 100),
]
for model, classes in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != fractalnet_cifar10 or weight_count == 33724618)
assert (model != fractalnet_cifar100 or weight_count == 33770788)
x = mx.nd.zeros((14, 3, 32, 32), ctx=ctx)
y = net(x)
# with mx.autograd.record():
# y = net(x)
# y.backward()
assert (y.shape == (14, classes))
if __name__ == "__main__":
_test()
| 17,294 | 32.195777 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/mobilenetv3.py | """
MobileNetV3 for ImageNet-1K, implemented in Gluon.
Original paper: 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
"""
__all__ = ['MobileNetV3', 'mobilenetv3_small_w7d20', 'mobilenetv3_small_wd2', 'mobilenetv3_small_w3d4',
'mobilenetv3_small_w1', 'mobilenetv3_small_w5d4', 'mobilenetv3_large_w7d20', 'mobilenetv3_large_wd2',
'mobilenetv3_large_w3d4', 'mobilenetv3_large_w1', 'mobilenetv3_large_w5d4']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import round_channels, conv1x1, conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv5x5_block, SEBlock,\
HSwish
class MobileNetV3Unit(HybridBlock):
"""
MobileNetV3 unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
exp_channels : int
Number of middle (expanded) channels.
strides : int or tuple/list of 2 int
Strides of the second convolution layer.
use_kernel3 : bool
Whether to use 3x3 (instead of 5x5) kernel.
activation : str
Activation function or name of activation function.
use_se : bool
Whether to use SE-module.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
"""
def __init__(self,
in_channels,
out_channels,
exp_channels,
strides,
use_kernel3,
activation,
use_se,
bn_use_global_stats=False,
**kwargs):
super(MobileNetV3Unit, self).__init__(**kwargs)
assert (exp_channels >= out_channels)
self.residual = (in_channels == out_channels) and (strides == 1)
self.use_se = use_se
self.use_exp_conv = exp_channels != out_channels
mid_channels = exp_channels
with self.name_scope():
if self.use_exp_conv:
self.exp_conv = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats,
activation=activation)
if use_kernel3:
self.conv1 = dwconv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
activation=activation)
else:
self.conv1 = dwconv5x5_block(
in_channels=mid_channels,
out_channels=mid_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
activation=activation)
if self.use_se:
self.se = SEBlock(
channels=mid_channels,
reduction=4,
round_mid=True,
out_activation="hsigmoid")
self.conv2 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation=None)
def hybrid_forward(self, F, x):
if self.residual:
identity = x
if self.use_exp_conv:
x = self.exp_conv(x)
x = self.conv1(x)
if self.use_se:
x = self.se(x)
x = self.conv2(x)
if self.residual:
x = x + identity
return x
class MobileNetV3FinalBlock(HybridBlock):
"""
MobileNetV3 final block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
use_se : bool
Whether to use SE-module.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
"""
def __init__(self,
in_channels,
out_channels,
use_se,
bn_use_global_stats=False,
**kwargs):
super(MobileNetV3FinalBlock, self).__init__(**kwargs)
self.use_se = use_se
with self.name_scope():
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation="hswish")
if self.use_se:
self.se = SEBlock(
channels=out_channels,
reduction=4,
round_mid=True,
out_activation="hsigmoid")
def hybrid_forward(self, F, x):
x = self.conv(x)
if self.use_se:
x = self.se(x)
return x
class MobileNetV3Classifier(HybridBlock):
"""
MobileNetV3 classifier.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of middle channels.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels,
dropout_rate,
**kwargs):
super(MobileNetV3Classifier, self).__init__(**kwargs)
self.use_dropout = (dropout_rate != 0.0)
with self.name_scope():
self.conv1 = conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.activ = HSwish()
if self.use_dropout:
self.dropout = nn.Dropout(rate=dropout_rate)
self.conv2 = conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
use_bias=True)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.activ(x)
if self.use_dropout:
x = self.dropout(x)
x = self.conv2(x)
return x
class MobileNetV3(HybridBlock):
"""
MobileNetV3 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
exp_channels : list of list of int
Number of middle (expanded) channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final block of the feature extractor.
classifier_mid_channels : int
Number of middle channels for classifier.
kernels3 : list of list of int/bool
Using 3x3 (instead of 5x5) kernel for each unit.
use_relu : list of list of int/bool
Using ReLU activation flag for each unit.
use_se : list of list of int/bool
Using SE-block flag for each unit.
first_stride : bool
Whether to use stride for the first stage.
final_use_se : bool
Whether to use SE-module in the final block.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
exp_channels,
init_block_channels,
final_block_channels,
classifier_mid_channels,
kernels3,
use_relu,
use_se,
first_stride,
final_use_se,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(MobileNetV3, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
strides=2,
bn_use_global_stats=bn_use_global_stats,
activation="hswish"))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
exp_channels_ij = exp_channels[i][j]
strides = 2 if (j == 0) and ((i != 0) or first_stride) else 1
use_kernel3 = kernels3[i][j] == 1
activation = "relu" if use_relu[i][j] == 1 else "hswish"
use_se_flag = use_se[i][j] == 1
stage.add(MobileNetV3Unit(
in_channels=in_channels,
out_channels=out_channels,
exp_channels=exp_channels_ij,
use_kernel3=use_kernel3,
strides=strides,
activation=activation,
use_se=use_se_flag,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(MobileNetV3FinalBlock(
in_channels=in_channels,
out_channels=final_block_channels,
use_se=final_use_se,
bn_use_global_stats=bn_use_global_stats))
in_channels = final_block_channels
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(MobileNetV3Classifier(
in_channels=in_channels,
out_channels=classes,
mid_channels=classifier_mid_channels,
dropout_rate=0.2))
self.output.add(nn.Flatten())
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_mobilenetv3(version,
width_scale,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create MobileNetV3 model with specific parameters.
Parameters:
----------
version : str
Version of MobileNetV3 ('small' or 'large').
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if version == "small":
init_block_channels = 16
channels = [[16], [24, 24], [40, 40, 40, 48, 48], [96, 96, 96]]
exp_channels = [[16], [72, 88], [96, 240, 240, 120, 144], [288, 576, 576]]
kernels3 = [[1], [1, 1], [0, 0, 0, 0, 0], [0, 0, 0]]
use_relu = [[1], [1, 1], [0, 0, 0, 0, 0], [0, 0, 0]]
use_se = [[1], [0, 0], [1, 1, 1, 1, 1], [1, 1, 1]]
first_stride = True
final_block_channels = 576
elif version == "large":
init_block_channels = 16
channels = [[16], [24, 24], [40, 40, 40], [80, 80, 80, 80, 112, 112], [160, 160, 160]]
exp_channels = [[16], [64, 72], [72, 120, 120], [240, 200, 184, 184, 480, 672], [672, 960, 960]]
kernels3 = [[1], [1, 1], [0, 0, 0], [1, 1, 1, 1, 1, 1], [0, 0, 0]]
use_relu = [[1], [1, 1], [1, 1, 1], [0, 0, 0, 0, 0, 0], [0, 0, 0]]
use_se = [[0], [0, 0], [1, 1, 1], [0, 0, 0, 0, 1, 1], [1, 1, 1]]
first_stride = False
final_block_channels = 960
else:
raise ValueError("Unsupported MobileNetV3 version {}".format(version))
final_use_se = False
classifier_mid_channels = 1280
if width_scale != 1.0:
channels = [[round_channels(cij * width_scale) for cij in ci] for ci in channels]
exp_channels = [[round_channels(cij * width_scale) for cij in ci] for ci in exp_channels]
init_block_channels = round_channels(init_block_channels * width_scale)
if width_scale > 1.0:
final_block_channels = round_channels(final_block_channels * width_scale)
net = MobileNetV3(
channels=channels,
exp_channels=exp_channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
classifier_mid_channels=classifier_mid_channels,
kernels3=kernels3,
use_relu=use_relu,
use_se=use_se,
first_stride=first_stride,
final_use_se=final_use_se,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def mobilenetv3_small_w7d20(**kwargs):
"""
MobileNetV3 Small 224/0.35 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="small", width_scale=0.35, model_name="mobilenetv3_small_w7d20", **kwargs)
def mobilenetv3_small_wd2(**kwargs):
"""
MobileNetV3 Small 224/0.5 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="small", width_scale=0.5, model_name="mobilenetv3_small_wd2", **kwargs)
def mobilenetv3_small_w3d4(**kwargs):
"""
MobileNetV3 Small 224/0.75 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="small", width_scale=0.75, model_name="mobilenetv3_small_w3d4", **kwargs)
def mobilenetv3_small_w1(**kwargs):
"""
MobileNetV3 Small 224/1.0 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="small", width_scale=1.0, model_name="mobilenetv3_small_w1", **kwargs)
def mobilenetv3_small_w5d4(**kwargs):
"""
MobileNetV3 Small 224/1.25 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="small", width_scale=1.25, model_name="mobilenetv3_small_w5d4", **kwargs)
def mobilenetv3_large_w7d20(**kwargs):
"""
MobileNetV3 Small 224/0.35 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="large", width_scale=0.35, model_name="mobilenetv3_small_w7d20", **kwargs)
def mobilenetv3_large_wd2(**kwargs):
"""
MobileNetV3 Large 224/0.5 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="large", width_scale=0.5, model_name="mobilenetv3_large_wd2", **kwargs)
def mobilenetv3_large_w3d4(**kwargs):
"""
MobileNetV3 Large 224/0.75 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="large", width_scale=0.75, model_name="mobilenetv3_large_w3d4", **kwargs)
def mobilenetv3_large_w1(**kwargs):
"""
MobileNetV3 Large 224/1.0 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="large", width_scale=1.0, model_name="mobilenetv3_large_w1", **kwargs)
def mobilenetv3_large_w5d4(**kwargs):
"""
MobileNetV3 Large 224/1.25 model from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenetv3(version="large", width_scale=1.25, model_name="mobilenetv3_large_w5d4", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
mobilenetv3_small_w7d20,
mobilenetv3_small_wd2,
mobilenetv3_small_w3d4,
mobilenetv3_small_w1,
mobilenetv3_small_w5d4,
mobilenetv3_large_w7d20,
mobilenetv3_large_wd2,
mobilenetv3_large_w3d4,
mobilenetv3_large_w1,
mobilenetv3_large_w5d4,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != mobilenetv3_small_w7d20 or weight_count == 2159600)
assert (model != mobilenetv3_small_wd2 or weight_count == 2288976)
assert (model != mobilenetv3_small_w3d4 or weight_count == 2581312)
assert (model != mobilenetv3_small_w1 or weight_count == 2945288)
assert (model != mobilenetv3_small_w5d4 or weight_count == 3643632)
assert (model != mobilenetv3_large_w7d20 or weight_count == 2943080)
assert (model != mobilenetv3_large_wd2 or weight_count == 3334896)
assert (model != mobilenetv3_large_w3d4 or weight_count == 4263496)
assert (model != mobilenetv3_large_w1 or weight_count == 5481752)
assert (model != mobilenetv3_large_w5d4 or weight_count == 7459144)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 21,706 | 35.238731 | 118 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/diaresnet.py | """
DIA-ResNet for ImageNet-1K, implemented in Gluon.
Original paper: 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
"""
__all__ = ['DIAResNet', 'diaresnet10', 'diaresnet12', 'diaresnet14', 'diaresnetbc14b', 'diaresnet16', 'diaresnet18',
'diaresnet26', 'diaresnetbc26b', 'diaresnet34', 'diaresnetbc38b', 'diaresnet50', 'diaresnet50b',
'diaresnet101', 'diaresnet101b', 'diaresnet152', 'diaresnet152b', 'diaresnet200', 'diaresnet200b',
'DIAAttention', 'DIAResUnit']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block, DualPathSequential
from .resnet import ResBlock, ResBottleneck, ResInitBlock
class FirstLSTMAmp(HybridBlock):
"""
First LSTM amplifier branch.
Parameters:
----------
in_units : int
Number of input channels.
units : int
Number of output channels.
"""
def __init__(self,
in_units,
units,
**kwargs):
super(FirstLSTMAmp, self).__init__(**kwargs)
mid_units = in_units // 4
with self.name_scope():
self.fc1 = nn.Dense(
units=mid_units,
in_units=in_units)
self.activ = nn.Activation("relu")
self.fc2 = nn.Dense(
units=units,
in_units=mid_units)
def hybrid_forward(self, F, x):
x = self.fc1(x)
x = self.activ(x)
x = self.fc2(x)
return x
class DIALSTMCell(HybridBlock):
"""
DIA-LSTM cell.
Parameters:
----------
in_x_features : int
Number of x input channels.
in_h_features : int
Number of h input channels.
num_layers : int
Number of amplifiers.
dropout_rate : float, default 0.1
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_x_features,
in_h_features,
num_layers,
dropout_rate=0.1,
**kwargs):
super(DIALSTMCell, self).__init__(**kwargs)
self.num_layers = num_layers
out_features = 4 * in_h_features
with self.name_scope():
self.x_amps = nn.HybridSequential(prefix="")
self.h_amps = nn.HybridSequential(prefix="")
for i in range(num_layers):
amp_class = FirstLSTMAmp if i == 0 else nn.Dense
self.x_amps.add(amp_class(
in_units=in_x_features,
units=out_features))
self.h_amps.add(amp_class(
in_units=in_h_features,
units=out_features))
in_x_features = in_h_features
self.dropout = nn.Dropout(rate=dropout_rate)
def hybrid_forward(self, F, x, h, c):
hy = []
cy = []
for i in range(self.num_layers):
hx_i = h[i]
cx_i = c[i]
gates = self.x_amps[i](x) + self.h_amps[i](hx_i)
i_gate, f_gate, c_gate, o_gate = F.split(gates, axis=1, num_outputs=4)
i_gate = F.sigmoid(i_gate)
f_gate = F.sigmoid(f_gate)
c_gate = F.tanh(c_gate)
o_gate = F.sigmoid(o_gate)
cy_i = (f_gate * cx_i) + (i_gate * c_gate)
hy_i = o_gate * F.sigmoid(cy_i)
cy.append(cy_i)
hy.append(hy_i)
x = self.dropout(hy_i)
return hy, cy
class DIAAttention(HybridBlock):
"""
DIA-Net attention module.
Parameters:
----------
in_x_features : int
Number of x input channels.
in_h_features : int
Number of h input channels.
num_layers : int, default 1
Number of amplifiers.
"""
def __init__(self,
in_x_features,
in_h_features,
num_layers=1,
**kwargs):
super(DIAAttention, self).__init__(**kwargs)
self.num_layers = num_layers
with self.name_scope():
self.lstm = DIALSTMCell(
in_x_features=in_x_features,
in_h_features=in_h_features,
num_layers=num_layers)
def hybrid_forward(self, F, x, hc=None):
w = F.contrib.AdaptiveAvgPooling2D(x, output_size=1)
w = w.flatten()
if hc is None:
h = [F.zeros_like(w)] * self.num_layers
c = [F.zeros_like(w)] * self.num_layers
else:
h, c = hc
h, c = self.lstm(w, h, c)
w = h[self.num_layers - 1].expand_dims(axis=-1).expand_dims(axis=-1)
x = F.broadcast_mul(x, w)
return x, (h, c)
class DIAResUnit(HybridBlock):
"""
DIA-ResNet unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for the second convolution layer in bottleneck.
dilation : int or tuple/list of 2 int, default 1
Dilation value for the second convolution layer in bottleneck.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bottleneck : bool, default True
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default False
Whether to use stride in the first or the second convolution layer of the block.
attention : nn.Module, default None
Attention module.
"""
def __init__(self,
in_channels,
out_channels,
strides,
padding=1,
dilation=1,
bn_use_global_stats=False,
bottleneck=True,
conv1_stride=False,
attention=None,
**kwargs):
super(DIAResUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
if bottleneck:
self.body = ResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
padding=padding,
dilation=dilation,
bn_use_global_stats=bn_use_global_stats,
conv1_stride=conv1_stride)
else:
self.body = ResBlock(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
activation=None)
self.activ = nn.Activation("relu")
self.attention = attention
def hybrid_forward(self, F, x, hc=None):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x, hc = self.attention(x, hc)
x = x + identity
x = self.activ(x)
return x, hc
class DIAResNet(HybridBlock):
"""
DIA-ResNet model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(DIAResNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = DualPathSequential(
return_two=False,
prefix="stage{}_".format(i + 1))
attention = DIAAttention(
in_x_features=channels_per_stage[0],
in_h_features=channels_per_stage[0])
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
stage.add(DIAResUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
attention=attention))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_diaresnet(blocks,
bottleneck=None,
conv1_stride=True,
width_scale=1.0,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create DIA-ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
bottleneck : bool, default None
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
width_scale : float, default 1.0
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if bottleneck is None:
bottleneck = (blocks >= 50)
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14 and not bottleneck:
layers = [2, 2, 1, 1]
elif (blocks == 14) and bottleneck:
layers = [1, 1, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif (blocks == 26) and not bottleneck:
layers = [3, 3, 3, 3]
elif (blocks == 26) and bottleneck:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif (blocks == 38) and bottleneck:
layers = [3, 3, 3, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
else:
raise ValueError("Unsupported DIA-ResNet with number of blocks: {}".format(blocks))
if bottleneck:
assert (sum(layers) * 3 + 2 == blocks)
else:
assert (sum(layers) * 2 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [64, 128, 256, 512]
if bottleneck:
bottleneck_factor = 4
channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) if (i != len(channels) - 1) or (j != len(ci) - 1) else cij
for j, cij in enumerate(ci)] for i, ci in enumerate(channels)]
init_block_channels = int(init_block_channels * width_scale)
net = DIAResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def diaresnet10(**kwargs):
"""
DIA-ResNet-10 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=10, model_name="diaresnet10", **kwargs)
def diaresnet12(**kwargs):
"""
DIA-ResNet-12 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=12, model_name="diaresnet12", **kwargs)
def diaresnet14(**kwargs):
"""
DIA-ResNet-14 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=14, model_name="diaresnet14", **kwargs)
def diaresnetbc14b(**kwargs):
"""
DIA-ResNet-BC-14b model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model (bottleneck compressed).
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=14, bottleneck=True, conv1_stride=False, model_name="diaresnetbc14b", **kwargs)
def diaresnet16(**kwargs):
"""
DIA-ResNet-16 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=16, model_name="diaresnet16", **kwargs)
def diaresnet18(**kwargs):
"""
DIA-ResNet-18 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=18, model_name="diaresnet18", **kwargs)
def diaresnet26(**kwargs):
"""
DIA-ResNet-26 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=26, bottleneck=False, model_name="diaresnet26", **kwargs)
def diaresnetbc26b(**kwargs):
"""
DIA-ResNet-BC-26b model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model (bottleneck compressed).
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=26, bottleneck=True, conv1_stride=False, model_name="diaresnetbc26b", **kwargs)
def diaresnet34(**kwargs):
"""
DIA-ResNet-34 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=34, model_name="diaresnet34", **kwargs)
def diaresnetbc38b(**kwargs):
"""
DIA-ResNet-BC-38b model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model (bottleneck compressed).
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=38, bottleneck=True, conv1_stride=False, model_name="diaresnetbc38b", **kwargs)
def diaresnet50(**kwargs):
"""
DIA-ResNet-50 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=50, model_name="diaresnet50", **kwargs)
def diaresnet50b(**kwargs):
"""
DIA-ResNet-50 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=50, conv1_stride=False, model_name="diaresnet50b", **kwargs)
def diaresnet101(**kwargs):
"""
DIA-ResNet-101 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=101, model_name="diaresnet101", **kwargs)
def diaresnet101b(**kwargs):
"""
DIA-ResNet-101 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=101, conv1_stride=False, model_name="diaresnet101b", **kwargs)
def diaresnet152(**kwargs):
"""
DIA-ResNet-152 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=152, model_name="diaresnet152", **kwargs)
def diaresnet152b(**kwargs):
"""
DIA-ResNet-152 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=152, conv1_stride=False, model_name="diaresnet152b", **kwargs)
def diaresnet200(**kwargs):
"""
DIA-ResNet-200 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=200, model_name="diaresnet200", **kwargs)
def diaresnet200b(**kwargs):
"""
DIA-ResNet-200 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diaresnet(blocks=200, conv1_stride=False, model_name="diaresnet200b", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
diaresnet10,
diaresnet12,
diaresnet14,
diaresnetbc14b,
diaresnet16,
diaresnet18,
diaresnet26,
diaresnetbc26b,
diaresnet34,
diaresnetbc38b,
diaresnet50,
diaresnet50b,
diaresnet101,
diaresnet101b,
diaresnet152,
diaresnet152b,
diaresnet200,
diaresnet200b,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != diaresnet10 or weight_count == 6297352)
assert (model != diaresnet12 or weight_count == 6371336)
assert (model != diaresnet14 or weight_count == 6666760)
assert (model != diaresnetbc14b or weight_count == 24023976)
assert (model != diaresnet16 or weight_count == 7847432)
assert (model != diaresnet18 or weight_count == 12568072)
assert (model != diaresnet26 or weight_count == 18838792)
assert (model != diaresnetbc26b or weight_count == 29954216)
assert (model != diaresnet34 or weight_count == 22676232)
assert (model != diaresnetbc38b or weight_count == 35884456)
assert (model != diaresnet50 or weight_count == 39516072)
assert (model != diaresnet50b or weight_count == 39516072)
assert (model != diaresnet101 or weight_count == 58508200)
assert (model != diaresnet101b or weight_count == 58508200)
assert (model != diaresnet152 or weight_count == 74151848)
assert (model != diaresnet152b or weight_count == 74151848)
assert (model != diaresnet200 or weight_count == 78632872)
assert (model != diaresnet200b or weight_count == 78632872)
x = mx.nd.zeros((14, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (14, 1000))
if __name__ == "__main__":
_test()
| 27,098 | 33.565051 | 116 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/lffd.py | """
LFFD for face detection, implemented in Gluon.
Original paper: 'LFFD: A Light and Fast Face Detector for Edge Devices,' https://arxiv.org/abs/1904.10633.
"""
__all__ = ['LFFD', 'lffd20x5s320v2_widerface', 'lffd25x8s560v1_widerface']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from mxnet.gluon.contrib.nn import HybridConcurrent
from .common import conv3x3, conv1x1_block, conv3x3_block, MultiOutputSequential, ParallelConcurent
from .resnet import ResUnit
from .preresnet import PreResUnit
class LffdDetectionBranch(HybridBlock):
"""
LFFD specific detection branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
use_bias : bool
Whether the layer uses a bias vector.
use_bn : bool
Whether to use BatchNorm layer.
"""
def __init__(self,
in_channels,
out_channels,
use_bias,
use_bn,
**kwargs):
super(LffdDetectionBranch, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=in_channels,
use_bias=use_bias,
use_bn=use_bn)
self.conv2 = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
use_bias=use_bias,
use_bn=use_bn,
activation=None)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class LffdDetectionBlock(HybridBlock):
"""
LFFD specific detection block.
Parameters:
----------
in_channels : int
Number of input channels.
mid_channels : int
Number of middle channels.
use_bias : bool
Whether the layer uses a bias vector.
use_bn : bool
Whether to use BatchNorm layer.
"""
def __init__(self,
in_channels,
mid_channels,
use_bias,
use_bn,
**kwargs):
super(LffdDetectionBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
use_bias=use_bias,
use_bn=use_bn)
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(LffdDetectionBranch(
in_channels=mid_channels,
out_channels=4,
use_bias=use_bias,
use_bn=use_bn))
self.branches.add(LffdDetectionBranch(
in_channels=mid_channels,
out_channels=2,
use_bias=use_bias,
use_bn=use_bn))
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.branches(x)
return x
class LFFD(HybridBlock):
"""
LFFD model from 'LFFD: A Light and Fast Face Detector for Edge Devices,' https://arxiv.org/abs/1904.10633.
Parameters:
----------
enc_channels : list of int
Number of output channels for each encoder stage.
dec_channels : int
Number of output channels for each decoder stage.
init_block_channels : int
Number of output channels for the initial encoder unit.
layers : list of int
Number of units in each encoder stage.
int_bends : list of int
Number of internal bends for each encoder stage.
use_preresnet : bool
Whether to use PreResnet backbone instead of ResNet.
receptive_field_center_starts : list of int
The start location of the first receptive field of each scale.
receptive_field_strides : list of int
Receptive field stride for each scale.
bbox_factors : list of float
A half of bbox upper bound for each scale.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (640, 640)
Spatial size of the expected input image.
"""
def __init__(self,
enc_channels,
dec_channels,
init_block_channels,
layers,
int_bends,
use_preresnet,
receptive_field_center_starts,
receptive_field_strides,
bbox_factors,
in_channels=3,
in_size=(480, 640),
**kwargs):
super(LFFD, self).__init__(**kwargs)
self.in_size = in_size
self.receptive_field_center_starts = receptive_field_center_starts
self.receptive_field_strides = receptive_field_strides
self.bbox_factors = bbox_factors
unit_class = PreResUnit if use_preresnet else ResUnit
use_bias = True
use_bn = False
with self.name_scope():
self.encoder = MultiOutputSequential(return_last=False)
self.encoder.add(conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
strides=2,
padding=0,
use_bias=use_bias,
use_bn=use_bn))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(enc_channels):
layers_per_stage = layers[i]
int_bends_per_stage = int_bends[i]
stage = MultiOutputSequential(prefix="stage{}_".format(i + 1), multi_output=False, dual_output=True)
stage.add(conv3x3(
in_channels=in_channels,
out_channels=channels_per_stage,
strides=2,
padding=0,
use_bias=use_bias))
for j in range(layers_per_stage):
unit = unit_class(
in_channels=channels_per_stage,
out_channels=channels_per_stage,
strides=1,
use_bias=use_bias,
use_bn=use_bn,
bottleneck=False)
if layers_per_stage - j <= int_bends_per_stage:
unit.do_output = True
stage.add(unit)
final_activ = nn.Activation("relu")
final_activ.do_output = True
stage.add(final_activ)
stage.do_output2 = True
in_channels = channels_per_stage
self.encoder.add(stage)
self.decoder = ParallelConcurent()
k = 0
for i, channels_per_stage in enumerate(enc_channels):
layers_per_stage = layers[i]
int_bends_per_stage = int_bends[i]
for j in range(layers_per_stage):
if layers_per_stage - j <= int_bends_per_stage:
self.decoder.add(LffdDetectionBlock(
in_channels=channels_per_stage,
mid_channels=dec_channels,
use_bias=use_bias,
use_bn=use_bn))
k += 1
self.decoder.add(LffdDetectionBlock(
in_channels=channels_per_stage,
mid_channels=dec_channels,
use_bias=use_bias,
use_bn=use_bn))
k += 1
def hybrid_forward(self, F, x):
x = self.encoder(x)
x = self.decoder(x)
return x
def get_lffd(blocks,
use_preresnet,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create LFFD model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
use_preresnet : bool
Whether to use PreResnet backbone instead of ResNet.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if blocks == 20:
layers = [3, 1, 1, 1, 1]
enc_channels = [64, 64, 64, 128, 128]
int_bends = [0, 0, 0, 0, 0]
receptive_field_center_starts = [3, 7, 15, 31, 63]
receptive_field_strides = [4, 8, 16, 32, 64]
bbox_factors = [10.0, 20.0, 40.0, 80.0, 160.0]
elif blocks == 25:
layers = [4, 2, 1, 3]
enc_channels = [64, 64, 128, 128]
int_bends = [1, 1, 0, 2]
receptive_field_center_starts = [3, 3, 7, 7, 15, 31, 31, 31]
receptive_field_strides = [4, 4, 8, 8, 16, 32, 32, 32]
bbox_factors = [7.5, 10.0, 20.0, 35.0, 55.0, 125.0, 200.0, 280.0]
else:
raise ValueError("Unsupported LFFD with number of blocks: {}".format(blocks))
dec_channels = 128
init_block_channels = 64
net = LFFD(
enc_channels=enc_channels,
dec_channels=dec_channels,
init_block_channels=init_block_channels,
layers=layers,
int_bends=int_bends,
use_preresnet=use_preresnet,
receptive_field_center_starts=receptive_field_center_starts,
receptive_field_strides=receptive_field_strides,
bbox_factors=bbox_factors,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def lffd20x5s320v2_widerface(**kwargs):
"""
LFFD-320-20L-5S-V2 model for WIDER FACE from 'LFFD: A Light and Fast Face Detector for Edge Devices,'
https://arxiv.org/abs/1904.10633.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_lffd(blocks=20, use_preresnet=True, model_name="lffd20x5s320v2_widerface", **kwargs)
def lffd25x8s560v1_widerface(**kwargs):
"""
LFFD-560-25L-8S-V1 model for WIDER FACE from 'LFFD: A Light and Fast Face Detector for Edge Devices,'
https://arxiv.org/abs/1904.10633.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_lffd(blocks=25, use_preresnet=False, model_name="lffd25x8s560v1_widerface", **kwargs)
def _test():
import numpy as np
import mxnet as mx
in_size = (480, 640)
pretrained = False
models = [
(lffd20x5s320v2_widerface, 5),
(lffd25x8s560v1_widerface, 8),
]
for model, num_outs in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != lffd20x5s320v2_widerface or weight_count == 1520606)
assert (model != lffd25x8s560v1_widerface or weight_count == 2290608)
batch = 14
x = mx.nd.random.normal(shape=(batch, 3, in_size[0], in_size[1]), ctx=ctx)
y = net(x)
assert (len(y) == num_outs)
if __name__ == "__main__":
_test()
| 12,410 | 33.28453 | 116 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/sepreresnet.py | """
SE-PreResNet for ImageNet-1K, implemented in Gluon.
Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
"""
__all__ = ['SEPreResNet', 'sepreresnet10', 'sepreresnet12', 'sepreresnet14', 'sepreresnet16', 'sepreresnet18',
'sepreresnet26', 'sepreresnetbc26b', 'sepreresnet34', 'sepreresnetbc38b', 'sepreresnet50', 'sepreresnet50b',
'sepreresnet101', 'sepreresnet101b', 'sepreresnet152', 'sepreresnet152b', 'sepreresnet200',
'sepreresnet200b', 'SEPreResUnit']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1, SEBlock
from .preresnet import PreResBlock, PreResBottleneck, PreResInitBlock, PreResActivation
class SEPreResUnit(HybridBlock):
"""
SE-PreResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer of the block.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats,
bottleneck,
conv1_stride,
**kwargs):
super(SEPreResUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
if bottleneck:
self.body = PreResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
conv1_stride=conv1_stride)
else:
self.body = PreResBlock(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats)
self.se = SEBlock(channels=out_channels)
if self.resize_identity:
self.identity_conv = conv1x1(
in_channels=in_channels,
out_channels=out_channels,
strides=strides)
def hybrid_forward(self, F, x):
identity = x
x, x_pre_activ = self.body(x)
x = self.se(x)
if self.resize_identity:
identity = self.identity_conv(x_pre_activ)
x = x + identity
return x
class SEPreResNet(HybridBlock):
"""
SE-PreResNet model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(SEPreResNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(PreResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
stage.add(SEPreResUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bottleneck=bottleneck,
conv1_stride=conv1_stride))
in_channels = out_channels
self.features.add(stage)
self.features.add(PreResActivation(
in_channels=in_channels,
bn_use_global_stats=bn_use_global_stats))
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_sepreresnet(blocks,
bottleneck=None,
conv1_stride=True,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create SE-PreResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
bottleneck : bool, default None
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if bottleneck is None:
bottleneck = (blocks >= 50)
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14 and not bottleneck:
layers = [2, 2, 1, 1]
elif (blocks == 14) and bottleneck:
layers = [1, 1, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif (blocks == 26) and not bottleneck:
layers = [3, 3, 3, 3]
elif (blocks == 26) and bottleneck:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif (blocks == 38) and bottleneck:
layers = [3, 3, 3, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
elif blocks == 269:
layers = [3, 30, 48, 8]
else:
raise ValueError("Unsupported SE-PreResNet with number of blocks: {}".format(blocks))
if bottleneck:
assert (sum(layers) * 3 + 2 == blocks)
else:
assert (sum(layers) * 2 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [64, 128, 256, 512]
if bottleneck:
bottleneck_factor = 4
channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = SEPreResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def sepreresnet10(**kwargs):
"""
SE-PreResNet-10 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=10, model_name="sepreresnet10", **kwargs)
def sepreresnet12(**kwargs):
"""
SE-PreResNet-12 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=12, model_name="sepreresnet12", **kwargs)
def sepreresnet14(**kwargs):
"""
SE-PreResNet-14 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=14, model_name="sepreresnet14", **kwargs)
def sepreresnet16(**kwargs):
"""
SE-PreResNet-16 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=16, model_name="sepreresnet16", **kwargs)
def sepreresnet18(**kwargs):
"""
SE-PreResNet-18 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=18, model_name="sepreresnet18", **kwargs)
def sepreresnet26(**kwargs):
"""
SE-PreResNet-26 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=26, bottleneck=False, model_name="sepreresnet26", **kwargs)
def sepreresnetbc26b(**kwargs):
"""
SE-PreResNet-BC-26b model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=26, bottleneck=True, conv1_stride=False, model_name="sepreresnetbc26b", **kwargs)
def sepreresnet34(**kwargs):
"""
SE-PreResNet-34 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=34, model_name="sepreresnet34", **kwargs)
def sepreresnetbc38b(**kwargs):
"""
SE-PreResNet-BC-38b model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=38, bottleneck=True, conv1_stride=False, model_name="sepreresnetbc38b", **kwargs)
def sepreresnet50(**kwargs):
"""
SE-PreResNet-50 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=50, model_name="sepreresnet50", **kwargs)
def sepreresnet50b(**kwargs):
"""
SE-PreResNet-50 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=50, conv1_stride=False, model_name="sepreresnet50b", **kwargs)
def sepreresnet101(**kwargs):
"""
SE-PreResNet-101 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=101, model_name="sepreresnet101", **kwargs)
def sepreresnet101b(**kwargs):
"""
SE-PreResNet-101 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=101, conv1_stride=False, model_name="sepreresnet101b", **kwargs)
def sepreresnet152(**kwargs):
"""
SE-PreResNet-152 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=152, model_name="sepreresnet152", **kwargs)
def sepreresnet152b(**kwargs):
"""
SE-PreResNet-152 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=152, conv1_stride=False, model_name="sepreresnet152b", **kwargs)
def sepreresnet200(**kwargs):
"""
SE-PreResNet-200 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an
experimental model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=200, model_name="sepreresnet200", **kwargs)
def sepreresnet200b(**kwargs):
"""
SE-PreResNet-200 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sepreresnet(blocks=200, conv1_stride=False, model_name="sepreresnet200b", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
sepreresnet10,
sepreresnet12,
sepreresnet14,
sepreresnet16,
sepreresnet18,
sepreresnet26,
sepreresnetbc26b,
sepreresnet34,
sepreresnetbc38b,
sepreresnet50,
sepreresnet50b,
sepreresnet101,
sepreresnet101b,
sepreresnet152,
sepreresnet152b,
sepreresnet200,
sepreresnet200b,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != sepreresnet10 or weight_count == 5461668)
assert (model != sepreresnet12 or weight_count == 5536232)
assert (model != sepreresnet14 or weight_count == 5833840)
assert (model != sepreresnet16 or weight_count == 7022976)
assert (model != sepreresnet18 or weight_count == 11776928)
assert (model != sepreresnet26 or weight_count == 18092188)
assert (model != sepreresnetbc26b or weight_count == 17388424)
assert (model != sepreresnet34 or weight_count == 21957204)
assert (model != sepreresnetbc38b or weight_count == 24019064)
assert (model != sepreresnet50 or weight_count == 28080472)
assert (model != sepreresnet50b or weight_count == 28080472)
assert (model != sepreresnet101 or weight_count == 49319320)
assert (model != sepreresnet101b or weight_count == 49319320)
assert (model != sepreresnet152 or weight_count == 66814296)
assert (model != sepreresnet152b or weight_count == 66814296)
assert (model != sepreresnet200 or weight_count == 71828312)
assert (model != sepreresnet200b or weight_count == 71828312)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 21,007 | 34.071786 | 119 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/resnext.py | """
ResNeXt for ImageNet-1K, implemented in Gluon.
Original paper: 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431.
"""
__all__ = ['ResNeXt', 'resnext14_16x4d', 'resnext14_32x2d', 'resnext14_32x4d', 'resnext26_16x4d', 'resnext26_32x2d',
'resnext26_32x4d', 'resnext38_32x4d', 'resnext50_32x4d', 'resnext101_32x4d', 'resnext101_64x4d',
'ResNeXtBottleneck', 'ResNeXtUnit']
import os
import math
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block, conv3x3_block
from .resnet import ResInitBlock
class ResNeXtBottleneck(HybridBlock):
"""
ResNeXt bottleneck block for residual path in ResNeXt unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bottleneck_factor : int, default 4
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
strides,
cardinality,
bottleneck_width,
bn_use_global_stats,
bottleneck_factor=4,
**kwargs):
super(ResNeXtBottleneck, self).__init__(**kwargs)
mid_channels = out_channels // bottleneck_factor
D = int(math.floor(mid_channels * (bottleneck_width / 64.0)))
group_width = cardinality * D
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=group_width,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = conv3x3_block(
in_channels=group_width,
out_channels=group_width,
strides=strides,
groups=cardinality,
bn_use_global_stats=bn_use_global_stats)
self.conv3 = conv1x1_block(
in_channels=group_width,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation=None)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class ResNeXtUnit(HybridBlock):
"""
ResNeXt unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
cardinality,
bottleneck_width,
bn_use_global_stats,
**kwargs):
super(ResNeXtUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
self.body = ResNeXtBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
bn_use_global_stats=bn_use_global_stats)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
activation=None)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class ResNeXt(HybridBlock):
"""
ResNeXt model from 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
cardinality,
bottleneck_width,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(ResNeXt, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
stage.add(ResNeXtUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_resnext(blocks,
cardinality,
bottleneck_width,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create ResNeXt model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if blocks == 14:
layers = [1, 1, 1, 1]
elif blocks == 26:
layers = [2, 2, 2, 2]
elif blocks == 38:
layers = [3, 3, 3, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
else:
raise ValueError("Unsupported ResNeXt with number of blocks: {}".format(blocks))
assert (sum(layers) * 3 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = ResNeXt(
channels=channels,
init_block_channels=init_block_channels,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def resnext14_16x4d(**kwargs):
"""
ResNeXt-14 (16x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=14, cardinality=16, bottleneck_width=4, model_name="resnext14_16x4d", **kwargs)
def resnext14_32x2d(**kwargs):
"""
ResNeXt-14 (32x2d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=14, cardinality=32, bottleneck_width=2, model_name="resnext14_32x2d", **kwargs)
def resnext14_32x4d(**kwargs):
"""
ResNeXt-14 (32x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=14, cardinality=32, bottleneck_width=4, model_name="resnext14_32x4d", **kwargs)
def resnext26_16x4d(**kwargs):
"""
ResNeXt-26 (16x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=26, cardinality=16, bottleneck_width=4, model_name="resnext26_16x4d", **kwargs)
def resnext26_32x2d(**kwargs):
"""
ResNeXt-26 (32x2d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=26, cardinality=32, bottleneck_width=2, model_name="resnext26_32x2d", **kwargs)
def resnext26_32x4d(**kwargs):
"""
ResNeXt-26 (32x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=26, cardinality=32, bottleneck_width=4, model_name="resnext26_32x4d", **kwargs)
def resnext38_32x4d(**kwargs):
"""
ResNeXt-38 (32x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=38, cardinality=32, bottleneck_width=4, model_name="resnext38_32x4d", **kwargs)
def resnext50_32x4d(**kwargs):
"""
ResNeXt-50 (32x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=50, cardinality=32, bottleneck_width=4, model_name="resnext50_32x4d", **kwargs)
def resnext101_32x4d(**kwargs):
"""
ResNeXt-101 (32x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=101, cardinality=32, bottleneck_width=4, model_name="resnext101_32x4d", **kwargs)
def resnext101_64x4d(**kwargs):
"""
ResNeXt-101 (64x4d) model from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext(blocks=101, cardinality=64, bottleneck_width=4, model_name="resnext101_64x4d", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
resnext14_16x4d,
resnext14_32x2d,
resnext14_32x4d,
resnext26_16x4d,
resnext26_32x2d,
resnext26_32x4d,
resnext38_32x4d,
resnext50_32x4d,
resnext101_32x4d,
resnext101_64x4d,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != resnext14_16x4d or weight_count == 7127336)
assert (model != resnext14_32x2d or weight_count == 7029416)
assert (model != resnext14_32x4d or weight_count == 9411880)
assert (model != resnext26_16x4d or weight_count == 10119976)
assert (model != resnext26_32x2d or weight_count == 9924136)
assert (model != resnext26_32x4d or weight_count == 15389480)
assert (model != resnext38_32x4d or weight_count == 21367080)
assert (model != resnext50_32x4d or weight_count == 25028904)
assert (model != resnext101_32x4d or weight_count == 44177704)
assert (model != resnext101_64x4d or weight_count == 83455272)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 17,156 | 33.245509 | 119 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/jasper.py | """
Jasper/DR for ASR, implemented in Gluon.
Original paper: 'Jasper: An End-to-End Convolutional Neural Acoustic Model,' https://arxiv.org/abs/1904.03288.
"""
__all__ = ['Jasper', 'jasper5x3', 'jasper10x4', 'jasper10x5', 'get_jasper', 'MaskConv1d', 'NemoAudioReader',
'NemoMelSpecExtractor', 'CtcDecoder']
import os
import numpy as np
import mxnet as mx
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import BatchNormExtra, DualPathSequential, DualPathParallelConcurent
def outmask_fill(F, x, x_len, value=0.0):
"""
Masked fill a tensor.
Parameters:
----------
F : object
MXNet tensor processing package.
x : tensor
Input tensor.
x_len : tensor
Tensor with lengths.
value : float, default 0.0
Filled value.
Returns:
-------
tensor
Resulted tensor.
"""
x = F.SequenceMask(
data=x.swapaxes(1, 2),
sequence_length=x_len,
use_sequence_length=True,
value=value,
axis=1).swapaxes(1, 2)
return x
def masked_normalize2(F, x, x_len):
"""
Normalize a tensor with mask (scheme #2).
Parameters:
----------
F : object
MXNet tensor processing package.
x : tensor
Input tensor.
x_len : tensor
Tensor with lengths.
Returns:
-------
tensor
Resulted tensor.
"""
x = outmask_fill(F, x, x_len)
x_len_float = x_len.astype("float32").expand_dims(axis=1)
x_mean = x.sum(axis=2) / x_len_float
x2_mean = x.square().sum(axis=2) / x_len_float
x_std = (x2_mean - x_mean.square()).sqrt()
x = (x - x_mean.expand_dims(axis=2)) / x_std.expand_dims(axis=2)
return x
class NemoAudioReader(object):
"""
Audio Reader from NVIDIA NEMO toolkit.
Parameters:
----------
desired_audio_sample_rate : int, default 16000
Desired audio sample rate.
trunc_value : int or None, default None
Value to truncate.
"""
def __init__(self, desired_audio_sample_rate=16000):
super(NemoAudioReader, self).__init__()
self.desired_audio_sample_rate = desired_audio_sample_rate
def read_from_file(self, audio_file_path):
"""
Read audio from file.
Parameters:
----------
audio_file_path : str
Path to audio file.
Returns:
-------
np.array
Audio data.
"""
from soundfile import SoundFile
with SoundFile(audio_file_path, "r") as data:
sample_rate = data.samplerate
audio_data = data.read(dtype="float32")
audio_data = audio_data.transpose()
if sample_rate != self.desired_audio_sample_rate:
from librosa.core import resample as lr_resample
audio_data = lr_resample(y=audio_data, orig_sr=sample_rate, target_sr=self.desired_audio_sample_rate)
if audio_data.ndim >= 2:
audio_data = np.mean(audio_data, axis=1)
return audio_data
def read_from_files(self, audio_file_paths):
"""
Read audios from files.
Parameters:
----------
audio_file_paths : list of str
Paths to audio files.
Returns:
-------
list of np.array
Audio data.
"""
assert (type(audio_file_paths) in (list, tuple))
audio_data_list = []
for audio_file_path in audio_file_paths:
audio_data = self.read_from_file(audio_file_path)
audio_data_list.append(audio_data)
return audio_data_list
class NemoMelSpecExtractor(HybridBlock):
"""
Mel-Spectrogram Extractor from NVIDIA NEMO toolkit.
Parameters:
----------
sample_rate : int, default 16000
Sample rate of the input audio data.
window_size_sec : float, default 0.02
Size of window for FFT in seconds.
window_stride_sec : float, default 0.01
Stride of window for FFT in seconds.
n_fft : int, default 512
Length of FT window.
n_filters : int, default 64
Number of Mel spectrogram freq bins.
preemph : float, default 0.97
Amount of pre emphasis to add to audio.
dither : float, default 1.0e-05
Amount of white-noise dithering.
"""
def __init__(self,
sample_rate=16000,
window_size_sec=0.02,
window_stride_sec=0.01,
n_fft=512,
n_filters=64,
preemph=0.97,
dither=1.0e-5,
**kwargs):
super(NemoMelSpecExtractor, self).__init__(**kwargs)
self.log_zero_guard_value = 2 ** -24
win_length = int(window_size_sec * sample_rate)
self.hop_length = int(window_stride_sec * sample_rate)
self.n_filters = n_filters
from scipy import signal as scipy_signal
from librosa import stft as librosa_stft
window_arr = scipy_signal.hann(win_length, sym=True)
self.stft = lambda x: librosa_stft(
x,
n_fft=n_fft,
hop_length=self.hop_length,
win_length=win_length,
window=window_arr,
center=True)
self.dither = dither
self.preemph = preemph
self.pad_align = 16
from librosa.filters import mel as librosa_mel
fb_arr = librosa_mel(
sr=sample_rate,
n_fft=n_fft,
n_mels=n_filters,
fmin=0.0,
fmax=(sample_rate / 2.0))
fb_arr = np.expand_dims(fb_arr, axis=0)
with self.name_scope():
self.window = self.params.get(
"window",
grad_req="null",
shape=window_arr.shape,
init=mx.init.Constant(window_arr),
allow_deferred_init=False,
differentiable=False)
self.fb = self.params.get(
"fb",
grad_req="null",
shape=fb_arr.shape,
init=mx.init.Constant(fb_arr),
allow_deferred_init=False,
differentiable=False)
def hybrid_forward(self, F, x, x_len, window=None, fb=None):
x_len = ((x_len.astype("float32") / self.hop_length).ceil()).astype("int64")
if self.dither > 0:
x += self.dither * F.random.normal_like(x)
x = F.concat(x[:, :1], x[:, 1:] - self.preemph * x[:, :-1], dim=1)
x = self.calc_real_stft(F, x)
x = F.power(x, 2)
x = F.batch_dot(fb.repeat(repeats=x.shape[0], axis=0), x)
x = F.log(x + self.log_zero_guard_value)
x = masked_normalize2(F, x, x_len)
x = outmask_fill(F, x, x_len)
x_len_max = x.shape[-1]
pad_rem = x_len_max % self.pad_align
if pad_rem != 0:
x = x.expand_dims(1).pad(mode="constant", pad_width=(0, 0, 0, 0, 0, 0, 0, self.pad_align - pad_rem),
constant_value=0).squeeze(1)
return x, x_len
def calc_real_stft(self, F, x):
x_np = x.asnumpy()
ys = []
for xi_np in x_np:
ys.append(self.stft(xi_np))
x_np = np.array(ys)
x_np = np.abs(x_np)
x = F.array(x_np, ctx=x.context)
return x
def calc_flops(self, x):
assert (x.shape[0] == 1)
num_flops = x[0].size
num_macs = 0
return num_flops, num_macs
class CtcDecoder(object):
"""
CTC decoder (to decode a sequence of labels to words).
Parameters:
----------
vocabulary : list of str
Vocabulary of the dataset.
"""
def __init__(self,
vocabulary):
super().__init__()
self.blank_id = len(vocabulary)
self.labels_map = dict([(i, vocabulary[i]) for i in range(len(vocabulary))])
def __call__(self,
predictions):
"""
Decode a sequence of labels to words.
Parameters:
----------
predictions : np.array of int or list of list of int
Tensor with predicted labels.
Returns:
-------
list of str
Words.
"""
hypotheses = []
for prediction in predictions:
decoded_prediction = []
previous = self.blank_id
for p in prediction:
if (p != previous or previous == self.blank_id) and p != self.blank_id:
decoded_prediction.append(p)
previous = p
hypothesis = "".join([self.labels_map[c] for c in decoded_prediction])
hypotheses.append(hypothesis)
return hypotheses
def conv1d1(in_channels,
out_channels,
strides=1,
groups=1,
use_bias=False,
**kwargs):
"""
1-dim kernel version of the 1D convolution layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int, default 1
Strides of the convolution.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
"""
return nn.Conv1D(
channels=out_channels,
kernel_size=1,
strides=strides,
groups=groups,
use_bias=use_bias,
in_channels=in_channels,
**kwargs)
class MaskConv1d(nn.Conv1D):
"""
Masked 1D convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 1 int
Convolution window size.
strides : int or tuple/list of 1 int
Strides of the convolution.
padding : int or tuple/list of 1 int, default 0
Padding value for convolution layer.
dilation : int or tuple/list of 1 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_mask : bool, default True
Whether to use mask.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding=0,
dilation=1,
groups=1,
use_bias=False,
use_mask=True,
**kwargs):
super(MaskConv1d, self).__init__(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
in_channels=in_channels,
**kwargs)
self.use_mask = use_mask
if self.use_mask:
self.kernel_size = kernel_size[0] if isinstance(kernel_size, (list, tuple)) else kernel_size
self.strides = strides[0] if isinstance(strides, (list, tuple)) else strides
self.padding = padding[0] if isinstance(padding, (list, tuple)) else padding
self.dilation = dilation[0] if isinstance(dilation, (list, tuple)) else dilation
def hybrid_forward(self, F, x, x_len, weight, bias=None):
if self.use_mask:
x = outmask_fill(F, x, x_len)
x_len = ((x_len + 2 * self.padding - self.dilation * (self.kernel_size - 1) - 1) / self.strides + 1).floor()
x = super(MaskConv1d, self).hybrid_forward(F, x, weight=weight, bias=bias)
return x, x_len
def mask_conv1d1(in_channels,
out_channels,
strides=1,
groups=1,
use_bias=False,
**kwargs):
"""
Masked 1-dim kernel version of the 1D convolution layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int, default 1
Strides of the convolution.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
"""
return MaskConv1d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
strides=strides,
groups=groups,
use_bias=use_bias,
**kwargs)
class MaskConvBlock1d(HybridBlock):
"""
Masked 1D convolution block with batch normalization, activation, and dropout.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int
Convolution window size.
strides : int
Strides of the convolution.
padding : int
Padding value for convolution layer.
dilation : int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
dropout_rate : float, default 0.0
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
dilation=1,
groups=1,
use_bias=False,
use_bn=True,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
activation=(lambda: nn.Activation("relu")),
dropout_rate=0.0,
**kwargs):
super(MaskConvBlock1d, self).__init__(**kwargs)
self.activate = (activation is not None)
self.use_bn = use_bn
self.use_dropout = (dropout_rate != 0.0)
with self.name_scope():
self.conv = MaskConv1d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias)
if self.use_bn:
self.bn = BatchNormExtra(
in_channels=out_channels,
epsilon=bn_epsilon,
use_global_stats=bn_use_global_stats,
cudnn_off=bn_cudnn_off)
if self.activate:
self.activ = activation()
if self.use_dropout:
self.dropout = nn.Dropout(rate=dropout_rate)
def hybrid_forward(self, F, x, x_len):
x, x_len = self.conv(x, x_len)
if self.use_bn:
x = self.bn(x)
if self.activate:
x = self.activ(x)
if self.use_dropout:
x = self.dropout(x)
return x, x_len
def mask_conv1d1_block(in_channels,
out_channels,
strides=1,
padding=0,
**kwargs):
"""
1-dim kernel version of the masked 1D convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int, default 1
Strides of the convolution.
padding : int, default 0
Padding value for convolution layer.
"""
return MaskConvBlock1d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
strides=strides,
padding=padding,
**kwargs)
class ChannelShuffle1d(HybridBlock):
"""
1D version of the channel shuffle layer.
Parameters:
----------
channels : int
Number of channels.
groups : int
Number of groups.
"""
def __init__(self,
channels,
groups,
**kwargs):
super(ChannelShuffle1d, self).__init__(**kwargs)
assert (channels % groups == 0)
self.groups = groups
def hybrid_forward(self, F, x):
return x.reshape((0, -4, self.groups, -1, -2)).swapaxes(1, 2).reshape((0, -3, -2))
def __repr__(self):
s = "{name}(groups={groups})"
return s.format(
name=self.__class__.__name__,
groups=self.groups)
class DwsConvBlock1d(HybridBlock):
"""
Depthwise version of the 1D standard convolution block with batch normalization, activation, dropout, and channel
shuffle.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int
Convolution window size.
strides : int
Strides of the convolution.
padding : int
Padding value for convolution layer.
dilation : int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
dropout_rate : float, default 0.0
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
dilation=1,
groups=1,
use_bias=False,
use_bn=True,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
activation=(lambda: nn.Activation("relu")),
dropout_rate=0.0,
**kwargs):
super(DwsConvBlock1d, self).__init__(**kwargs)
self.activate = (activation is not None)
self.use_bn = use_bn
self.use_dropout = (dropout_rate != 0.0)
self.use_channel_shuffle = (groups > 1)
with self.name_scope():
self.dw_conv = MaskConv1d(
in_channels=in_channels,
out_channels=in_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
dilation=dilation,
groups=in_channels,
use_bias=use_bias)
self.pw_conv = mask_conv1d1(
in_channels=in_channels,
out_channels=out_channels,
groups=groups,
use_bias=use_bias)
if self.use_channel_shuffle:
self.shuffle = ChannelShuffle1d(
channels=out_channels,
groups=groups)
if self.use_bn:
self.bn = BatchNormExtra(
in_channels=out_channels,
epsilon=bn_epsilon,
use_global_stats=bn_use_global_stats,
cudnn_off=bn_cudnn_off)
if self.activate:
self.activ = activation()
if self.use_dropout:
self.dropout = nn.Dropout(rate=dropout_rate)
def hybrid_forward(self, F, x, x_len):
x, x_len = self.dw_conv(x, x_len)
x, x_len = self.pw_conv(x, x_len)
if self.use_channel_shuffle:
x = self.shuffle(x)
if self.use_bn:
x = self.bn(x)
if self.activate:
x = self.activ(x)
if self.use_dropout:
x = self.dropout(x)
return x, x_len
class JasperUnit(HybridBlock):
"""
Jasper unit with residual connection.
Parameters:
----------
in_channels : int or list of int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int
Convolution window size.
bn_epsilon : float
Small float added to variance in Batch norm.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
repeat : int
Count of body convolution blocks.
use_dw : bool
Whether to use depthwise block.
use_dr : bool
Whether to use dense residual scheme.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
bn_epsilon,
dropout_rate,
repeat,
use_dw,
use_dr,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(JasperUnit, self).__init__(**kwargs)
self.use_dropout = (dropout_rate != 0.0)
self.use_dr = use_dr
block_class = DwsConvBlock1d if use_dw else MaskConvBlock1d
with self.name_scope():
if self.use_dr:
self.identity_block = DualPathParallelConcurent()
for i, dense_in_channels_i in enumerate(in_channels):
self.identity_block.add(mask_conv1d1_block(
in_channels=dense_in_channels_i,
out_channels=out_channels,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
dropout_rate=0.0,
activation=None))
in_channels = in_channels[-1]
else:
self.identity_block = mask_conv1d1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
dropout_rate=0.0,
activation=None)
self.body = DualPathSequential()
for i in range(repeat):
activation = (lambda: nn.Activation("relu")) if i < repeat - 1 else None
dropout_rate_i = dropout_rate if i < repeat - 1 else 0.0
self.body.add(block_class(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
strides=1,
padding=(kernel_size // 2),
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
dropout_rate=dropout_rate_i,
activation=activation))
in_channels = out_channels
self.activ = nn.Activation("relu")
if self.use_dropout:
self.dropout = nn.Dropout(rate=dropout_rate)
def hybrid_forward(self, F, x, x_len):
if self.use_dr:
x_len, y, y_len = x_len if type(x_len) is tuple else (x_len, None, None)
y = [x] if y is None else y + [x]
y_len = [x_len] if y_len is None else y_len + [x_len]
identity, _ = self.identity_block(y, y_len)
identity = F.stack(*identity, axis=1)
identity = identity.sum(axis=1)
else:
identity, _ = self.identity_block(x, x_len)
x, x_len = self.body(x, x_len)
x = x + identity
x = self.activ(x)
if self.use_dropout:
x = self.dropout(x)
if self.use_dr:
return x, (x_len, y, y_len)
else:
return x, x_len
class JasperFinalBlock(HybridBlock):
"""
Jasper specific final block.
Parameters:
----------
in_channels : int
Number of input channels.
channels : list of int
Number of output channels for each block.
kernel_sizes : list of int
Kernel sizes for each block.
bn_epsilon : float
Small float added to variance in Batch norm.
dropout_rates : list of int
Dropout rates for each block.
use_dw : bool
Whether to use depthwise block.
use_dr : bool
Whether to use dense residual scheme.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
channels,
kernel_sizes,
bn_epsilon,
dropout_rates,
use_dw,
use_dr,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(JasperFinalBlock, self).__init__(**kwargs)
self.use_dr = use_dr
conv1_class = DwsConvBlock1d if use_dw else MaskConvBlock1d
with self.name_scope():
self.conv1 = conv1_class(
in_channels=in_channels,
out_channels=channels[-2],
kernel_size=kernel_sizes[-2],
strides=1,
padding=(2 * kernel_sizes[-2] // 2 - 1),
dilation=2,
bn_epsilon=bn_epsilon,
dropout_rate=dropout_rates[-2],
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.conv2 = MaskConvBlock1d(
in_channels=channels[-2],
out_channels=channels[-1],
kernel_size=kernel_sizes[-1],
strides=1,
padding=(kernel_sizes[-1] // 2),
bn_epsilon=bn_epsilon,
dropout_rate=dropout_rates[-1],
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
def hybrid_forward(self, F, x, x_len):
if self.use_dr:
x_len = x_len[0]
x, x_len = self.conv1(x, x_len)
x, x_len = self.conv2(x, x_len)
return x, x_len
class Jasper(HybridBlock):
"""
Jasper/DR/QuartzNet model from 'Jasper: An End-to-End Convolutional Neural Acoustic Model,'
https://arxiv.org/abs/1904.03288.
Parameters:
----------
channels : list of int
Number of output channels for each unit and initial/final block.
kernel_sizes : list of int
Kernel sizes for each unit and initial/final block.
bn_epsilon : float
Small float added to variance in Batch norm.
dropout_rates : list of int
Dropout rates for each unit and initial/final block.
repeat : int
Count of body convolution blocks.
use_dw : bool
Whether to use depthwise block.
use_dr : bool
Whether to use dense residual scheme.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
from_audio : bool, default True
Whether to treat input as audio instead of Mel-specs.
dither : float, default 0.0
Amount of white-noise dithering.
return_text : bool, default False
Whether to return text instead of logits.
vocabulary : list of str or None, default None
Vocabulary of the dataset.
in_channels : int, default 64
Number of input channels (audio features).
classes : int, default 29
Number of classification classes (number of graphemes).
"""
def __init__(self,
channels,
kernel_sizes,
bn_epsilon,
dropout_rates,
repeat,
use_dw,
use_dr,
bn_use_global_stats=False,
bn_cudnn_off=False,
from_audio=True,
dither=0.0,
return_text=False,
vocabulary=None,
in_channels=64,
classes=29,
**kwargs):
super(Jasper, self).__init__(**kwargs)
self.in_size = in_channels
self.classes = classes
self.vocabulary = vocabulary
self.from_audio = from_audio
self.return_text = return_text
with self.name_scope():
if self.from_audio:
self.preprocessor = NemoMelSpecExtractor(dither=dither)
self.features = DualPathSequential()
init_block_class = DwsConvBlock1d if use_dw else MaskConvBlock1d
self.features.add(init_block_class(
in_channels=in_channels,
out_channels=channels[0],
kernel_size=kernel_sizes[0],
strides=2,
padding=(kernel_sizes[0] // 2),
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
dropout_rate=dropout_rates[0]))
in_channels = channels[0]
in_channels_list = []
for i, (out_channels, kernel_size, dropout_rate) in\
enumerate(zip(channels[1:-2], kernel_sizes[1:-2], dropout_rates[1:-2])):
in_channels_list += [in_channels]
self.features.add(JasperUnit(
in_channels=(in_channels_list if use_dr else in_channels),
out_channels=out_channels,
kernel_size=kernel_size,
bn_epsilon=bn_epsilon,
dropout_rate=dropout_rate,
repeat=repeat,
use_dw=use_dw,
use_dr=use_dr,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
in_channels = out_channels
self.features.add(JasperFinalBlock(
in_channels=in_channels,
channels=channels,
kernel_sizes=kernel_sizes,
bn_epsilon=bn_epsilon,
dropout_rates=dropout_rates,
use_dw=use_dw,
use_dr=use_dr,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
in_channels = channels[-1]
self.output = conv1d1(
in_channels=in_channels,
out_channels=classes,
use_bias=True)
if self.return_text:
self.ctc_decoder = CtcDecoder(vocabulary=vocabulary)
def hybrid_forward(self, F, x, x_len=None):
if x_len is None:
assert (type(x) in (list, tuple))
x, x_len = x
if self.from_audio:
x, x_len = self.preprocessor(x, x_len)
x, x_len = self.features(x, x_len)
x = self.output(x)
if self.return_text:
greedy_predictions = x.swapaxes(1, 2).log_softmax(dim=-1).argmax(dim=-1, keepdim=False).asnumpy()
return self.ctc_decoder(greedy_predictions)
else:
return x, x_len
def get_jasper(version,
use_dw=False,
use_dr=False,
bn_epsilon=1e-3,
vocabulary=None,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create Jasper/DR/QuartzNet model with specific parameters.
Parameters:
----------
version : tuple of str
Model type and configuration.
use_dw : bool, default False
Whether to use depthwise block.
use_dr : bool, default False
Whether to use dense residual scheme.
bn_epsilon : float, default 1e-3
Small float added to variance in Batch norm.
vocabulary : list of str or None, default None
Vocabulary of the dataset.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
import numpy as np
blocks, repeat = tuple(map(int, version[1].split("x")))
main_stage_repeat = blocks // 5
model_type = version[0]
if model_type == "jasper":
channels_per_stage = [256, 256, 384, 512, 640, 768, 896, 1024]
kernel_sizes_per_stage = [11, 11, 13, 17, 21, 25, 29, 1]
dropout_rates_per_stage = [0.2, 0.2, 0.2, 0.2, 0.3, 0.3, 0.4, 0.4]
elif model_type == "quartznet":
channels_per_stage = [256, 256, 256, 512, 512, 512, 512, 1024]
kernel_sizes_per_stage = [33, 33, 39, 51, 63, 75, 87, 1]
dropout_rates_per_stage = [0.0] * 8
else:
raise ValueError("Unsupported Jasper family model type: {}".format(model_type))
stage_repeat = np.full((8,), 1)
stage_repeat[1:-2] *= main_stage_repeat
channels = sum([[a] * r for (a, r) in zip(channels_per_stage, stage_repeat)], [])
kernel_sizes = sum([[a] * r for (a, r) in zip(kernel_sizes_per_stage, stage_repeat)], [])
dropout_rates = sum([[a] * r for (a, r) in zip(dropout_rates_per_stage, stage_repeat)], [])
net = Jasper(
channels=channels,
kernel_sizes=kernel_sizes,
bn_epsilon=bn_epsilon,
dropout_rates=dropout_rates,
repeat=repeat,
use_dw=use_dw,
use_dr=use_dr,
vocabulary=vocabulary,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def jasper5x3(**kwargs):
"""
Jasper 5x3 model from 'Jasper: An End-to-End Convolutional Neural Acoustic Model,'
https://arxiv.org/abs/1904.03288.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_jasper(version=("jasper", "5x3"), model_name="jasper5x3", **kwargs)
def jasper10x4(**kwargs):
"""
Jasper 10x4 model from 'Jasper: An End-to-End Convolutional Neural Acoustic Model,'
https://arxiv.org/abs/1904.03288.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_jasper(version=("jasper", "10x4"), model_name="jasper10x4", **kwargs)
def jasper10x5(**kwargs):
"""
Jasper 10x5 model from 'Jasper: An End-to-End Convolutional Neural Acoustic Model,'
https://arxiv.org/abs/1904.03288.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_jasper(version=("jasper", "10x5"), model_name="jasper10x5", **kwargs)
def _calc_width(net):
import numpy as np
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
return weight_count
def _test():
import mxnet as mx
pretrained = False
from_audio = True
# dither = 0.0
dither = 1.0e-5
audio_features = 64
classes = 29
models = [
jasper5x3,
jasper10x4,
jasper10x5,
]
for model in models:
net = model(
in_channels=audio_features,
classes=classes,
from_audio=from_audio,
dither=dither,
pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != jasper5x3 or weight_count == 107681053)
assert (model != jasper10x4 or weight_count == 261393693)
assert (model != jasper10x5 or weight_count == 322286877)
batch = 3
aud_scale = 640 if from_audio else 1
seq_len = np.random.randint(150, 250, batch) * aud_scale
seq_len_max = seq_len.max() + 2
x_shape = (batch, seq_len_max) if from_audio else (batch, audio_features, seq_len_max)
x = mx.nd.random.normal(shape=x_shape, ctx=ctx)
x_len = mx.nd.array(seq_len, ctx=ctx, dtype=np.long)
y, y_len = net(x, x_len)
assert (y.shape[:2] == (batch, net.classes))
if from_audio:
assert (y.shape[2] in range(seq_len_max // aud_scale * 2, seq_len_max // aud_scale * 2 + 9))
else:
assert (y.shape[2] in [seq_len_max // 2, seq_len_max // 2 + 1])
if __name__ == "__main__":
_test()
| 38,940 | 31.806234 | 120 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/resneta.py | """
ResNet(A) with average downsampling for ImageNet-1K, implemented in Gluon.
Original paper: 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
"""
__all__ = ['ResNetA', 'resneta10', 'resnetabc14b', 'resneta18', 'resneta50b', 'resneta101b', 'resneta152b']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block
from .resnet import ResBlock, ResBottleneck
from .senet import SEInitBlock
class ResADownBlock(HybridBlock):
"""
ResNet(A) downsample block for the identity branch of a residual unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
dilation : int or tuple/list of 2 int, default 1
Dilation value for the second convolution layer in bottleneck.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
strides,
dilation=1,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(ResADownBlock, self).__init__(**kwargs)
with self.name_scope():
self.pool = nn.AvgPool2D(
pool_size=(strides if dilation == 1 else 1),
strides=(strides if dilation == 1 else 1),
ceil_mode=True,
count_include_pad=False)
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=None)
def hybrid_forward(self, F, x):
x = self.pool(x)
x = self.conv(x)
return x
class ResAUnit(HybridBlock):
"""
ResNet(A) unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for the second convolution layer in bottleneck.
dilation : int or tuple/list of 2 int, default 1
Dilation value for the second convolution layer in bottleneck.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
bottleneck : bool, default True
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default False
Whether to use stride in the first or the second convolution layer of the block.
"""
def __init__(self,
in_channels,
out_channels,
strides,
padding=1,
dilation=1,
bn_use_global_stats=False,
bn_cudnn_off=False,
bottleneck=True,
conv1_stride=False,
**kwargs):
super(ResAUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
if bottleneck:
self.body = ResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
padding=padding,
dilation=dilation,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
conv1_stride=conv1_stride)
else:
self.body = ResBlock(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
if self.resize_identity:
self.identity_block = ResADownBlock(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
dilation=dilation,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_block(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class ResNetA(HybridBlock):
"""
ResNet(A) with average downsampling model from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
dilated : bool, default False
Whether to use dilation.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
bn_use_global_stats=False,
bn_cudnn_off=False,
dilated=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(ResNetA, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(SEInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
if dilated:
strides = 2 if ((j == 0) and (i != 0) and (i < 2)) else 1
dilation = (2 ** max(0, i - 1 - int(j == 0)))
else:
strides = 2 if (j == 0) and (i != 0) else 1
dilation = 1
stage.add(ResAUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
padding=dilation,
dilation=dilation,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
bottleneck=bottleneck,
conv1_stride=conv1_stride))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.GlobalAvgPool2D())
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_resneta(blocks,
bottleneck=None,
conv1_stride=True,
width_scale=1.0,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create ResNet(A) with average downsampling model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
bottleneck : bool, default None
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
width_scale : float, default 1.0
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if bottleneck is None:
bottleneck = (blocks >= 50)
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14 and not bottleneck:
layers = [2, 2, 1, 1]
elif (blocks == 14) and bottleneck:
layers = [1, 1, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif (blocks == 26) and not bottleneck:
layers = [3, 3, 3, 3]
elif (blocks == 26) and bottleneck:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif (blocks == 38) and bottleneck:
layers = [3, 3, 3, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
else:
raise ValueError("Unsupported ResNet(A) with number of blocks: {}".format(blocks))
if bottleneck:
assert (sum(layers) * 3 + 2 == blocks)
else:
assert (sum(layers) * 2 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [64, 128, 256, 512]
if bottleneck:
bottleneck_factor = 4
channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) if (i != len(channels) - 1) or (j != len(ci) - 1) else cij
for j, cij in enumerate(ci)] for i, ci in enumerate(channels)]
init_block_channels = int(init_block_channels * width_scale)
net = ResNetA(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def resneta10(**kwargs):
"""
ResNet(A)-10 with average downsampling model from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resneta(blocks=10, model_name="resneta10", **kwargs)
def resnetabc14b(**kwargs):
"""
ResNet(A)-BC-14b with average downsampling model from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385. It's an experimental model (bottleneck compressed).
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resneta(blocks=14, bottleneck=True, conv1_stride=False, model_name="resnetabc14b", **kwargs)
def resneta18(**kwargs):
"""
ResNet(A)-18 with average downsampling model from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resneta(blocks=18, model_name="resneta18", **kwargs)
def resneta50b(**kwargs):
"""
ResNet(A)-50 with average downsampling model with stride at the second convolution in bottleneck block
from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resneta(blocks=50, conv1_stride=False, model_name="resneta50b", **kwargs)
def resneta101b(**kwargs):
"""
ResNet(A)-101 with average downsampling model with stride at the second convolution in bottleneck
block from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resneta(blocks=101, conv1_stride=False, model_name="resneta101b", **kwargs)
def resneta152b(**kwargs):
"""
ResNet(A)-152 with average downsampling model with stride at the second convolution in bottleneck
block from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resneta(blocks=152, conv1_stride=False, model_name="resneta152b", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
resneta10,
resnetabc14b,
resneta18,
resneta50b,
resneta101b,
resneta152b,
]
for model in models:
net = model(
pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != resneta10 or weight_count == 5438024)
assert (model != resnetabc14b or weight_count == 10084168)
assert (model != resneta18 or weight_count == 11708744)
assert (model != resneta50b or weight_count == 25576264)
assert (model != resneta101b or weight_count == 44568392)
assert (model != resneta152b or weight_count == 60212040)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 17,132 | 34.545643 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/resnesta.py | """
ResNeSt(A) with average downsampling for ImageNet-1K, implemented in Gluon.
Original paper: 'ResNeSt: Split-Attention Networks,' https://arxiv.org/abs/2004.08955.
"""
__all__ = ['ResNeStA', 'resnestabc14', 'resnesta18', 'resnestabc26', 'resnestabc38', 'resnesta50', 'resnesta101',
'resnesta152', 'resnesta200', 'resnesta269', 'ResNeStADownBlock']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block, conv3x3_block, saconv3x3_block
from .senet import SEInitBlock
class ResNeStABlock(HybridBlock):
"""
Simple ResNeSt(A) block for residual path in ResNeSt(A) unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
strides,
use_bias=False,
use_bn=True,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(ResNeStABlock, self).__init__(**kwargs)
self.resize = (strides > 1)
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
if self.resize:
self.pool = nn.AvgPool2D(
pool_size=3,
strides=strides,
padding=1)
self.conv2 = saconv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=None)
def hybrid_forward(self, F, x):
x = self.conv1(x)
if self.resize:
x = self.pool(x)
x = self.conv2(x)
return x
class ResNeStABottleneck(HybridBlock):
"""
ResNeSt(A) bottleneck block for residual path in ResNeSt(A) unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
bottleneck_factor : int, default 4
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats=False,
bn_cudnn_off=False,
bottleneck_factor=4,
**kwargs):
super(ResNeStABottleneck, self).__init__(**kwargs)
self.resize = (strides > 1)
mid_channels = out_channels // bottleneck_factor
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.conv2 = saconv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
if self.resize:
self.pool = nn.AvgPool2D(
pool_size=3,
strides=strides,
padding=1)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=None)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
if self.resize:
x = self.pool(x)
x = self.conv3(x)
return x
class ResNeStADownBlock(HybridBlock):
"""
ResNeSt(A) downsample block for the identity branch of a residual unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(ResNeStADownBlock, self).__init__(**kwargs)
with self.name_scope():
self.pool = nn.AvgPool2D(
pool_size=strides,
strides=strides,
ceil_mode=True,
count_include_pad=False)
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=None)
def hybrid_forward(self, F, x):
x = self.pool(x)
x = self.conv(x)
return x
class ResNeStAUnit(HybridBlock):
"""
ResNeSt(A) unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
bottleneck : bool, default True
Whether to use a bottleneck or simple block in units.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats=False,
bn_cudnn_off=False,
bottleneck=True,
**kwargs):
super(ResNeStAUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
if bottleneck:
self.body = ResNeStABottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
else:
self.body = ResNeStABlock(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
if self.resize_identity:
self.identity_block = ResNeStADownBlock(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_block(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class ResNeStA(HybridBlock):
"""
ResNeSt(A) with average downsampling model from 'ResNeSt: Split-Attention Networks,'
https://arxiv.org/abs/2004.08955.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
dropout_rate : float, default 0.0
Fraction of the input units to drop. Must be a number between 0 and 1.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
dropout_rate=0.0,
bn_use_global_stats=False,
bn_cudnn_off=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(ResNeStA, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(SEInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
stage.add(ResNeStAUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
bottleneck=bottleneck))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.GlobalAvgPool2D())
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
if dropout_rate > 0.0:
self.output.add(nn.Dropout(rate=dropout_rate))
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_resnesta(blocks,
bottleneck=None,
width_scale=1.0,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create ResNeSt(A) with average downsampling model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
bottleneck : bool, default None
Whether to use a bottleneck or simple block in units.
width_scale : float, default 1.0
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if bottleneck is None:
bottleneck = (blocks >= 50)
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14 and not bottleneck:
layers = [2, 2, 1, 1]
elif (blocks == 14) and bottleneck:
layers = [1, 1, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif (blocks == 26) and not bottleneck:
layers = [3, 3, 3, 3]
elif (blocks == 26) and bottleneck:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif (blocks == 38) and bottleneck:
layers = [3, 3, 3, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
elif blocks == 269:
layers = [3, 30, 48, 8]
else:
raise ValueError("Unsupported ResNeSt(A) with number of blocks: {}".format(blocks))
if bottleneck:
assert (sum(layers) * 3 + 2 == blocks)
else:
assert (sum(layers) * 2 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [64, 128, 256, 512]
if blocks >= 101:
init_block_channels *= 2
if bottleneck:
bottleneck_factor = 4
channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) if (i != len(channels) - 1) or (j != len(ci) - 1) else cij
for j, cij in enumerate(ci)] for i, ci in enumerate(channels)]
init_block_channels = int(init_block_channels * width_scale)
net = ResNeStA(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def resnestabc14(**kwargs):
"""
ResNeSt(A)-BC-14 with average downsampling model from 'ResNeSt: Split-Attention Networks,'
https://arxiv.org/abs/2004.08955.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnesta(blocks=14, bottleneck=True, model_name="resnestabc14", **kwargs)
def resnesta18(**kwargs):
"""
ResNeSt(A)-18 with average downsampling model from 'ResNeSt: Split-Attention Networks,'
https://arxiv.org/abs/2004.08955.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnesta(blocks=18, model_name="resnesta18", **kwargs)
def resnestabc26(**kwargs):
"""
ResNeSt(A)-BC-26 with average downsampling model from 'ResNeSt: Split-Attention Networks,'
https://arxiv.org/abs/2004.08955.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnesta(blocks=26, bottleneck=True, model_name="resnestabc26", **kwargs)
def resnestabc38(**kwargs):
"""
ResNeSt(A)-BC-38 with average downsampling model from 'ResNeSt: Split-Attention Networks,'
https://arxiv.org/abs/2004.08955.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnesta(blocks=38, bottleneck=True, model_name="resnestabc38", **kwargs)
def resnesta50(**kwargs):
"""
ResNeSt(A)-50 with average downsampling model with stride at the second convolution in bottleneck block
from 'ResNeSt: Split-Attention Networks,' https://arxiv.org/abs/2004.08955.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnesta(blocks=50, model_name="resnesta50", **kwargs)
def resnesta101(**kwargs):
"""
ResNeSt(A)-101 with average downsampling model with stride at the second convolution in bottleneck
block from 'ResNeSt: Split-Attention Networks,' https://arxiv.org/abs/2004.08955.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnesta(blocks=101, model_name="resnesta101", **kwargs)
def resnesta152(**kwargs):
"""
ResNeSt(A)-152 with average downsampling model with stride at the second convolution in bottleneck
block from 'ResNeSt: Split-Attention Networks,' https://arxiv.org/abs/2004.08955.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnesta(blocks=152, model_name="resnesta152", **kwargs)
def resnesta200(in_size=(256, 256), **kwargs):
"""
ResNeSt(A)-200 with average downsampling model with stride at the second convolution in bottleneck
block from 'ResNeSt: Split-Attention Networks,' https://arxiv.org/abs/2004.08955.
Parameters:
----------
in_size : tuple of two ints, default (256, 256)
Spatial size of the expected input image.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnesta(blocks=200, in_size=in_size, dropout_rate=0.2, model_name="resnesta200", **kwargs)
def resnesta269(in_size=(320, 320), **kwargs):
"""
ResNeSt(A)-269 with average downsampling model with stride at the second convolution in bottleneck
block from 'ResNeSt: Split-Attention Networks,' https://arxiv.org/abs/2004.08955.
Parameters:
----------
in_size : tuple of two ints, default (320, 320)
Spatial size of the expected input image.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnesta(blocks=269, in_size=in_size, dropout_rate=0.2, model_name="resnesta269", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
(resnestabc14, 224),
(resnesta18, 224),
(resnestabc26, 224),
(resnestabc38, 224),
(resnesta50, 224),
(resnesta101, 224),
(resnesta152, 224),
(resnesta200, 256),
(resnesta269, 320),
]
for model, size in models:
net = model(
pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != resnestabc14 or weight_count == 10611688)
assert (model != resnesta18 or weight_count == 12763784)
assert (model != resnestabc26 or weight_count == 17069448)
assert (model != resnestabc38 or weight_count == 23527208)
assert (model != resnesta50 or weight_count == 27483240)
assert (model != resnesta101 or weight_count == 48275016)
assert (model != resnesta152 or weight_count == 65316040)
assert (model != resnesta200 or weight_count == 70201544)
assert (model != resnesta269 or weight_count == 110929480)
batch = 14
x = mx.nd.zeros((batch, 3, size, size), ctx=ctx)
y = net(x)
assert (y.shape == (batch, 1000))
if __name__ == "__main__":
_test()
| 22,512 | 33.849845 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/senet.py | """
SENet for ImageNet-1K, implemented in Gluon.
Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
"""
__all__ = ['SENet', 'senet16', 'senet28', 'senet40', 'senet52', 'senet103', 'senet154', 'SEInitBlock']
import os
import math
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block, conv3x3_block, SEBlock
class SENetBottleneck(HybridBlock):
"""
SENet bottleneck block for residual path in SENet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
cardinality,
bottleneck_width,
bn_use_global_stats,
**kwargs):
super(SENetBottleneck, self).__init__(**kwargs)
mid_channels = out_channels // 4
D = int(math.floor(mid_channels * (bottleneck_width / 64.0)))
group_width = cardinality * D
group_width2 = group_width // 2
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=group_width2,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = conv3x3_block(
in_channels=group_width2,
out_channels=group_width,
strides=strides,
groups=cardinality,
bn_use_global_stats=bn_use_global_stats)
self.conv3 = conv1x1_block(
in_channels=group_width,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation=None)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class SENetUnit(HybridBlock):
"""
SENet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
identity_conv3x3 : bool, default False
Whether to use 3x3 convolution in the identity link.
"""
def __init__(self,
in_channels,
out_channels,
strides,
cardinality,
bottleneck_width,
bn_use_global_stats,
identity_conv3x3,
**kwargs):
super(SENetUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
self.body = SENetBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
bn_use_global_stats=bn_use_global_stats)
self.se = SEBlock(channels=out_channels)
if self.resize_identity:
if identity_conv3x3:
self.identity_conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
activation=None)
else:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
activation=None)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = self.se(x)
x = x + identity
x = self.activ(x)
return x
class SEInitBlock(HybridBlock):
"""
SENet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(SEInitBlock, self).__init__(**kwargs)
mid_channels = out_channels // 2
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels,
strides=2,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.conv3 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.pool = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=1)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.pool(x)
return x
class SENet(HybridBlock):
"""
SENet model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
cardinality,
bottleneck_width,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(SENet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(SEInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
identity_conv3x3 = (i != 0)
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
stage.add(SENetUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
bn_use_global_stats=bn_use_global_stats,
identity_conv3x3=identity_conv3x3))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dropout(rate=0.2))
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_senet(blocks,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create SENet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if blocks == 16:
layers = [1, 1, 1, 1]
cardinality = 32
elif blocks == 28:
layers = [2, 2, 2, 2]
cardinality = 32
elif blocks == 40:
layers = [3, 3, 3, 3]
cardinality = 32
elif blocks == 52:
layers = [3, 4, 6, 3]
cardinality = 32
elif blocks == 103:
layers = [3, 4, 23, 3]
cardinality = 32
elif blocks == 154:
layers = [3, 8, 36, 3]
cardinality = 64
else:
raise ValueError("Unsupported SENet with number of blocks: {}".format(blocks))
bottleneck_width = 4
init_block_channels = 128
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = SENet(
channels=channels,
init_block_channels=init_block_channels,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def senet16(**kwargs):
"""
SENet-16 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_senet(blocks=16, model_name="senet16", **kwargs)
def senet28(**kwargs):
"""
SENet-28 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_senet(blocks=28, model_name="senet28", **kwargs)
def senet40(**kwargs):
"""
SENet-40 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_senet(blocks=40, model_name="senet40", **kwargs)
def senet52(**kwargs):
"""
SENet-52 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_senet(blocks=52, model_name="senet52", **kwargs)
def senet103(**kwargs):
"""
SENet-103 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_senet(blocks=103, model_name="senet103", **kwargs)
def senet154(**kwargs):
"""
SENet-154 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_senet(blocks=154, model_name="senet154", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
senet16,
senet28,
senet40,
senet52,
senet103,
senet154,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != senet16 or weight_count == 31366168)
assert (model != senet28 or weight_count == 36453768)
assert (model != senet40 or weight_count == 41541368)
assert (model != senet52 or weight_count == 44659416)
assert (model != senet103 or weight_count == 60963096)
assert (model != senet154 or weight_count == 115088984)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 15,863 | 31.641975 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/diapreresnet_cifar.py | """
DIA-PreResNet for CIFAR/SVHN, implemented in Gluon.
Original papers: 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
"""
__all__ = ['CIFARDIAPreResNet', 'diapreresnet20_cifar10', 'diapreresnet20_cifar100', 'diapreresnet20_svhn',
'diapreresnet56_cifar10', 'diapreresnet56_cifar100', 'diapreresnet56_svhn', 'diapreresnet110_cifar10',
'diapreresnet110_cifar100', 'diapreresnet110_svhn', 'diapreresnet164bn_cifar10',
'diapreresnet164bn_cifar100', 'diapreresnet164bn_svhn', 'diapreresnet1001_cifar10',
'diapreresnet1001_cifar100', 'diapreresnet1001_svhn', 'diapreresnet1202_cifar10',
'diapreresnet1202_cifar100', 'diapreresnet1202_svhn']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv3x3, DualPathSequential
from .preresnet import PreResActivation
from .diaresnet import DIAAttention
from .diapreresnet import DIAPreResUnit
class CIFARDIAPreResNet(HybridBlock):
"""
DIA-PreResNet model for CIFAR from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
bn_use_global_stats=False,
in_channels=3,
in_size=(32, 32),
classes=10,
**kwargs):
super(CIFARDIAPreResNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(conv3x3(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = DualPathSequential(
return_two=False,
prefix="stage{}_".format(i + 1))
attention = DIAAttention(
in_x_features=channels_per_stage[0],
in_h_features=channels_per_stage[0])
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
stage.add(DIAPreResUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bottleneck=bottleneck,
conv1_stride=False,
attention=attention))
in_channels = out_channels
self.features.add(stage)
self.features.add(PreResActivation(
in_channels=in_channels,
bn_use_global_stats=bn_use_global_stats))
self.features.add(nn.AvgPool2D(
pool_size=8,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_diapreresnet_cifar(classes,
blocks,
bottleneck,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create DIA-PreResNet model for CIFAR with specific parameters.
Parameters:
----------
classes : int
Number of classification classes.
blocks : int
Number of blocks.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
assert (classes in [10, 100])
if bottleneck:
assert ((blocks - 2) % 9 == 0)
layers = [(blocks - 2) // 9] * 3
else:
assert ((blocks - 2) % 6 == 0)
layers = [(blocks - 2) // 6] * 3
channels_per_layers = [16, 32, 64]
init_block_channels = 16
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if bottleneck:
channels = [[cij * 4 for cij in ci] for ci in channels]
net = CIFARDIAPreResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
classes=classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def diapreresnet20_cifar10(classes=10, **kwargs):
"""
DIA-PreResNet-20 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="diapreresnet20_cifar10",
**kwargs)
def diapreresnet20_cifar100(classes=100, **kwargs):
"""
DIA-PreResNet-20 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="diapreresnet20_cifar100",
**kwargs)
def diapreresnet20_svhn(classes=10, **kwargs):
"""
DIA-PreResNet-20 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="diapreresnet20_svhn",
**kwargs)
def diapreresnet56_cifar10(classes=10, **kwargs):
"""
DIA-PreResNet-56 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name="diapreresnet56_cifar10",
**kwargs)
def diapreresnet56_cifar100(classes=100, **kwargs):
"""
DIA-PreResNet-56 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name="diapreresnet56_cifar100",
**kwargs)
def diapreresnet56_svhn(classes=10, **kwargs):
"""
DIA-PreResNet-56 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name="diapreresnet56_svhn",
**kwargs)
def diapreresnet110_cifar10(classes=10, **kwargs):
"""
DIA-PreResNet-110 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name="diapreresnet110_cifar10",
**kwargs)
def diapreresnet110_cifar100(classes=100, **kwargs):
"""
DIA-PreResNet-110 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name="diapreresnet110_cifar100",
**kwargs)
def diapreresnet110_svhn(classes=10, **kwargs):
"""
DIA-PreResNet-110 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name="diapreresnet110_svhn",
**kwargs)
def diapreresnet164bn_cifar10(classes=10, **kwargs):
"""
DIA-PreResNet-164(BN) model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name="diapreresnet164bn_cifar10",
**kwargs)
def diapreresnet164bn_cifar100(classes=100, **kwargs):
"""
DIA-PreResNet-164(BN) model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name="diapreresnet164bn_cifar100",
**kwargs)
def diapreresnet164bn_svhn(classes=10, **kwargs):
"""
DIA-PreResNet-164(BN) model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name="diapreresnet164bn_svhn",
**kwargs)
def diapreresnet1001_cifar10(classes=10, **kwargs):
"""
DIA-PreResNet-1001 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="diapreresnet1001_cifar10",
**kwargs)
def diapreresnet1001_cifar100(classes=100, **kwargs):
"""
DIA-PreResNet-1001 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="diapreresnet1001_cifar100",
**kwargs)
def diapreresnet1001_svhn(classes=10, **kwargs):
"""
DIA-PreResNet-1001 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="diapreresnet1001_svhn",
**kwargs)
def diapreresnet1202_cifar10(classes=10, **kwargs):
"""
DIA-PreResNet-1202 model for CIFAR-10 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name="diapreresnet1202_cifar10",
**kwargs)
def diapreresnet1202_cifar100(classes=100, **kwargs):
"""
DIA-PreResNet-1202 model for CIFAR-100 from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=1202, bottleneck=False,
model_name="diapreresnet1202_cifar100", **kwargs)
def diapreresnet1202_svhn(classes=10, **kwargs):
"""
DIA-PreResNet-1202 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,'
https://arxiv.org/abs/1905.10671.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name="diapreresnet1202_svhn",
**kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
(diapreresnet20_cifar10, 10),
(diapreresnet20_cifar100, 100),
(diapreresnet20_svhn, 10),
(diapreresnet56_cifar10, 10),
(diapreresnet56_cifar100, 100),
(diapreresnet56_svhn, 10),
(diapreresnet110_cifar10, 10),
(diapreresnet110_cifar100, 100),
(diapreresnet110_svhn, 10),
(diapreresnet164bn_cifar10, 10),
(diapreresnet164bn_cifar100, 100),
(diapreresnet164bn_svhn, 10),
(diapreresnet1001_cifar10, 10),
(diapreresnet1001_cifar100, 100),
(diapreresnet1001_svhn, 10),
(diapreresnet1202_cifar10, 10),
(diapreresnet1202_cifar100, 100),
(diapreresnet1202_svhn, 10),
]
for model, classes in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != diapreresnet20_cifar10 or weight_count == 286674)
assert (model != diapreresnet20_cifar100 or weight_count == 292524)
assert (model != diapreresnet20_svhn or weight_count == 286674)
assert (model != diapreresnet56_cifar10 or weight_count == 869970)
assert (model != diapreresnet56_cifar100 or weight_count == 875820)
assert (model != diapreresnet56_svhn or weight_count == 869970)
assert (model != diapreresnet110_cifar10 or weight_count == 1744914)
assert (model != diapreresnet110_cifar100 or weight_count == 1750764)
assert (model != diapreresnet110_svhn or weight_count == 1744914)
assert (model != diapreresnet164bn_cifar10 or weight_count == 1922106)
assert (model != diapreresnet164bn_cifar100 or weight_count == 1945236)
assert (model != diapreresnet164bn_svhn or weight_count == 1922106)
assert (model != diapreresnet1001_cifar10 or weight_count == 10546554)
assert (model != diapreresnet1001_cifar100 or weight_count == 10569684)
assert (model != diapreresnet1001_svhn or weight_count == 10546554)
assert (model != diapreresnet1202_cifar10 or weight_count == 19438226)
assert (model != diapreresnet1202_cifar100 or weight_count == 19444076)
assert (model != diapreresnet1202_svhn or weight_count == 19438226)
x = mx.nd.zeros((1, 3, 32, 32), ctx=ctx)
y = net(x)
assert (y.shape == (1, classes))
if __name__ == "__main__":
_test()
| 22,523 | 36.855462 | 120 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/simplepose_coco.py | """
SimplePose for COCO Keypoint, implemented in Gluon.
Original paper: 'Simple Baselines for Human Pose Estimation and Tracking,' https://arxiv.org/abs/1804.06208.
"""
__all__ = ['SimplePose', 'simplepose_resnet18_coco', 'simplepose_resnet50b_coco', 'simplepose_resnet101b_coco',
'simplepose_resnet152b_coco', 'simplepose_resneta50b_coco', 'simplepose_resneta101b_coco',
'simplepose_resneta152b_coco', 'HeatmapMaxDetBlock']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import DeconvBlock, conv1x1, HeatmapMaxDetBlock
from .resnet import resnet18, resnet50b, resnet101b, resnet152b
from .resneta import resneta50b, resneta101b, resneta152b
class SimplePose(HybridBlock):
"""
SimplePose model from 'Simple Baselines for Human Pose Estimation and Tracking,' https://arxiv.org/abs/1804.06208.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
backbone_out_channels : int
Number of output channels for the backbone.
channels : list of int
Number of output channels for each decoder unit.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
bn_cudnn_off : bool, default True
Whether to disable CUDNN batch normalization operator.
return_heatmap : bool, default False
Whether to return only heatmap.
fixed_size : bool, default True
Whether to expect fixed spatial size of input image.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (256, 192)
Spatial size of the expected input image.
keypoints : int, default 17
Number of keypoints.
"""
def __init__(self,
backbone,
backbone_out_channels,
channels,
bn_use_global_stats=False,
bn_cudnn_off=True,
return_heatmap=False,
fixed_size=True,
in_channels=3,
in_size=(256, 192),
keypoints=17,
**kwargs):
super(SimplePose, self).__init__(**kwargs)
assert (in_channels == 3)
self.in_size = in_size
self.keypoints = keypoints
self.return_heatmap = return_heatmap
with self.name_scope():
self.backbone = backbone
self.decoder = nn.HybridSequential(prefix="")
in_channels = backbone_out_channels
for out_channels in channels:
self.decoder.add(DeconvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=4,
strides=2,
padding=1,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
in_channels = out_channels
self.decoder.add(conv1x1(
in_channels=in_channels,
out_channels=keypoints,
use_bias=True))
self.heatmap_max_det = HeatmapMaxDetBlock(
channels=keypoints,
in_size=(in_size[0] // 4, in_size[1] // 4),
fixed_size=fixed_size)
def hybrid_forward(self, F, x):
x = self.backbone(x)
heatmap = self.decoder(x)
if self.return_heatmap:
return heatmap
else:
keypoints = self.heatmap_max_det(heatmap)
return keypoints
def get_simplepose(backbone,
backbone_out_channels,
keypoints,
bn_cudnn_off,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create SimplePose model with specific parameters.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
backbone_out_channels : int
Number of output channels for the backbone.
keypoints : int
Number of keypoints.
bn_cudnn_off : bool
Whether to disable CUDNN batch normalization operator.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
channels = [256, 256, 256]
net = SimplePose(
backbone=backbone,
backbone_out_channels=backbone_out_channels,
channels=channels,
bn_cudnn_off=bn_cudnn_off,
keypoints=keypoints,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def simplepose_resnet18_coco(pretrained_backbone=False, keypoints=17, bn_cudnn_off=True, **kwargs):
"""
SimplePose model on the base of ResNet-18 for COCO Keypoint from 'Simple Baselines for Human Pose Estimation and
Tracking,' https://arxiv.org/abs/1804.06208.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
keypoints : int, default 17
Number of keypoints.
bn_cudnn_off : bool, default True
Whether to disable CUDNN batch normalization operator.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnet18(pretrained=pretrained_backbone, bn_cudnn_off=bn_cudnn_off).features[:-1]
return get_simplepose(backbone=backbone, backbone_out_channels=512, keypoints=keypoints, bn_cudnn_off=bn_cudnn_off,
model_name="simplepose_resnet18_coco", **kwargs)
def simplepose_resnet50b_coco(pretrained_backbone=False, keypoints=17, bn_cudnn_off=True, **kwargs):
"""
SimplePose model on the base of ResNet-50b for COCO Keypoint from 'Simple Baselines for Human Pose Estimation and
Tracking,' https://arxiv.org/abs/1804.06208.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
keypoints : int, default 17
Number of keypoints.
bn_cudnn_off : bool, default True
Whether to disable CUDNN batch normalization operator.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnet50b(pretrained=pretrained_backbone, bn_cudnn_off=bn_cudnn_off).features[:-1]
return get_simplepose(backbone=backbone, backbone_out_channels=2048, keypoints=keypoints, bn_cudnn_off=bn_cudnn_off,
model_name="simplepose_resnet50b_coco", **kwargs)
def simplepose_resnet101b_coco(pretrained_backbone=False, keypoints=17, bn_cudnn_off=True, **kwargs):
"""
SimplePose model on the base of ResNet-101b for COCO Keypoint from 'Simple Baselines for Human Pose Estimation
and Tracking,' https://arxiv.org/abs/1804.06208.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
keypoints : int, default 17
Number of keypoints.
bn_cudnn_off : bool, default True
Whether to disable CUDNN batch normalization operator.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnet101b(pretrained=pretrained_backbone, bn_cudnn_off=bn_cudnn_off).features[:-1]
return get_simplepose(backbone=backbone, backbone_out_channels=2048, keypoints=keypoints, bn_cudnn_off=bn_cudnn_off,
model_name="simplepose_resnet101b_coco", **kwargs)
def simplepose_resnet152b_coco(pretrained_backbone=False, keypoints=17, bn_cudnn_off=True, **kwargs):
"""
SimplePose model on the base of ResNet-152b for COCO Keypoint from 'Simple Baselines for Human Pose Estimation
and Tracking,' https://arxiv.org/abs/1804.06208.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
keypoints : int, default 17
Number of keypoints.
bn_cudnn_off : bool, default True
Whether to disable CUDNN batch normalization operator.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnet152b(pretrained=pretrained_backbone, bn_cudnn_off=bn_cudnn_off).features[:-1]
return get_simplepose(backbone=backbone, backbone_out_channels=2048, keypoints=keypoints, bn_cudnn_off=bn_cudnn_off,
model_name="simplepose_resnet152b_coco", **kwargs)
def simplepose_resneta50b_coco(pretrained_backbone=False, keypoints=17, bn_cudnn_off=True, **kwargs):
"""
SimplePose model on the base of ResNet(A)-50b for COCO Keypoint from 'Simple Baselines for Human Pose Estimation
and Tracking,' https://arxiv.org/abs/1804.06208.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
keypoints : int, default 17
Number of keypoints.
bn_cudnn_off : bool, default True
Whether to disable CUDNN batch normalization operator.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resneta50b(pretrained=pretrained_backbone, bn_cudnn_off=bn_cudnn_off).features[:-1]
return get_simplepose(backbone=backbone, backbone_out_channels=2048, keypoints=keypoints, bn_cudnn_off=bn_cudnn_off,
model_name="simplepose_resneta50b_coco", **kwargs)
def simplepose_resneta101b_coco(pretrained_backbone=False, keypoints=17, bn_cudnn_off=True, **kwargs):
"""
SimplePose model on the base of ResNet(A)-101b for COCO Keypoint from 'Simple Baselines for Human Pose Estimation
and Tracking,' https://arxiv.org/abs/1804.06208.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
keypoints : int, default 17
Number of keypoints.
bn_cudnn_off : bool, default True
Whether to disable CUDNN batch normalization operator.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resneta101b(pretrained=pretrained_backbone, bn_cudnn_off=bn_cudnn_off).features[:-1]
return get_simplepose(backbone=backbone, backbone_out_channels=2048, keypoints=keypoints, bn_cudnn_off=bn_cudnn_off,
model_name="simplepose_resneta101b_coco", **kwargs)
def simplepose_resneta152b_coco(pretrained_backbone=False, keypoints=17, bn_cudnn_off=True, **kwargs):
"""
SimplePose model on the base of ResNet(A)-152b for COCO Keypoint from 'Simple Baselines for Human Pose Estimation
and Tracking,' https://arxiv.org/abs/1804.06208.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
keypoints : int, default 17
Number of keypoints.
bn_cudnn_off : bool, default True
Whether to disable CUDNN batch normalization operator.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resneta152b(pretrained=pretrained_backbone, bn_cudnn_off=bn_cudnn_off).features[:-1]
return get_simplepose(backbone=backbone, backbone_out_channels=2048, keypoints=keypoints, bn_cudnn_off=bn_cudnn_off,
model_name="simplepose_resneta152b_coco", **kwargs)
def _test():
import numpy as np
import mxnet as mx
in_size = (256, 192)
keypoints = 17
return_heatmap = True
pretrained = False
models = [
simplepose_resnet18_coco,
simplepose_resnet50b_coco,
simplepose_resnet101b_coco,
simplepose_resnet152b_coco,
simplepose_resneta50b_coco,
simplepose_resneta101b_coco,
simplepose_resneta152b_coco,
]
for model in models:
net = model(pretrained=pretrained, in_size=in_size, return_heatmap=return_heatmap)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != simplepose_resnet18_coco or weight_count == 15376721)
assert (model != simplepose_resnet50b_coco or weight_count == 33999697)
assert (model != simplepose_resnet101b_coco or weight_count == 52991825)
assert (model != simplepose_resnet152b_coco or weight_count == 68635473)
assert (model != simplepose_resneta50b_coco or weight_count == 34018929)
assert (model != simplepose_resneta101b_coco or weight_count == 53011057)
assert (model != simplepose_resneta152b_coco or weight_count == 68654705)
batch = 14
x = mx.nd.random.normal(shape=(batch, 3, in_size[0], in_size[1]), ctx=ctx)
y = net(x)
assert ((y.shape[0] == batch) and (y.shape[1] == keypoints))
if return_heatmap:
assert ((y.shape[2] == x.shape[2] // 4) and (y.shape[3] == x.shape[3] // 4))
else:
assert (y.shape[2] == 3)
if __name__ == "__main__":
_test()
| 15,538 | 39.571802 | 120 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/vovnet.py | """
VoVNet for ImageNet-1K, implemented in Gluon.
Original paper: 'An Energy and GPU-Computation Efficient Backbone Network for Real-Time Object Detection,'
https://arxiv.org/abs/1904.09730.
"""
__all__ = ['VoVNet', 'vovnet27s', 'vovnet39', 'vovnet57']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block, conv3x3_block, SequentialConcurrent
class VoVUnit(HybridBlock):
"""
VoVNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
branch_channels : int
Number of output channels for each branch.
num_branches : int
Number of branches.
resize : bool
Whether to use resize block.
use_residual : bool
Whether to use residual block.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
branch_channels,
num_branches,
resize,
use_residual,
bn_use_global_stats=False,
**kwargs):
super(VoVUnit, self).__init__(**kwargs)
self.resize = resize
self.use_residual = use_residual
with self.name_scope():
if self.resize:
self.pool = nn.MaxPool2D(
pool_size=3,
strides=2,
ceil_mode=True)
self.branches = SequentialConcurrent(prefix="")
with self.branches.name_scope():
branch_in_channels = in_channels
for i in range(num_branches):
self.branches.add(conv3x3_block(
in_channels=branch_in_channels,
out_channels=branch_channels,
bn_use_global_stats=bn_use_global_stats))
branch_in_channels = branch_channels
self.concat_conv = conv1x1_block(
in_channels=(in_channels + num_branches * branch_channels),
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
if self.resize:
x = self.pool(x)
if self.use_residual:
identity = x
x = self.branches(x)
x = self.concat_conv(x)
if self.use_residual:
x = x + identity
return x
class VoVInitBlock(HybridBlock):
"""
VoVNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats=False,
**kwargs):
super(VoVInitBlock, self).__init__(**kwargs)
mid_channels = out_channels // 2
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels,
strides=2,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats)
self.conv3 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
strides=2,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class VoVNet(HybridBlock):
"""
VoVNet model from 'An Energy and GPU-Computation Efficient Backbone Network for Real-Time Object Detection,'
https://arxiv.org/abs/1904.09730.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
branch_channels : list of list of int
Number of branch output channels for each unit.
num_branches : int
Number of branches for the each unit.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
branch_channels,
num_branches,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(VoVNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
init_block_channels = 128
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(VoVInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
use_residual = (j != 0)
resize = (j == 0) and (i != 0)
stage.add(VoVUnit(
in_channels=in_channels,
out_channels=out_channels,
branch_channels=branch_channels[i][j],
num_branches=num_branches,
resize=resize,
use_residual=use_residual,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_vovnet(blocks,
slim=False,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
slim : bool, default False
Whether to use a slim model.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if blocks == 27:
layers = [1, 1, 1, 1]
elif blocks == 39:
layers = [1, 1, 2, 2]
elif blocks == 57:
layers = [1, 1, 4, 3]
else:
raise ValueError("Unsupported VoVNet with number of blocks: {}".format(blocks))
assert (sum(layers) * 6 + 3 == blocks)
num_branches = 5
channels_per_layers = [256, 512, 768, 1024]
branch_channels_per_layers = [128, 160, 192, 224]
if slim:
channels_per_layers = [ci // 2 for ci in channels_per_layers]
branch_channels_per_layers = [ci // 2 for ci in branch_channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
branch_channels = [[ci] * li for (ci, li) in zip(branch_channels_per_layers, layers)]
net = VoVNet(
channels=channels,
branch_channels=branch_channels,
num_branches=num_branches,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def vovnet27s(**kwargs):
"""
VoVNet-27-slim model from 'An Energy and GPU-Computation Efficient Backbone Network for Real-Time Object Detection,'
https://arxiv.org/abs/1904.09730.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_vovnet(blocks=27, slim=True, model_name="vovnet27s", **kwargs)
def vovnet39(**kwargs):
"""
VoVNet-39 model from 'An Energy and GPU-Computation Efficient Backbone Network for Real-Time Object Detection,'
https://arxiv.org/abs/1904.09730.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_vovnet(blocks=39, model_name="vovnet39", **kwargs)
def vovnet57(**kwargs):
"""
VoVNet-57 model from 'An Energy and GPU-Computation Efficient Backbone Network for Real-Time Object Detection,'
https://arxiv.org/abs/1904.09730.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_vovnet(blocks=57, model_name="vovnet57", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
vovnet27s,
vovnet39,
vovnet57,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != vovnet27s or weight_count == 3525736)
assert (model != vovnet39 or weight_count == 22600296)
assert (model != vovnet57 or weight_count == 36640296)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 11,803 | 32.064426 | 120 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/crunetb.py | """
CRU-Net(b), implemented in Gluon.
Original paper: 'Sharing Residual Units Through Collective Tensor Factorization To Improve Deep Neural Networks,'
https://www.ijcai.org/proceedings/2018/88.
"""
__all__ = ['CRUNetb', 'crunet56b', 'crunet116b']
import os
import math
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv3x3, pre_conv1x1_block, pre_conv3x3_block
from .resnet import ResInitBlock
from .preresnet import PreResActivation
class CRUConvBlock(HybridBlock):
"""
CRU-Net specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
groups : int, default 1
Number of groups.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
return_preact : bool, default False
Whether return pre-activation. It's used by PreResNet.
shared_conv : HybridBlock, default None
Shared convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
groups=1,
bn_use_global_stats=False,
return_preact=False,
shared_conv=None,
**kwargs):
super(CRUConvBlock, self).__init__(**kwargs)
self.return_preact = return_preact
with self.name_scope():
self.bn = nn.BatchNorm(
in_channels=in_channels,
use_global_stats=bn_use_global_stats)
self.activ = nn.Activation("relu")
if shared_conv is None:
self.conv = nn.Conv2D(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
groups=groups,
use_bias=False,
in_channels=in_channels)
else:
self.conv = shared_conv
def hybrid_forward(self, F, x):
x = self.bn(x)
x = self.activ(x)
if self.return_preact:
x_pre_activ = x
x = self.conv(x)
if self.return_preact:
return x, x_pre_activ
else:
return x
def cru_conv1x1_block(in_channels,
out_channels,
strides=1,
bn_use_global_stats=False,
return_preact=False,
shared_conv=None):
"""
1x1 version of the CRU-Net specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
return_preact : bool, default False
Whether return pre-activation.
shared_conv : HybridBlock, default None
Shared convolution layer.
"""
return CRUConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
strides=strides,
padding=0,
bn_use_global_stats=bn_use_global_stats,
return_preact=return_preact,
shared_conv=shared_conv)
class ResBottleneck(HybridBlock):
"""
Pre-ResNeXt bottleneck block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
cardinality,
bottleneck_width,
bn_use_global_stats,
**kwargs):
super(ResBottleneck, self).__init__(**kwargs)
mid_channels = out_channels // 4
D = int(math.floor(mid_channels * (bottleneck_width / 64.0)))
group_width = cardinality * D
with self.name_scope():
self.conv1 = pre_conv1x1_block(
in_channels=in_channels,
out_channels=group_width,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = pre_conv3x3_block(
in_channels=group_width,
out_channels=group_width,
strides=strides,
groups=cardinality,
bn_use_global_stats=bn_use_global_stats)
self.conv3 = pre_conv1x1_block(
in_channels=group_width,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class CRUBottleneck(HybridBlock):
"""
CRU-Net bottleneck block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
group_width: int
Group width parameter.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
shared_conv1 : HybridBlock, default None
Shared convolution layer #1.
shared_conv2 : HybridBlock, default None
Shared convolution layer #2.
"""
def __init__(self,
in_channels,
out_channels,
strides,
group_width,
bn_use_global_stats,
shared_conv1=None,
shared_conv2=None,
**kwargs):
super(CRUBottleneck, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = cru_conv1x1_block(
in_channels=in_channels,
out_channels=group_width,
bn_use_global_stats=bn_use_global_stats,
shared_conv=shared_conv1)
if shared_conv2 is None:
self.conv2 = conv3x3(
in_channels=group_width,
out_channels=group_width,
strides=strides,
groups=group_width)
else:
self.conv2 = shared_conv2
self.conv3 = pre_conv1x1_block(
in_channels=group_width,
out_channels=group_width,
bn_use_global_stats=bn_use_global_stats)
self.conv4 = pre_conv1x1_block(
in_channels=group_width,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.conv4(x)
return x
class ResUnit(HybridBlock):
"""
CRU-Net residual unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
cardinality,
bottleneck_width,
bn_use_global_stats,
**kwargs):
super(ResUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
self.body = ResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
bn_use_global_stats=bn_use_global_stats)
if self.resize_identity:
self.identity_conv = pre_conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
return x
class CRUUnit(HybridBlock):
"""
CRU-Net collective residual unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
group_width: int
Group width parameter.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
shared_conv1 : HybridBlock, default None
Shared convolution layer #1.
shared_conv2 : HybridBlock, default None
Shared convolution layer #2.
"""
def __init__(self,
in_channels,
out_channels,
strides,
group_width,
bn_use_global_stats,
shared_conv1=None,
shared_conv2=None,
**kwargs):
super(CRUUnit, self).__init__(**kwargs)
assert (strides == 1) or ((shared_conv1 is None) and (shared_conv2 is None))
self.resize_input = (in_channels != out_channels)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
if self.resize_input:
self.input_conv = pre_conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
self.body = CRUBottleneck(
in_channels=out_channels,
out_channels=out_channels,
strides=strides,
group_width=group_width,
bn_use_global_stats=bn_use_global_stats,
shared_conv1=shared_conv1,
shared_conv2=shared_conv2)
if self.resize_identity:
# assert (self.input_conv.conv._kwargs["stride"][0] == strides)
self.identity_conv = cru_conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
shared_conv=self.input_conv.conv if strides == 1 else None)
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
if self.resize_input:
x = self.input_conv(x)
x = self.body(x)
x = x + identity
return x
class CRUNetb(HybridBlock):
"""
CRU-Net(b) model from 'Sharing Residual Units Through Collective Tensor Factorization To Improve Deep Neural
Networks,' https://www.ijcai.org/proceedings/2018/88.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
group_widths: list of int
List of group width parameters.
refresh_steps: list of int
List of refresh step parameters.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
cardinality,
bottleneck_width,
group_widths,
refresh_steps,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(CRUNetb, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
group_width = group_widths[i]
refresh_step = refresh_steps[i]
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
if group_width != 0:
if ((refresh_step == 0) and (j == 0)) or ((refresh_step != 0) and (j % refresh_step == 0)):
shared_conv1 = None
shared_conv2 = None
if (shared_conv2 is not None) and (shared_conv2._kwargs["stride"][0] != 1) and\
(strides == 1):
shared_conv2 = None
unit = CRUUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
group_width=group_width,
bn_use_global_stats=bn_use_global_stats,
shared_conv1=shared_conv1,
shared_conv2=shared_conv2)
if shared_conv1 is None:
shared_conv1 = unit.body.conv1.conv
if shared_conv2 is None:
shared_conv2 = unit.body.conv2
stage.add(unit)
else:
stage.add(ResUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(PreResActivation(
in_channels=in_channels,
bn_use_global_stats=bn_use_global_stats))
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_crunetb(blocks,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create CRU-Net(b) model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
cardinality = 32
bottleneck_width = 4
if blocks == 56:
layers = [3, 4, 6, 3]
group_widths = [0, 0, 640, 0]
refresh_steps = [0, 0, 0, 0]
elif blocks == 116:
layers = [3, 6, 18, 3]
group_widths = [0, 352, 704, 0]
refresh_steps = [0, 0, 6, 0]
else:
raise ValueError("Unsupported CRU-Net(b) with number of blocks: {}".format(blocks))
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = CRUNetb(
channels=channels,
init_block_channels=init_block_channels,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
group_widths=group_widths,
refresh_steps=refresh_steps,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def crunet56b(**kwargs):
"""
CRU-Net-56(b) model from 'Sharing Residual Units Through Collective Tensor Factorization To Improve Deep Neural
Networks,' https://www.ijcai.org/proceedings/2018/88.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_crunetb(blocks=56, model_name="crunet56b", **kwargs)
def crunet116b(**kwargs):
"""
CRU-Net-116(b) model from 'Sharing Residual Units Through Collective Tensor Factorization To Improve Deep Neural
Networks,' https://www.ijcai.org/proceedings/2018/88.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_crunetb(blocks=116, model_name="crunet116b", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
crunet56b,
crunet116b,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != crunet56b or weight_count == 26139432)
assert (model != crunet116b or weight_count == 44321000)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 20,687 | 33.138614 | 119 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/espnetv2.py | """
ESPNetv2 for ImageNet-1K, implemented in Gluon.
Original paper: 'ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural Network,'
https://arxiv.org/abs/1811.11431.
"""
__all__ = ['ESPNetv2', 'espnetv2_wd2', 'espnetv2_w1', 'espnetv2_w5d4', 'espnetv2_w3d2', 'espnetv2_w2']
import os
import math
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import PReLU2, conv3x3, conv1x1_block, conv3x3_block, DualPathSequential
class PreActivation(HybridBlock):
"""
PreResNet like pure pre-activation block without convolution layer.
Parameters:
----------
in_channels : int
Number of input channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
bn_use_global_stats=False,
**kwargs):
super(PreActivation, self).__init__(**kwargs)
with self.name_scope():
self.bn = nn.BatchNorm(
in_channels=in_channels,
use_global_stats=bn_use_global_stats)
self.activ = PReLU2(in_channels=in_channels)
def hybrid_forward(self, F, x):
x = self.bn(x)
x = self.activ(x)
return x
class ShortcutBlock(HybridBlock):
"""
ESPNetv2 shortcut block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats,
**kwargs):
super(ShortcutBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=in_channels,
bn_use_global_stats=bn_use_global_stats,
activation=(lambda: PReLU2(in_channels)))
self.conv2 = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation=None)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class HierarchicalConcurrent(nn.HybridSequential):
"""
A container for hierarchical concatenation of blocks with parameters.
Parameters:
----------
axis : int, default 1
The axis on which to concatenate the outputs.
"""
def __init__(self,
axis=1,
**kwargs):
super(HierarchicalConcurrent, self).__init__(**kwargs)
self.axis = axis
def hybrid_forward(self, F, x):
out = []
y_prev = None
for block in self._children.values():
y = block(x)
if y_prev is not None:
y = y + y_prev
out.append(y)
y_prev = y
out = F.concat(*out, dim=self.axis)
return out
class ESPBlock(HybridBlock):
"""
ESPNetv2 block (so-called EESP block).
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the branch convolution layers.
dilations : list of int
Dilation values for branches.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
dilations,
bn_use_global_stats,
**kwargs):
super(ESPBlock, self).__init__(**kwargs)
num_branches = len(dilations)
assert (out_channels % num_branches == 0)
self.downsample = (strides != 1)
mid_channels = out_channels // num_branches
with self.name_scope():
self.reduce_conv = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
groups=num_branches,
bn_use_global_stats=bn_use_global_stats,
activation=(lambda: PReLU2(mid_channels)))
self.branches = HierarchicalConcurrent(axis=1, prefix="")
for i in range(num_branches):
self.branches.add(conv3x3(
in_channels=mid_channels,
out_channels=mid_channels,
strides=strides,
padding=dilations[i],
dilation=dilations[i],
groups=mid_channels))
self.merge_conv = conv1x1_block(
in_channels=out_channels,
out_channels=out_channels,
groups=num_branches,
bn_use_global_stats=bn_use_global_stats,
activation=None)
self.preactiv = PreActivation(in_channels=out_channels)
if not self.downsample:
self.activ = PReLU2(out_channels)
def hybrid_forward(self, F, x, x0):
y = self.reduce_conv(x)
y = self.branches(y)
y = self.preactiv(y)
y = self.merge_conv(y)
if not self.downsample:
y = y + x
y = self.activ(y)
return y, x0
class DownsampleBlock(HybridBlock):
"""
ESPNetv2 downsample block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
x0_channels : int
Number of input channels for shortcut.
dilations : list of int
Dilation values for branches in EESP block.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
x0_channels,
dilations,
bn_use_global_stats,
**kwargs):
super(DownsampleBlock, self).__init__(**kwargs)
inc_channels = out_channels - in_channels
with self.name_scope():
self.pool = nn.AvgPool2D(
pool_size=3,
strides=2,
padding=1)
self.eesp = ESPBlock(
in_channels=in_channels,
out_channels=inc_channels,
strides=2,
dilations=dilations,
bn_use_global_stats=bn_use_global_stats)
self.shortcut_block = ShortcutBlock(
in_channels=x0_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
self.activ = PReLU2(out_channels)
def hybrid_forward(self, F, x, x0):
y1 = self.pool(x)
y2, _ = self.eesp(x, None)
x = F.concat(y1, y2, dim=1)
x0 = self.pool(x0)
y3 = self.shortcut_block(x0)
x = x + y3
x = self.activ(x)
return x, x0
class ESPInitBlock(HybridBlock):
"""
ESPNetv2 initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats,
**kwargs):
super(ESPInitBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
strides=2,
bn_use_global_stats=bn_use_global_stats,
activation=(lambda: PReLU2(out_channels)))
self.pool = nn.AvgPool2D(
pool_size=3,
strides=2,
padding=1)
def hybrid_forward(self, F, x, x0):
x = self.conv(x)
x0 = self.pool(x0)
return x, x0
class ESPFinalBlock(HybridBlock):
"""
ESPNetv2 final block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
final_groups : int
Number of groups in the last convolution layer.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
final_groups,
bn_use_global_stats,
**kwargs):
super(ESPFinalBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=in_channels,
groups=in_channels,
bn_use_global_stats=bn_use_global_stats,
activation=(lambda: PReLU2(in_channels)))
self.conv2 = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
groups=final_groups,
bn_use_global_stats=bn_use_global_stats,
activation=(lambda: PReLU2(out_channels)))
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class ESPNetv2(HybridBlock):
"""
ESPNetv2 model from 'ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural Network,'
https://arxiv.org/abs/1811.11431.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final unit.
final_block_groups : int
Number of groups for the final unit.
dilations : list of list of list of int
Dilation values for branches in each unit.
dropout_rate : float, default 0.2
Parameter of Dropout layer. Faction of the input units to drop.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
final_block_groups,
dilations,
dropout_rate=0.2,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000):
super(ESPNetv2, self).__init__()
self.in_size = in_size
self.classes = classes
x0_channels = in_channels
with self.name_scope():
self.features = DualPathSequential(
return_two=False,
first_ordinals=0,
last_ordinals=2,
prefix="")
self.features.add(ESPInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = DualPathSequential(prefix="stage{}_".format(i + 1))
for j, out_channels in enumerate(channels_per_stage):
if j == 0:
unit = DownsampleBlock(
in_channels=in_channels,
out_channels=out_channels,
x0_channels=x0_channels,
dilations=dilations[i][j],
bn_use_global_stats=bn_use_global_stats)
else:
unit = ESPBlock(
in_channels=in_channels,
out_channels=out_channels,
strides=1,
dilations=dilations[i][j],
bn_use_global_stats=bn_use_global_stats)
stage.add(unit)
in_channels = out_channels
self.features.add(stage)
self.features.add(ESPFinalBlock(
in_channels=in_channels,
out_channels=final_block_channels,
final_groups=final_block_groups,
bn_use_global_stats=bn_use_global_stats))
in_channels = final_block_channels
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dropout(rate=dropout_rate))
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x, x)
x = self.output(x)
return x
def get_espnetv2(width_scale,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create ESPNetv2 model with specific parameters.
Parameters:
----------
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
assert (width_scale <= 2.0)
branches = 4
layers = [1, 4, 8, 4]
max_dilation_list = [6, 5, 4, 3, 2]
max_dilations = [[max_dilation_list[i]] + [max_dilation_list[i + 1]] * (li - 1) for (i, li) in enumerate(layers)]
dilations = [[sorted([k + 1 if k < dij else 1 for k in range(branches)]) for dij in di] for di in max_dilations]
base_channels = 32
weighed_base_channels = math.ceil(float(math.floor(base_channels * width_scale)) / branches) * branches
channels_per_layers = [weighed_base_channels * pow(2, i + 1) for i in range(len(layers))]
init_block_channels = base_channels if weighed_base_channels > base_channels else weighed_base_channels
final_block_channels = 1024 if width_scale <= 1.5 else 1280
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = ESPNetv2(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
final_block_groups=branches,
dilations=dilations,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ignore_extra=True,
ctx=ctx)
return net
def espnetv2_wd2(**kwargs):
"""
ESPNetv2 x0.5 model from 'ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural
Network,' https://arxiv.org/abs/1811.11431.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_espnetv2(width_scale=0.5, model_name="espnetv2_wd2", **kwargs)
def espnetv2_w1(**kwargs):
"""
ESPNetv2 x1.0 model from 'ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural
Network,' https://arxiv.org/abs/1811.11431.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_espnetv2(width_scale=1.0, model_name="espnetv2_w1", **kwargs)
def espnetv2_w5d4(**kwargs):
"""
ESPNetv2 x1.25 model from 'ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural
Network,' https://arxiv.org/abs/1811.11431.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_espnetv2(width_scale=1.25, model_name="espnetv2_w5d4", **kwargs)
def espnetv2_w3d2(**kwargs):
"""
ESPNetv2 x1.5 model from 'ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural
Network,' https://arxiv.org/abs/1811.11431.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_espnetv2(width_scale=1.5, model_name="espnetv2_w3d2", **kwargs)
def espnetv2_w2(**kwargs):
"""
ESPNetv2 x2.0 model from 'ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural
Network,' https://arxiv.org/abs/1811.11431.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_espnetv2(width_scale=2.0, model_name="espnetv2_w2", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
espnetv2_wd2,
espnetv2_w1,
espnetv2_w5d4,
espnetv2_w3d2,
espnetv2_w2,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != espnetv2_wd2 or weight_count == 1241092)
assert (model != espnetv2_w1 or weight_count == 1669592)
assert (model != espnetv2_w5d4 or weight_count == 1964832)
assert (model != espnetv2_w3d2 or weight_count == 2314120)
assert (model != espnetv2_w2 or weight_count == 3497144)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 20,193 | 32.600666 | 118 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/shufflenet.py | """
ShuffleNet for ImageNet-1K, implemented in Gluon.
Original paper: 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
"""
__all__ = ['ShuffleNet', 'shufflenet_g1_w1', 'shufflenet_g2_w1', 'shufflenet_g3_w1', 'shufflenet_g4_w1',
'shufflenet_g8_w1', 'shufflenet_g1_w3d4', 'shufflenet_g3_w3d4', 'shufflenet_g1_wd2', 'shufflenet_g3_wd2',
'shufflenet_g1_wd4', 'shufflenet_g3_wd4']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1, conv3x3, depthwise_conv3x3, ChannelShuffle
class ShuffleUnit(HybridBlock):
"""
ShuffleNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
groups : int
Number of groups in convolution layers.
downsample : bool
Whether do downsample.
ignore_group : bool
Whether ignore group value in the first convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
groups,
downsample,
ignore_group,
**kwargs):
super(ShuffleUnit, self).__init__(**kwargs)
self.downsample = downsample
mid_channels = out_channels // 4
if downsample:
out_channels -= in_channels
with self.name_scope():
self.compress_conv1 = conv1x1(
in_channels=in_channels,
out_channels=mid_channels,
groups=(1 if ignore_group else groups))
self.compress_bn1 = nn.BatchNorm(in_channels=mid_channels)
self.c_shuffle = ChannelShuffle(
channels=mid_channels,
groups=groups)
self.dw_conv2 = depthwise_conv3x3(
channels=mid_channels,
strides=(2 if self.downsample else 1))
self.dw_bn2 = nn.BatchNorm(in_channels=mid_channels)
self.expand_conv3 = conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
groups=groups)
self.expand_bn3 = nn.BatchNorm(in_channels=out_channels)
if downsample:
self.avgpool = nn.AvgPool2D(
pool_size=3,
strides=2,
padding=1)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
identity = x
x = self.compress_conv1(x)
x = self.compress_bn1(x)
x = self.activ(x)
x = self.c_shuffle(x)
x = self.dw_conv2(x)
x = self.dw_bn2(x)
x = self.expand_conv3(x)
x = self.expand_bn3(x)
if self.downsample:
identity = self.avgpool(identity)
x = F.concat(x, identity, dim=1)
else:
x = x + identity
x = self.activ(x)
return x
class ShuffleInitBlock(HybridBlock):
"""
ShuffleNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels,
**kwargs):
super(ShuffleInitBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv = conv3x3(
in_channels=in_channels,
out_channels=out_channels,
strides=2)
self.bn = nn.BatchNorm(in_channels=out_channels)
self.activ = nn.Activation("relu")
self.pool = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=1)
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.bn(x)
x = self.activ(x)
x = self.pool(x)
return x
class ShuffleNet(HybridBlock):
"""
ShuffleNet model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
groups : int
Number of groups in convolution layers.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
groups,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(ShuffleNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(ShuffleInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
downsample = (j == 0)
ignore_group = (i == 0) and (j == 0)
stage.add(ShuffleUnit(
in_channels=in_channels,
out_channels=out_channels,
groups=groups,
downsample=downsample,
ignore_group=ignore_group))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_shufflenet(groups,
width_scale,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create ShuffleNet model with specific parameters.
Parameters:
----------
groups : int
Number of groups in convolution layers.
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
init_block_channels = 24
layers = [4, 8, 4]
if groups == 1:
channels_per_layers = [144, 288, 576]
elif groups == 2:
channels_per_layers = [200, 400, 800]
elif groups == 3:
channels_per_layers = [240, 480, 960]
elif groups == 4:
channels_per_layers = [272, 544, 1088]
elif groups == 8:
channels_per_layers = [384, 768, 1536]
else:
raise ValueError("The {} of groups is not supported".format(groups))
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) for cij in ci] for ci in channels]
init_block_channels = int(init_block_channels * width_scale)
net = ShuffleNet(
channels=channels,
init_block_channels=init_block_channels,
groups=groups,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def shufflenet_g1_w1(**kwargs):
"""
ShuffleNet 1x (g=1) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=1, width_scale=1.0, model_name="shufflenet_g1_w1", **kwargs)
def shufflenet_g2_w1(**kwargs):
"""
ShuffleNet 1x (g=2) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=2, width_scale=1.0, model_name="shufflenet_g2_w1", **kwargs)
def shufflenet_g3_w1(**kwargs):
"""
ShuffleNet 1x (g=3) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=3, width_scale=1.0, model_name="shufflenet_g3_w1", **kwargs)
def shufflenet_g4_w1(**kwargs):
"""
ShuffleNet 1x (g=4) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=4, width_scale=1.0, model_name="shufflenet_g4_w1", **kwargs)
def shufflenet_g8_w1(**kwargs):
"""
ShuffleNet 1x (g=8) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=8, width_scale=1.0, model_name="shufflenet_g8_w1", **kwargs)
def shufflenet_g1_w3d4(**kwargs):
"""
ShuffleNet 0.75x (g=1) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile
Devices,' https://arxiv.org/abs/1707.01083.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=1, width_scale=0.75, model_name="shufflenet_g1_w3d4", **kwargs)
def shufflenet_g3_w3d4(**kwargs):
"""
ShuffleNet 0.75x (g=3) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile
Devices,' https://arxiv.org/abs/1707.01083.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=3, width_scale=0.75, model_name="shufflenet_g3_w3d4", **kwargs)
def shufflenet_g1_wd2(**kwargs):
"""
ShuffleNet 0.5x (g=1) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile
Devices,' https://arxiv.org/abs/1707.01083.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=1, width_scale=0.5, model_name="shufflenet_g1_wd2", **kwargs)
def shufflenet_g3_wd2(**kwargs):
"""
ShuffleNet 0.5x (g=3) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile
Devices,' https://arxiv.org/abs/1707.01083.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=3, width_scale=0.5, model_name="shufflenet_g3_wd2", **kwargs)
def shufflenet_g1_wd4(**kwargs):
"""
ShuffleNet 0.25x (g=1) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile
Devices,' https://arxiv.org/abs/1707.01083.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=1, width_scale=0.25, model_name="shufflenet_g1_wd4", **kwargs)
def shufflenet_g3_wd4(**kwargs):
"""
ShuffleNet 0.25x (g=3) model from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile
Devices,' https://arxiv.org/abs/1707.01083.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenet(groups=3, width_scale=0.25, model_name="shufflenet_g3_wd4", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
shufflenet_g1_w1,
shufflenet_g2_w1,
shufflenet_g3_w1,
shufflenet_g4_w1,
shufflenet_g8_w1,
shufflenet_g1_w3d4,
shufflenet_g3_w3d4,
shufflenet_g1_wd2,
shufflenet_g3_wd2,
shufflenet_g1_wd4,
shufflenet_g3_wd4,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != shufflenet_g1_w1 or weight_count == 1531936)
assert (model != shufflenet_g2_w1 or weight_count == 1733848)
assert (model != shufflenet_g3_w1 or weight_count == 1865728)
assert (model != shufflenet_g4_w1 or weight_count == 1968344)
assert (model != shufflenet_g8_w1 or weight_count == 2434768)
assert (model != shufflenet_g1_w3d4 or weight_count == 975214)
assert (model != shufflenet_g3_w3d4 or weight_count == 1238266)
assert (model != shufflenet_g1_wd2 or weight_count == 534484)
assert (model != shufflenet_g3_wd2 or weight_count == 718324)
assert (model != shufflenet_g1_wd4 or weight_count == 209746)
assert (model != shufflenet_g3_wd4 or weight_count == 305902)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 17,247 | 33.222222 | 120 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/bamresnet.py | """
BAM-ResNet for ImageNet-1K, implemented in Gluon.
Original paper: 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.
"""
__all__ = ['BamResNet', 'bam_resnet18', 'bam_resnet34', 'bam_resnet50', 'bam_resnet101', 'bam_resnet152']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1, conv1x1_block, conv3x3_block
from .resnet import ResInitBlock, ResUnit
class DenseBlock(HybridBlock):
"""
Standard dense block with Batch normalization and ReLU activation.
Parameters:
----------
in_channels : int
Number of input features.
out_channels : int
Number of output features.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats,
**kwargs):
super(DenseBlock, self).__init__(**kwargs)
with self.name_scope():
self.fc = nn.Dense(
units=out_channels,
in_units=in_channels)
self.bn = nn.BatchNorm(
in_channels=out_channels,
use_global_stats=bn_use_global_stats)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
x = self.fc(x)
x = self.bn(x)
x = self.activ(x)
return x
class ChannelGate(HybridBlock):
"""
BAM channel gate block.
Parameters:
----------
channels : int
Number of input/output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
reduction_ratio : int, default 16
Channel reduction ratio.
num_layers : int, default 1
Number of dense blocks.
"""
def __init__(self,
channels,
bn_use_global_stats,
reduction_ratio=16,
num_layers=1,
**kwargs):
super(ChannelGate, self).__init__(**kwargs)
mid_channels = channels // reduction_ratio
with self.name_scope():
self.pool = nn.GlobalAvgPool2D()
self.flatten = nn.Flatten()
self.init_fc = DenseBlock(
in_channels=channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats)
self.main_fcs = nn.HybridSequential(prefix="")
for i in range(num_layers - 1):
self.main_fcs.add(DenseBlock(
in_channels=mid_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats))
self.final_fc = nn.Dense(
units=channels,
in_units=mid_channels)
def hybrid_forward(self, F, x):
input = x
x = self.pool(x)
x = self.flatten(x)
x = self.init_fc(x)
x = self.main_fcs(x)
x = self.final_fc(x)
x = x.expand_dims(2).expand_dims(3).broadcast_like(input)
return x
class SpatialGate(HybridBlock):
"""
BAM spatial gate block.
Parameters:
----------
channels : int
Number of input/output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
reduction_ratio : int, default 16
Channel reduction ratio.
num_dil_convs : int, default 2
Number of dilated convolutions.
dilation : int, default 4
Dilation/padding value for corresponding convolutions.
"""
def __init__(self,
channels,
bn_use_global_stats,
reduction_ratio=16,
num_dil_convs=2,
dilation=4,
**kwargs):
super(SpatialGate, self).__init__(**kwargs)
mid_channels = channels // reduction_ratio
with self.name_scope():
self.init_conv = conv1x1_block(
in_channels=channels,
out_channels=mid_channels,
strides=1,
use_bias=True,
bn_use_global_stats=bn_use_global_stats)
self.dil_convs = nn.HybridSequential(prefix="")
for i in range(num_dil_convs):
self.dil_convs.add(conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
strides=1,
padding=dilation,
dilation=dilation,
use_bias=True,
bn_use_global_stats=bn_use_global_stats))
self.final_conv = conv1x1(
in_channels=mid_channels,
out_channels=1,
strides=1,
use_bias=True)
def hybrid_forward(self, F, x):
input = x
x = self.init_conv(x)
x = self.dil_convs(x)
x = self.final_conv(x)
x = x.broadcast_like(input)
return x
class BamBlock(HybridBlock):
"""
BAM attention block for BAM-ResNet.
Parameters:
----------
channels : int
Number of input/output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
channels,
bn_use_global_stats,
**kwargs):
super(BamBlock, self).__init__(**kwargs)
with self.name_scope():
self.ch_att = ChannelGate(
channels=channels,
bn_use_global_stats=bn_use_global_stats)
self.sp_att = SpatialGate(
channels=channels,
bn_use_global_stats=bn_use_global_stats)
self.sigmoid = nn.Activation("sigmoid")
def hybrid_forward(self, F, x):
att = 1 + self.sigmoid(self.ch_att(x) * self.sp_att(x))
x = x * att
return x
class BamResUnit(HybridBlock):
"""
BAM-ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats,
bottleneck,
**kwargs):
super(BamResUnit, self).__init__(**kwargs)
self.use_bam = (strides != 1)
with self.name_scope():
if self.use_bam:
self.bam = BamBlock(
channels=in_channels,
bn_use_global_stats=bn_use_global_stats)
self.res_unit = ResUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bottleneck=bottleneck,
conv1_stride=False)
def hybrid_forward(self, F, x):
if self.use_bam:
x = self.bam(x)
x = self.res_unit(x)
return x
class BamResNet(HybridBlock):
"""
BAM-ResNet model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(BamResNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
stage.add(BamResUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bottleneck=bottleneck))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_resnet(blocks,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create BAM-ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
use_se : bool
Whether to use SE block.
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if blocks == 18:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
else:
raise ValueError("Unsupported BAM-ResNet with number of blocks: {}".format(blocks))
init_block_channels = 64
if blocks < 50:
channels_per_layers = [64, 128, 256, 512]
bottleneck = False
else:
channels_per_layers = [256, 512, 1024, 2048]
bottleneck = True
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = BamResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def bam_resnet18(**kwargs):
"""
BAM-ResNet-18 model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=18, model_name="bam_resnet18", **kwargs)
def bam_resnet34(**kwargs):
"""
BAM-ResNet-34 model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=34, model_name="bam_resnet34", **kwargs)
def bam_resnet50(**kwargs):
"""
BAM-ResNet-50 model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=50, model_name="bam_resnet50", **kwargs)
def bam_resnet101(**kwargs):
"""
BAM-ResNet-101 model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=101, model_name="bam_resnet101", **kwargs)
def bam_resnet152(**kwargs):
"""
BAM-ResNet-152 model from 'BAM: Bottleneck Attention Module,' https://arxiv.org/abs/1807.06514.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet(blocks=152, model_name="bam_resnet152", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
bam_resnet18,
bam_resnet34,
bam_resnet50,
bam_resnet101,
bam_resnet152,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != bam_resnet18 or weight_count == 11712503)
assert (model != bam_resnet34 or weight_count == 21820663)
assert (model != bam_resnet50 or weight_count == 25915099)
assert (model != bam_resnet101 or weight_count == 44907227)
assert (model != bam_resnet152 or weight_count == 60550875)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 16,255 | 31.253968 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/resattnet.py | """
ResAttNet for ImageNet-1K, implemented in Gluon.
Original paper: 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
"""
__all__ = ['ResAttNet', 'resattnet56', 'resattnet92', 'resattnet128', 'resattnet164', 'resattnet200', 'resattnet236',
'resattnet452']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1, conv7x7_block, pre_conv1x1_block, pre_conv3x3_block, Hourglass
class PreResBottleneck(HybridBlock):
"""
PreResNet bottleneck block for residual path in PreResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats,
**kwargs):
super(PreResBottleneck, self).__init__(**kwargs)
mid_channels = out_channels // 4
with self.name_scope():
self.conv1 = pre_conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats,
return_preact=True)
self.conv2 = pre_conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats,
strides=strides)
self.conv3 = pre_conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x, x_pre_activ = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x, x_pre_activ
class ResBlock(HybridBlock):
"""
Residual block with pre-activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides=1,
bn_use_global_stats=False,
**kwargs):
super(ResBlock, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
self.body = PreResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats)
if self.resize_identity:
self.identity_conv = conv1x1(
in_channels=in_channels,
out_channels=out_channels,
strides=strides)
def hybrid_forward(self, F, x):
identity = x
x, x_pre_activ = self.body(x)
if self.resize_identity:
identity = self.identity_conv(x_pre_activ)
x = x + identity
return x
class InterpolationBlock(HybridBlock):
"""
Interpolation block.
Parameters:
----------
size : tuple of 2 int
Spatial size of the output tensor for the bilinear upsampling operation.
"""
def __init__(self,
size,
**kwargs):
super(InterpolationBlock, self).__init__(**kwargs)
self.size = size
def hybrid_forward(self, F, x):
return F.contrib.BilinearResize2D(x, height=self.size[0], width=self.size[1])
class DoubleSkipBlock(HybridBlock):
"""
Double skip connection block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats,
**kwargs):
super(DoubleSkipBlock, self).__init__(**kwargs)
with self.name_scope():
self.skip1 = ResBlock(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = x + self.skip1(x)
return x
class ResBlockSequence(HybridBlock):
"""
Sequence of residual blocks with pre-activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
length : int
Length of sequence.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
length,
bn_use_global_stats,
**kwargs):
super(ResBlockSequence, self).__init__(**kwargs)
with self.name_scope():
self.blocks = nn.HybridSequential(prefix="")
for i in range(length):
self.blocks.add(ResBlock(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats))
def hybrid_forward(self, F, x):
x = self.blocks(x)
return x
class DownAttBlock(HybridBlock):
"""
Down sub-block for hourglass of attention block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
length : int
Length of residual blocks list.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
length,
bn_use_global_stats,
**kwargs):
super(DownAttBlock, self).__init__(**kwargs)
with self.name_scope():
self.pool = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=1)
self.res_blocks = ResBlockSequence(
in_channels=in_channels,
out_channels=out_channels,
length=length,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.pool(x)
x = self.res_blocks(x)
return x
class UpAttBlock(HybridBlock):
"""
Up sub-block for hourglass of attention block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
length : int
Length of residual blocks list.
size : tuple of 2 int
Spatial size of the output tensor for the bilinear upsampling operation.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
length,
size,
bn_use_global_stats,
**kwargs):
super(UpAttBlock, self).__init__(**kwargs)
with self.name_scope():
self.res_blocks = ResBlockSequence(
in_channels=in_channels,
out_channels=out_channels,
length=length,
bn_use_global_stats=bn_use_global_stats)
self.upsample = InterpolationBlock(size)
def hybrid_forward(self, F, x):
x = self.res_blocks(x)
x = self.upsample(x)
return x
class MiddleAttBlock(HybridBlock):
"""
Middle sub-block for attention block.
Parameters:
----------
channels : int
Number of input/output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
channels,
bn_use_global_stats,
**kwargs):
super(MiddleAttBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = pre_conv1x1_block(
in_channels=channels,
out_channels=channels,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = pre_conv1x1_block(
in_channels=channels,
out_channels=channels,
bn_use_global_stats=bn_use_global_stats)
self.sigmoid = nn.Activation("sigmoid")
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.sigmoid(x)
return x
class AttBlock(HybridBlock):
"""
Attention block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
hourglass_depth : int
Depth of hourglass block.
att_scales : list of int
Attention block specific scales.
in_size : tuple of 2 int
Spatial size of the input tensor for the bilinear upsampling operation.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
hourglass_depth,
att_scales,
in_size,
bn_use_global_stats,
**kwargs):
super(AttBlock, self).__init__(**kwargs)
assert (len(att_scales) == 3)
scale_factor = 2
scale_p, scale_t, scale_r = att_scales
with self.name_scope():
self.init_blocks = ResBlockSequence(
in_channels=in_channels,
out_channels=out_channels,
length=scale_p,
bn_use_global_stats=bn_use_global_stats)
down_seq = nn.HybridSequential(prefix="")
up_seq = nn.HybridSequential(prefix="")
skip_seq = nn.HybridSequential(prefix="")
for i in range(hourglass_depth):
down_seq.add(DownAttBlock(
in_channels=in_channels,
out_channels=out_channels,
length=scale_r,
bn_use_global_stats=bn_use_global_stats))
up_seq.add(UpAttBlock(
in_channels=in_channels,
out_channels=out_channels,
length=scale_r,
size=in_size,
bn_use_global_stats=bn_use_global_stats))
in_size = tuple([x // scale_factor for x in in_size])
if i == 0:
skip_seq.add(ResBlockSequence(
in_channels=in_channels,
out_channels=out_channels,
length=scale_t,
bn_use_global_stats=bn_use_global_stats))
else:
skip_seq.add(DoubleSkipBlock(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats))
self.hg = Hourglass(
down_seq=down_seq,
up_seq=up_seq,
skip_seq=skip_seq,
return_first_skip=True)
self.middle_block = MiddleAttBlock(
channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
self.final_block = ResBlock(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.init_blocks(x)
x, y = self.hg(x)
x = self.middle_block(x)
x = (1 + x) * y
x = self.final_block(x)
return x
class ResAttInitBlock(HybridBlock):
"""
ResAttNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats,
**kwargs):
super(ResAttInitBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv = conv7x7_block(
in_channels=in_channels,
out_channels=out_channels,
strides=2,
bn_use_global_stats=bn_use_global_stats)
self.pool = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=1)
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.pool(x)
return x
class PreActivation(HybridBlock):
"""
Pre-activation block without convolution layer. It's used by itself as the final block in PreResNet.
Parameters:
----------
in_channels : int
Number of input channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
bn_use_global_stats,
**kwargs):
super(PreActivation, self).__init__(**kwargs)
with self.name_scope():
self.bn = nn.BatchNorm(
in_channels=in_channels,
use_global_stats=bn_use_global_stats)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
x = self.bn(x)
x = self.activ(x)
return x
class ResAttNet(HybridBlock):
"""
ResAttNet model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
attentions : list of list of int
Whether to use a attention unit or residual one.
att_scales : list of int
Attention block specific scales.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
attentions,
att_scales,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(ResAttNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(ResAttInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
in_size = tuple([x // 4 for x in in_size])
for i, channels_per_stage in enumerate(channels):
hourglass_depth = len(channels) - 1 - i
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
if attentions[i][j]:
stage.add(AttBlock(
in_channels=in_channels,
out_channels=out_channels,
hourglass_depth=hourglass_depth,
att_scales=att_scales,
in_size=in_size,
bn_use_global_stats=bn_use_global_stats))
else:
stage.add(ResBlock(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
in_size = tuple([x // strides for x in in_size])
self.features.add(stage)
self.features.add(PreActivation(
in_channels=in_channels,
bn_use_global_stats=bn_use_global_stats))
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_resattnet(blocks,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create ResAttNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if blocks == 56:
att_layers = [1, 1, 1]
att_scales = [1, 2, 1]
elif blocks == 92:
att_layers = [1, 2, 3]
att_scales = [1, 2, 1]
elif blocks == 128:
att_layers = [2, 3, 4]
att_scales = [1, 2, 1]
elif blocks == 164:
att_layers = [3, 4, 5]
att_scales = [1, 2, 1]
elif blocks == 200:
att_layers = [4, 5, 6]
att_scales = [1, 2, 1]
elif blocks == 236:
att_layers = [5, 6, 7]
att_scales = [1, 2, 1]
elif blocks == 452:
att_layers = [5, 6, 7]
att_scales = [2, 4, 3]
else:
raise ValueError("Unsupported ResAttNet with number of blocks: {}".format(blocks))
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
layers = att_layers + [2]
channels = [[ci] * (li + 1) for (ci, li) in zip(channels_per_layers, layers)]
attentions = [[0] + [1] * li for li in att_layers] + [[0] * 3]
net = ResAttNet(
channels=channels,
init_block_channels=init_block_channels,
attentions=attentions,
att_scales=att_scales,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def resattnet56(**kwargs):
"""
ResAttNet-56 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resattnet(blocks=56, model_name="resattnet56", **kwargs)
def resattnet92(**kwargs):
"""
ResAttNet-92 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resattnet(blocks=92, model_name="resattnet92", **kwargs)
def resattnet128(**kwargs):
"""
ResAttNet-128 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resattnet(blocks=128, model_name="resattnet128", **kwargs)
def resattnet164(**kwargs):
"""
ResAttNet-164 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resattnet(blocks=164, model_name="resattnet164", **kwargs)
def resattnet200(**kwargs):
"""
ResAttNet-200 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resattnet(blocks=200, model_name="resattnet200", **kwargs)
def resattnet236(**kwargs):
"""
ResAttNet-236 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resattnet(blocks=236, model_name="resattnet236", **kwargs)
def resattnet452(**kwargs):
"""
ResAttNet-452 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resattnet(blocks=452, model_name="resattnet452", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
resattnet56,
resattnet92,
resattnet128,
resattnet164,
resattnet200,
resattnet236,
resattnet452,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != resattnet56 or weight_count == 31810728)
assert (model != resattnet92 or weight_count == 52466344)
assert (model != resattnet128 or weight_count == 65294504)
assert (model != resattnet164 or weight_count == 78122664)
assert (model != resattnet200 or weight_count == 90950824)
assert (model != resattnet236 or weight_count == 103778984)
assert (model != resattnet452 or weight_count == 182285224)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 25,649 | 32.096774 | 117 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/centernet.py | """
CenterNet for ImageNet-1K, implemented in Gluon.
Original paper: 'Objects as Points,' https://arxiv.org/abs/1904.07850.
"""
__all__ = ['CenterNet', 'centernet_resnet18_voc', 'centernet_resnet18_coco', 'centernet_resnet50b_voc',
'centernet_resnet50b_coco', 'centernet_resnet101b_voc', 'centernet_resnet101b_coco',
'CenterNetHeatmapMaxDet']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from mxnet.gluon.contrib.nn import HybridConcurrent
from .common import conv1x1, conv3x3_block, DeconvBlock
from .resnet import resnet18, resnet50b, resnet101b
class CenterNetDecoderUnit(HybridBlock):
"""
CenterNet decoder unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats=False,
**kwargs):
super(CenterNetDecoderUnit, self).__init__(**kwargs)
with self.name_scope():
self.conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
use_bias=True,
bn_use_global_stats=bn_use_global_stats)
self.deconv = DeconvBlock(
in_channels=out_channels,
out_channels=out_channels,
kernel_size=4,
strides=2,
padding=1,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.deconv(x)
return x
class CenterNetHeadBlock(HybridBlock):
"""
CenterNet simple head block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels,
**kwargs):
super(CenterNetHeadBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=in_channels,
use_bias=True,
use_bn=False)
self.conv2 = conv1x1(
in_channels=in_channels,
out_channels=out_channels,
use_bias=True)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class CenterNetHeatmapBlock(HybridBlock):
"""
CenterNet heatmap block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
do_nms : bool
Whether do NMS (or simply clip for training otherwise).
"""
def __init__(self,
in_channels,
out_channels,
do_nms,
**kwargs):
super(CenterNetHeatmapBlock, self).__init__(**kwargs)
self.do_nms = do_nms
with self.name_scope():
self.head = CenterNetHeadBlock(
in_channels=in_channels,
out_channels=out_channels)
self.sigmoid = nn.Activation("sigmoid")
if self.do_nms:
self.pool = nn.MaxPool2D(
pool_size=3,
strides=1,
padding=1)
def hybrid_forward(self, F, x):
x = self.head(x)
x = self.sigmoid(x)
if self.do_nms:
y = self.pool(x)
x = x * F.broadcast_equal(y, x)
else:
eps = 1e-4
x = x.clip(a_min=eps, a_max=(1.0 - eps))
return x
class CenterNetHeatmapMaxDet(HybridBlock):
"""
CenterNet decoder for heads (heatmap, wh, reg).
Parameters:
----------
topk : int, default 40
Keep only `topk` detections.
scale : int, default is 4
Downsampling scale factor.
max_batch : int, default is 256
Maximal batch size.
"""
def __init__(self,
topk=40,
scale=4,
max_batch=256,
**kwargs):
super(CenterNetHeatmapMaxDet, self).__init__(**kwargs)
self.topk = topk
self.scale = scale
self.max_batch = max_batch
def hybrid_forward(self, F, x):
heatmap = x.slice_axis(axis=1, begin=0, end=-4)
wh = x.slice_axis(axis=1, begin=-4, end=-2)
reg = x.slice_axis(axis=1, begin=-2, end=None)
_, _, out_h, out_w = heatmap.shape_array().split(num_outputs=4, axis=0)
scores, indices = heatmap.reshape((0, -1)).topk(k=self.topk, ret_typ="both")
indices = indices.astype(dtype="int64")
topk_classes = F.broadcast_div(indices, (out_h * out_w)).astype(dtype="float32")
topk_indices = F.broadcast_mod(indices, (out_h * out_w))
topk_ys = F.broadcast_div(topk_indices, out_w).astype(dtype="float32")
topk_xs = F.broadcast_mod(topk_indices, out_w).astype(dtype="float32")
center = reg.transpose((0, 2, 3, 1)).reshape((0, -1, 2))
wh = wh.transpose((0, 2, 3, 1)).reshape((0, -1, 2))
batch_indices = F.arange(self.max_batch).slice_like(center, axes=0).expand_dims(-1).repeat(self.topk, 1).\
astype(dtype="int64")
reg_xs_indices = F.zeros_like(batch_indices, dtype="int64")
reg_ys_indices = F.ones_like(batch_indices, dtype="int64")
reg_xs = F.concat(batch_indices, topk_indices, reg_xs_indices, dim=0).reshape((3, -1))
reg_ys = F.concat(batch_indices, topk_indices, reg_ys_indices, dim=0).reshape((3, -1))
xs = F.gather_nd(center, reg_xs).reshape((-1, self.topk))
ys = F.gather_nd(center, reg_ys).reshape((-1, self.topk))
topk_xs = topk_xs + xs
topk_ys = topk_ys + ys
w = F.gather_nd(wh, reg_xs).reshape((-1, self.topk))
h = F.gather_nd(wh, reg_ys).reshape((-1, self.topk))
half_w = 0.5 * w
half_h = 0.5 * h
bboxes = F.stack(topk_xs - half_w, topk_ys - half_h, topk_xs + half_w, topk_ys + half_h, axis=-1)
bboxes = bboxes * self.scale
topk_classes = topk_classes.expand_dims(axis=-1)
scores = scores.expand_dims(axis=-1)
result = F.concat(bboxes, topk_classes, scores, dim=-1)
return result
def __repr__(self):
s = "{name}(topk={topk}, scale={scale})"
return s.format(
name=self.__class__.__name__,
topk=self.topk,
scale=self.scale)
def calc_flops(self, x):
assert (x.shape[0] == 1)
num_flops = 10 * x.size
num_macs = 0
return num_flops, num_macs
class CenterNet(HybridBlock):
"""
CenterNet model from 'Objects as Points,' https://arxiv.org/abs/1904.07850.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
backbone_out_channels : int
Number of output channels for the backbone.
channels : list of int
Number of output channels for each decoder unit.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
return_heatmap : bool, default False
Whether to return only heatmap.
topk : int, default 40
Keep only `topk` detections.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (512, 512)
Spatial size of the expected input image.
classes : int, default 80
Number of classification classes.
"""
def __init__(self,
backbone,
backbone_out_channels,
channels,
bn_use_global_stats=False,
return_heatmap=False,
topk=40,
in_channels=3,
in_size=(512, 512),
classes=80,
**kwargs):
super(CenterNet, self).__init__(**kwargs)
self.in_size = in_size
self.in_channels = in_channels
self.return_heatmap = return_heatmap
with self.name_scope():
self.backbone = backbone
self.decoder = nn.HybridSequential(prefix="")
in_channels = backbone_out_channels
for out_channels in channels:
self.decoder.add(CenterNetDecoderUnit(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
heads = HybridConcurrent(axis=1, prefix="")
heads.add(CenterNetHeatmapBlock(
in_channels=in_channels,
out_channels=classes,
do_nms=(not self.return_heatmap)))
heads.add(CenterNetHeadBlock(
in_channels=in_channels,
out_channels=2))
heads.add(CenterNetHeadBlock(
in_channels=in_channels,
out_channels=2))
self.decoder.add(heads)
if not self.return_heatmap:
self.heatmap_max_det = CenterNetHeatmapMaxDet(
topk=topk,
scale=4)
def hybrid_forward(self, F, x):
x = self.backbone(x)
x = self.decoder(x)
if not self.return_heatmap:
x = self.heatmap_max_det(x)
return x
def get_centernet(backbone,
backbone_out_channels,
classes,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create CenterNet model with specific parameters.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
backbone_out_channels : int
Number of output channels for the backbone.
classes : int
Number of classes.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
Returns:
-------
HybridBlock
A network.
"""
channels = [256, 128, 64]
net = CenterNet(
backbone=backbone,
backbone_out_channels=backbone_out_channels,
channels=channels,
classes=classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def centernet_resnet18_voc(pretrained_backbone=False, classes=20, **kwargs):
"""
CenterNet model on the base of ResNet-101b for VOC Detection from 'Objects as Points,'
https://arxiv.org/abs/1904.07850.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 20
Number of classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnet18(pretrained=pretrained_backbone).features[:-1]
return get_centernet(backbone=backbone, backbone_out_channels=512, classes=classes,
model_name="centernet_resnet18_voc", **kwargs)
def centernet_resnet18_coco(pretrained_backbone=False, classes=80, **kwargs):
"""
CenterNet model on the base of ResNet-101b for COCO Detection from 'Objects as Points,'
https://arxiv.org/abs/1904.07850.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 80
Number of classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnet18(pretrained=pretrained_backbone).features[:-1]
return get_centernet(backbone=backbone, backbone_out_channels=512, classes=classes,
model_name="centernet_resnet18_coco", **kwargs)
def centernet_resnet50b_voc(pretrained_backbone=False, classes=20, **kwargs):
"""
CenterNet model on the base of ResNet-101b for VOC Detection from 'Objects as Points,'
https://arxiv.org/abs/1904.07850.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 20
Number of classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnet50b(pretrained=pretrained_backbone).features[:-1]
return get_centernet(backbone=backbone, backbone_out_channels=2048, classes=classes,
model_name="centernet_resnet50b_voc", **kwargs)
def centernet_resnet50b_coco(pretrained_backbone=False, classes=80, **kwargs):
"""
CenterNet model on the base of ResNet-101b for COCO Detection from 'Objects as Points,'
https://arxiv.org/abs/1904.07850.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 80
Number of classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnet50b(pretrained=pretrained_backbone).features[:-1]
return get_centernet(backbone=backbone, backbone_out_channels=2048, classes=classes,
model_name="centernet_resnet50b_coco", **kwargs)
def centernet_resnet101b_voc(pretrained_backbone=False, classes=20, **kwargs):
"""
CenterNet model on the base of ResNet-101b for VOC Detection from 'Objects as Points,'
https://arxiv.org/abs/1904.07850.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 20
Number of classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnet101b(pretrained=pretrained_backbone).features[:-1]
return get_centernet(backbone=backbone, backbone_out_channels=2048, classes=classes,
model_name="centernet_resnet101b_voc", **kwargs)
def centernet_resnet101b_coco(pretrained_backbone=False, classes=80, **kwargs):
"""
CenterNet model on the base of ResNet-101b for COCO Detection from 'Objects as Points,'
https://arxiv.org/abs/1904.07850.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 80
Number of classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnet101b(pretrained=pretrained_backbone).features[:-1]
return get_centernet(backbone=backbone, backbone_out_channels=2048, classes=classes,
model_name="centernet_resnet101b_coco", **kwargs)
def _test():
import numpy as np
import mxnet as mx
in_size = (512, 512)
topk = 40
return_heatmap = False
pretrained = False
models = [
(centernet_resnet18_voc, 20),
(centernet_resnet18_coco, 80),
(centernet_resnet50b_voc, 20),
(centernet_resnet50b_coco, 80),
(centernet_resnet101b_voc, 20),
(centernet_resnet101b_coco, 80),
]
for model, classes in models:
net = model(pretrained=pretrained, topk=topk, in_size=in_size, return_heatmap=return_heatmap)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != centernet_resnet18_voc or weight_count == 14215640)
assert (model != centernet_resnet18_coco or weight_count == 14219540)
assert (model != centernet_resnet50b_voc or weight_count == 30086104)
assert (model != centernet_resnet50b_coco or weight_count == 30090004)
assert (model != centernet_resnet101b_voc or weight_count == 49078232)
assert (model != centernet_resnet101b_coco or weight_count == 49082132)
batch = 14
x = mx.nd.random.normal(shape=(batch, 3, in_size[0], in_size[1]), ctx=ctx)
y = net(x)
assert (y.shape[0] == batch)
if return_heatmap:
assert (y.shape[1] == classes + 4) and (y.shape[2] == x.shape[2] // 4) and (y.shape[3] == x.shape[3] // 4)
else:
assert (y.shape[1] == topk) and (y.shape[2] == 6)
if __name__ == "__main__":
_test()
| 18,867 | 34.466165 | 118 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/xdensenet_cifar.py | """
X-DenseNet for CIFAR/SVHN, implemented in Gluon.
Original paper: 'Deep Expander Networks: Efficient Deep Networks from Graph Theory,'
https://arxiv.org/abs/1711.08757.
"""
__all__ = ['CIFARXDenseNet', 'xdensenet40_2_k24_bc_cifar10', 'xdensenet40_2_k24_bc_cifar100',
'xdensenet40_2_k24_bc_svhn', 'xdensenet40_2_k36_bc_cifar10', 'xdensenet40_2_k36_bc_cifar100',
'xdensenet40_2_k36_bc_svhn']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv3x3
from .preresnet import PreResActivation
from .densenet import TransitionBlock
from .xdensenet import pre_xconv3x3_block, XDenseUnit
class XDenseSimpleUnit(HybridBlock):
"""
X-DenseNet simple unit for CIFAR.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
expand_ratio : int
Ratio of expansion.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats,
dropout_rate,
expand_ratio,
**kwargs):
super(XDenseSimpleUnit, self).__init__(**kwargs)
self.use_dropout = (dropout_rate != 0.0)
inc_channels = out_channels - in_channels
with self.name_scope():
self.conv = pre_xconv3x3_block(
in_channels=in_channels,
out_channels=inc_channels,
bn_use_global_stats=bn_use_global_stats,
expand_ratio=expand_ratio)
if self.use_dropout:
self.dropout = nn.Dropout(rate=dropout_rate)
def hybrid_forward(self, F, x):
identity = x
x = self.conv(x)
if self.use_dropout:
x = self.dropout(x)
x = F.concat(identity, x, dim=1)
return x
class CIFARXDenseNet(HybridBlock):
"""
X-DenseNet model for CIFAR from 'Deep Expander Networks: Efficient Deep Networks from Graph Theory,'
https://arxiv.org/abs/1711.08757.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
dropout_rate : float, default 0.0
Parameter of Dropout layer. Faction of the input units to drop.
expand_ratio : int, default 2
Ratio of expansion.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
bn_use_global_stats=False,
dropout_rate=0.0,
expand_ratio=2,
in_channels=3,
in_size=(32, 32),
classes=10,
**kwargs):
super(CIFARXDenseNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
unit_class = XDenseUnit if bottleneck else XDenseSimpleUnit
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(conv3x3(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
if i != 0:
stage.add(TransitionBlock(
in_channels=in_channels,
out_channels=(in_channels // 2),
bn_use_global_stats=bn_use_global_stats))
in_channels = in_channels // 2
for j, out_channels in enumerate(channels_per_stage):
stage.add(unit_class(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
dropout_rate=dropout_rate,
expand_ratio=expand_ratio))
in_channels = out_channels
self.features.add(stage)
self.features.add(PreResActivation(
in_channels=in_channels,
bn_use_global_stats=bn_use_global_stats))
self.features.add(nn.AvgPool2D(
pool_size=8,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_xdensenet_cifar(classes,
blocks,
growth_rate,
bottleneck,
expand_ratio=2,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create X-DenseNet model for CIFAR with specific parameters.
Parameters:
----------
classes : int
Number of classification classes.
blocks : int
Number of blocks.
growth_rate : int
Growth rate.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
expand_ratio : int, default 2
Ratio of expansion.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
assert (classes in [10, 100])
if bottleneck:
assert ((blocks - 4) % 6 == 0)
layers = [(blocks - 4) // 6] * 3
else:
assert ((blocks - 4) % 3 == 0)
layers = [(blocks - 4) // 3] * 3
init_block_channels = 2 * growth_rate
from functools import reduce
channels = reduce(
lambda xi, yi: xi + [reduce(
lambda xj, yj: xj + [xj[-1] + yj],
[growth_rate] * yi,
[xi[-1][-1] // 2])[1:]],
layers,
[[init_block_channels * 2]])[1:]
net = CIFARXDenseNet(
channels=channels,
init_block_channels=init_block_channels,
classes=classes,
bottleneck=bottleneck,
expand_ratio=expand_ratio,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def xdensenet40_2_k24_bc_cifar10(classes=10, **kwargs):
"""
X-DenseNet-BC-40-2 (k=24) model for CIFAR-10 from 'Deep Expander Networks: Efficient Deep Networks from Graph
Theory,' https://arxiv.org/abs/1711.08757.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_xdensenet_cifar(classes=classes, blocks=40, growth_rate=24, bottleneck=True,
model_name="xdensenet40_2_k24_bc_cifar10", **kwargs)
def xdensenet40_2_k24_bc_cifar100(classes=100, **kwargs):
"""
X-DenseNet-BC-40-2 (k=24) model for CIFAR-100 from 'Deep Expander Networks: Efficient Deep Networks from Graph
Theory,' https://arxiv.org/abs/1711.08757.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_xdensenet_cifar(classes=classes, blocks=40, growth_rate=24, bottleneck=True,
model_name="xdensenet40_2_k24_bc_cifar100", **kwargs)
def xdensenet40_2_k24_bc_svhn(classes=10, **kwargs):
"""
X-DenseNet-BC-40-2 (k=24) model for SVHN from 'Deep Expander Networks: Efficient Deep Networks from Graph
Theory,' https://arxiv.org/abs/1711.08757.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_xdensenet_cifar(classes=classes, blocks=40, growth_rate=24, bottleneck=True,
model_name="xdensenet40_2_k24_bc_svhn", **kwargs)
def xdensenet40_2_k36_bc_cifar10(classes=10, **kwargs):
"""
X-DenseNet-BC-40-2 (k=36) model for CIFAR-10 from 'Deep Expander Networks: Efficient Deep Networks from Graph
Theory,' https://arxiv.org/abs/1711.08757.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_xdensenet_cifar(classes=classes, blocks=40, growth_rate=36, bottleneck=True,
model_name="xdensenet40_2_k36_bc_cifar10", **kwargs)
def xdensenet40_2_k36_bc_cifar100(classes=100, **kwargs):
"""
X-DenseNet-BC-40-2 (k=36) model for CIFAR-100 from 'Deep Expander Networks: Efficient Deep Networks from Graph
Theory,' https://arxiv.org/abs/1711.08757.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_xdensenet_cifar(classes=classes, blocks=40, growth_rate=36, bottleneck=True,
model_name="xdensenet40_2_k36_bc_cifar100", **kwargs)
def xdensenet40_2_k36_bc_svhn(classes=10, **kwargs):
"""
X-DenseNet-BC-40-2 (k=36) model for SVHN from 'Deep Expander Networks: Efficient Deep Networks from Graph
Theory,' https://arxiv.org/abs/1711.08757.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_xdensenet_cifar(classes=classes, blocks=40, growth_rate=36, bottleneck=True,
model_name="xdensenet40_2_k36_bc_svhn", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
(xdensenet40_2_k24_bc_cifar10, 10),
(xdensenet40_2_k24_bc_cifar100, 100),
(xdensenet40_2_k24_bc_svhn, 10),
(xdensenet40_2_k36_bc_cifar10, 10),
(xdensenet40_2_k36_bc_cifar100, 100),
(xdensenet40_2_k36_bc_svhn, 10),
]
for model, classes in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != xdensenet40_2_k24_bc_cifar10 or weight_count == 690346)
assert (model != xdensenet40_2_k24_bc_cifar100 or weight_count == 714196)
assert (model != xdensenet40_2_k24_bc_svhn or weight_count == 690346)
assert (model != xdensenet40_2_k36_bc_cifar10 or weight_count == 1542682)
assert (model != xdensenet40_2_k36_bc_cifar100 or weight_count == 1578412)
assert (model != xdensenet40_2_k36_bc_svhn or weight_count == 1542682)
x = mx.nd.zeros((1, 3, 32, 32), ctx=ctx)
y = net(x)
assert (y.shape == (1, classes))
if __name__ == "__main__":
_test()
| 14,171 | 35.245524 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/ntsnet_cub.py | """
NTS-Net for CUB-200-2011, implemented in Gluon.
Original paper: 'Learning to Navigate for Fine-grained Classification,' https://arxiv.org/abs/1809.00287.
"""
__all__ = ['NTSNet', 'ntsnet_cub']
import os
import numpy as np
import mxnet as mx
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1, conv3x3
from .resnet import resnet50b
def hard_nms(cdds,
top_n=10,
iou_thresh=0.25):
"""
Hard Non-Maximum Suppression.
Parameters:
----------
cdds : np.array
Borders.
top_n : int, default 10
Number of top-K informative regions.
iou_thresh : float, default 0.25
IoU threshold.
Returns:
-------
np.array
Filtered borders.
"""
assert (type(cdds) == np.ndarray)
assert (len(cdds.shape) == 2)
assert (cdds.shape[1] >= 5)
cdds = cdds.copy()
indices = np.argsort(cdds[:, 0])
cdds = cdds[indices]
cdd_results = []
res = cdds
while res.any():
cdd = res[-1]
cdd_results.append(cdd)
if len(cdd_results) == top_n:
return np.array(cdd_results)
res = res[:-1]
start_max = np.maximum(res[:, 1:3], cdd[1:3])
end_min = np.minimum(res[:, 3:5], cdd[3:5])
lengths = end_min - start_max
intersec_map = lengths[:, 0] * lengths[:, 1]
intersec_map[np.logical_or(lengths[:, 0] < 0, lengths[:, 1] < 0)] = 0
iou_map_cur = intersec_map / ((res[:, 3] - res[:, 1]) * (res[:, 4] - res[:, 2]) + (cdd[3] - cdd[1]) * (
cdd[4] - cdd[2]) - intersec_map)
res = res[iou_map_cur < iou_thresh]
return np.array(cdd_results)
class NavigatorBranch(HybridBlock):
"""
Navigator branch block for Navigator unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
"""
def __init__(self,
in_channels,
out_channels,
strides,
**kwargs):
super(NavigatorBranch, self).__init__(**kwargs)
mid_channels = 128
with self.name_scope():
self.down_conv = conv3x3(
in_channels=in_channels,
out_channels=mid_channels,
strides=strides,
use_bias=True)
self.activ = nn.Activation("relu")
self.tidy_conv = conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
use_bias=True)
self.flatten = nn.Flatten()
def hybrid_forward(self, F, x):
y = self.down_conv(x)
y = self.activ(y)
z = self.tidy_conv(y)
z = self.flatten(z)
return z, y
class NavigatorUnit(HybridBlock):
"""
Navigator init.
"""
def __init__(self,
**kwargs):
super(NavigatorUnit, self).__init__(**kwargs)
with self.name_scope():
self.branch1 = NavigatorBranch(
in_channels=2048,
out_channels=6,
strides=1)
self.branch2 = NavigatorBranch(
in_channels=128,
out_channels=6,
strides=2)
self.branch3 = NavigatorBranch(
in_channels=128,
out_channels=9,
strides=2)
def hybrid_forward(self, F, x):
t1, x = self.branch1(x)
t2, x = self.branch2(x)
t3, _ = self.branch3(x)
return F.concat(t1, t2, t3, dim=1)
class NTSNet(HybridBlock):
"""
NTS-Net model from 'Learning to Navigate for Fine-grained Classification,' https://arxiv.org/abs/1809.00287.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
aux : bool, default False
Whether to output auxiliary results.
top_n : int, default 4
Number of extra top-K informative regions.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
backbone,
aux=False,
top_n=4,
in_channels=3,
in_size=(448, 448),
classes=200,
**kwargs):
super(NTSNet, self).__init__(**kwargs)
assert (in_channels > 0)
self.in_size = in_size
self.classes = classes
self.top_n = top_n
self.aux = aux
self.num_cat = 4
pad_side = 224
self.pad_width = (0, 0, 0, 0, pad_side, pad_side, pad_side, pad_side)
_, edge_anchors, _ = self._generate_default_anchor_maps()
self.edge_anchors = (edge_anchors + 224).astype(np.int)
self.edge_anchors = np.concatenate(
(self.edge_anchors.copy(), np.arange(0, len(self.edge_anchors)).reshape(-1, 1)), axis=1)
with self.name_scope():
self.backbone = backbone
self.backbone_tail = nn.HybridSequential(prefix="")
self.backbone_tail.add(nn.GlobalAvgPool2D())
self.backbone_tail.add(nn.Flatten())
self.backbone_tail.add(nn.Dropout(rate=0.5))
self.backbone_classifier = nn.Dense(
units=classes,
in_units=(512 * 4))
self.navigator_unit = NavigatorUnit()
self.concat_net = nn.Dense(
units=classes,
in_units=(2048 * (self.num_cat + 1)))
if self.aux:
self.partcls_net = nn.Dense(
units=classes,
in_units=(512 * 4))
def hybrid_forward(self, F, x):
raw_pre_features = self.backbone(x)
rpn_score = self.navigator_unit(raw_pre_features)
all_cdds = [np.concatenate((y.reshape(-1, 1), self.edge_anchors.copy()), axis=1)
for y in rpn_score.asnumpy()]
top_n_cdds = [hard_nms(y, top_n=self.top_n, iou_thresh=0.25) for y in all_cdds]
top_n_cdds = np.array(top_n_cdds)
top_n_index = top_n_cdds[:, :, -1].astype(np.int64)
top_n_index2 = mx.nd.array(np.array([np.repeat(np.arange(top_n_cdds.shape[0]), top_n_cdds.shape[1]),
top_n_index.flatten()]), dtype=np.int64)
top_n_prob = F.gather_nd(rpn_score, top_n_index2).reshape(x.shape[0], -1)
batch = x.shape[0]
part_imgs = mx.nd.zeros(shape=(batch, self.top_n, 3, 224, 224), ctx=x.context, dtype=x.dtype)
x_pad = F.pad(x, mode="constant", pad_width=self.pad_width, constant_value=0)
for i in range(batch):
for j in range(self.top_n):
y0, x0, y1, x1 = tuple(top_n_cdds[i][j, 1:5].astype(np.int64))
part_imgs[i:i + 1, j] = F.contrib.BilinearResize2D(
x_pad[i:i + 1, :, y0:y1, x0:x1],
height=224,
width=224)
part_imgs = part_imgs.reshape((batch * self.top_n, 3, 224, 224))
part_features = self.backbone_tail(self.backbone(part_imgs.detach()))
part_feature = part_features.reshape((batch, self.top_n, -1))
part_feature = part_feature[:, :self.num_cat, :]
part_feature = part_feature.reshape((batch, -1))
raw_features = self.backbone_tail(raw_pre_features.detach())
concat_out = F.concat(part_feature, raw_features, dim=1)
concat_logits = self.concat_net(concat_out)
if self.aux:
raw_logits = self.backbone_classifier(raw_features)
part_logits = self.partcls_net(part_features).reshape((batch, self.top_n, -1))
return concat_logits, raw_logits, part_logits, top_n_prob
else:
return concat_logits
@staticmethod
def _generate_default_anchor_maps(input_shape=(448, 448)):
"""
Generate default anchor maps.
Parameters:
----------
input_shape : tuple of 2 int
Input image size.
Returns:
-------
center_anchors : np.array
anchors * 4 (oy, ox, h, w).
edge_anchors : np.array
anchors * 4 (y0, x0, y1, x1).
anchor_area : np.array
anchors * 1 (area).
"""
anchor_scale = [2 ** (1.0 / 3.0), 2 ** (2.0 / 3.0)]
anchor_aspect_ratio = [0.667, 1, 1.5]
anchors_setting = (
dict(layer="p3", stride=32, size=48, scale=anchor_scale, aspect_ratio=anchor_aspect_ratio),
dict(layer="p4", stride=64, size=96, scale=anchor_scale, aspect_ratio=anchor_aspect_ratio),
dict(layer="p5", stride=128, size=192, scale=[1, anchor_scale[0], anchor_scale[1]],
aspect_ratio=anchor_aspect_ratio),
)
center_anchors = np.zeros((0, 4), dtype=np.float32)
edge_anchors = np.zeros((0, 4), dtype=np.float32)
anchor_areas = np.zeros((0,), dtype=np.float32)
input_shape = np.array(input_shape, dtype=int)
for anchor_info in anchors_setting:
stride = anchor_info["stride"]
size = anchor_info["size"]
scales = anchor_info["scale"]
aspect_ratios = anchor_info["aspect_ratio"]
output_map_shape = np.ceil(input_shape.astype(np.float32) / stride)
output_map_shape = output_map_shape.astype(np.int)
output_shape = tuple(output_map_shape) + (4, )
ostart = stride / 2.0
oy = np.arange(ostart, ostart + stride * output_shape[0], stride)
oy = oy.reshape(output_shape[0], 1)
ox = np.arange(ostart, ostart + stride * output_shape[1], stride)
ox = ox.reshape(1, output_shape[1])
center_anchor_map_template = np.zeros(output_shape, dtype=np.float32)
center_anchor_map_template[:, :, 0] = oy
center_anchor_map_template[:, :, 1] = ox
for anchor_scale in scales:
for anchor_aspect_ratio in aspect_ratios:
center_anchor_map = center_anchor_map_template.copy()
center_anchor_map[:, :, 2] = size * anchor_scale / float(anchor_aspect_ratio) ** 0.5
center_anchor_map[:, :, 3] = size * anchor_scale * float(anchor_aspect_ratio) ** 0.5
edge_anchor_map = np.concatenate(
(center_anchor_map[:, :, :2] - center_anchor_map[:, :, 2:4] / 2.0,
center_anchor_map[:, :, :2] + center_anchor_map[:, :, 2:4] / 2.0),
axis=-1)
anchor_area_map = center_anchor_map[:, :, 2] * center_anchor_map[:, :, 3]
center_anchors = np.concatenate((center_anchors, center_anchor_map.reshape(-1, 4)))
edge_anchors = np.concatenate((edge_anchors, edge_anchor_map.reshape(-1, 4)))
anchor_areas = np.concatenate((anchor_areas, anchor_area_map.reshape(-1)))
return center_anchors, edge_anchors, anchor_areas
def get_ntsnet(backbone,
aux=False,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create NTS-Net model with specific parameters.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
aux : bool, default False
Whether to output auxiliary results.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
net = NTSNet(
backbone=backbone,
aux=aux,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx,
ignore_extra=True)
return net
def ntsnet_cub(pretrained_backbone=False, aux=True, **kwargs):
"""
NTS-Net model from 'Learning to Navigate for Fine-grained Classification,' https://arxiv.org/abs/1809.00287.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
aux : bool, default True
Whether to output an auxiliary result.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnet50b(pretrained=pretrained_backbone).features[:-1]
return get_ntsnet(backbone=backbone, aux=aux, model_name="ntsnet_cub", **kwargs)
def _test():
import numpy as np
import mxnet as mx
aux = True
pretrained = False
models = [
ntsnet_cub,
]
for model in models:
net = model(pretrained=pretrained, aux=aux)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
if aux:
assert (model != ntsnet_cub or weight_count == 29033133)
else:
assert (model != ntsnet_cub or weight_count == 28623333)
x = mx.nd.zeros((5, 3, 448, 448), ctx=ctx)
ys = net(x)
y = ys[0] if aux else ys
assert (y.shape[0] == x.shape[0]) and (y.shape[1] == 200)
if __name__ == "__main__":
_test()
| 14,467 | 33.695444 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/proxylessnas_cub.py | """
ProxylessNAS for CUB-200-2011, implemented in Gluon.
Original paper: 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,'
https://arxiv.org/abs/1812.00332.
"""
__all__ = ['proxylessnas_cpu_cub', 'proxylessnas_gpu_cub', 'proxylessnas_mobile_cub', 'proxylessnas_mobile14_cub']
from .proxylessnas import get_proxylessnas
def proxylessnas_cpu_cub(classes=200, **kwargs):
"""
ProxylessNAS (CPU) model for CUB-200-2011 from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and
Hardware,' https://arxiv.org/abs/1812.00332.
Parameters:
----------
classes : int, default 200
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_proxylessnas(classes=classes, version="cpu", model_name="proxylessnas_cpu_cub", **kwargs)
def proxylessnas_gpu_cub(classes=200, **kwargs):
"""
ProxylessNAS (GPU) model for CUB-200-2011 from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and
Hardware,' https://arxiv.org/abs/1812.00332.
Parameters:
----------
classes : int, default 200
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_proxylessnas(classes=classes, version="gpu", model_name="proxylessnas_gpu_cub", **kwargs)
def proxylessnas_mobile_cub(classes=200, **kwargs):
"""
ProxylessNAS (Mobile) model for CUB-200-2011 from 'ProxylessNAS: Direct Neural Architecture Search on Target Task
and Hardware,' https://arxiv.org/abs/1812.00332.
Parameters:
----------
classes : int, default 200
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_proxylessnas(classes=classes, version="mobile", model_name="proxylessnas_mobile_cub", **kwargs)
def proxylessnas_mobile14_cub(classes=200, **kwargs):
"""
ProxylessNAS (Mobile-14) model for CUB-200-2011 from 'ProxylessNAS: Direct Neural Architecture Search on Target Task
and Hardware,' https://arxiv.org/abs/1812.00332.
Parameters:
----------
classes : int, default 200
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_proxylessnas(classes=classes, version="mobile14", model_name="proxylessnas_mobile14_cub", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
proxylessnas_cpu_cub,
proxylessnas_gpu_cub,
proxylessnas_mobile_cub,
proxylessnas_mobile14_cub,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != proxylessnas_cpu_cub or weight_count == 3215248)
assert (model != proxylessnas_gpu_cub or weight_count == 5736648)
assert (model != proxylessnas_mobile_cub or weight_count == 3055712)
assert (model != proxylessnas_mobile14_cub or weight_count == 5423168)
x = mx.nd.zeros((14, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (14, 200))
if __name__ == "__main__":
_test()
| 4,484 | 33.767442 | 120 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/ibnresnet.py | """
IBN-ResNet for ImageNet-1K, implemented in Gluon.
Original paper: 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
"""
__all__ = ['IBNResNet', 'ibn_resnet50', 'ibn_resnet101', 'ibn_resnet152']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block, conv3x3_block, IBN
from .resnet import ResInitBlock
class IBNConvBlock(HybridBlock):
"""
IBN-Net specific convolution block with BN/IBN normalization and ReLU activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_ibn : bool, default False
Whether use Instance-Batch Normalization.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
activate : bool, default True
Whether activate the convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
dilation=1,
groups=1,
use_bias=False,
use_ibn=False,
bn_use_global_stats=False,
activate=True,
**kwargs):
super(IBNConvBlock, self).__init__(**kwargs)
self.activate = activate
self.use_ibn = use_ibn
with self.name_scope():
self.conv = nn.Conv2D(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
in_channels=in_channels)
if self.use_ibn:
self.ibn = IBN(channels=out_channels)
else:
self.bn = nn.BatchNorm(
in_channels=out_channels,
use_global_stats=bn_use_global_stats)
if self.activate:
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
x = self.conv(x)
if self.use_ibn:
x = self.ibn(x)
else:
x = self.bn(x)
if self.activate:
x = self.activ(x)
return x
def ibn_conv1x1_block(in_channels,
out_channels,
strides=1,
groups=1,
use_bias=False,
use_ibn=False,
bn_use_global_stats=False,
activate=True):
"""
1x1 version of the IBN-Net specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_ibn : bool, default False
Whether use Instance-Batch Normalization.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
activate : bool, default True
Whether activate the convolution block.
"""
return IBNConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
strides=strides,
padding=0,
groups=groups,
use_bias=use_bias,
use_ibn=use_ibn,
bn_use_global_stats=bn_use_global_stats,
activate=activate)
class IBNResBottleneck(HybridBlock):
"""
IBN-ResNet bottleneck block for residual path in IBN-ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
conv1_ibn : bool
Whether to use IBN normalization in the first convolution layer of the block.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
conv1_ibn,
bn_use_global_stats,
**kwargs):
super(IBNResBottleneck, self).__init__(**kwargs)
mid_channels = out_channels // 4
with self.name_scope():
self.conv1 = ibn_conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
use_ibn=conv1_ibn,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation=None)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class IBNResUnit(HybridBlock):
"""
IBN-ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
conv1_ibn : bool
Whether to use IBN normalization in the first convolution layer of the block.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
conv1_ibn,
bn_use_global_stats,
**kwargs):
super(IBNResUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
self.body = IBNResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
conv1_ibn=conv1_ibn,
bn_use_global_stats=bn_use_global_stats)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
activation=None)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class IBNResNet(HybridBlock):
"""
IBN-ResNet model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(IBNResNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
conv1_ibn = (out_channels < 2048)
stage.add(IBNResUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
conv1_ibn=conv1_ibn,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_ibnresnet(blocks,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create IBN-ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
else:
raise ValueError("Unsupported IBN-ResNet with number of blocks: {}".format(blocks))
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = IBNResNet(
channels=channels,
init_block_channels=init_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def ibn_resnet50(**kwargs):
"""
IBN-ResNet-50 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ibnresnet(blocks=50, model_name="ibn_resnet50", **kwargs)
def ibn_resnet101(**kwargs):
"""
IBN-ResNet-101 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ibnresnet(blocks=101, model_name="ibn_resnet101", **kwargs)
def ibn_resnet152(**kwargs):
"""
IBN-ResNet-152 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ibnresnet(blocks=152, model_name="ibn_resnet152", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
ibn_resnet50,
ibn_resnet101,
ibn_resnet152,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != ibn_resnet50 or weight_count == 25557032)
assert (model != ibn_resnet101 or weight_count == 44549160)
assert (model != ibn_resnet152 or weight_count == 60192808)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 14,932 | 31.81978 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/common.py | """
Common routines for models in Gluon.
"""
__all__ = ['round_channels', 'BreakBlock', 'get_activation_layer', 'ReLU6', 'PReLU2', 'HSigmoid', 'HSwish', 'Softmax',
'SelectableDense', 'BatchNormExtra', 'DenseBlock', 'ConvBlock1d', 'conv1x1', 'conv3x3', 'depthwise_conv3x3',
'ConvBlock', 'conv1x1_block', 'conv3x3_block', 'conv5x5_block', 'conv7x7_block', 'dwconv_block',
'dwconv3x3_block', 'dwconv5x5_block', 'dwsconv3x3_block', 'PreConvBlock', 'pre_conv1x1_block',
'pre_conv3x3_block', 'DeconvBlock', 'NormActivation', 'InterpolationBlock', 'ChannelShuffle',
'ChannelShuffle2', 'SEBlock', 'SABlock', 'SAConvBlock', 'saconv3x3_block', 'DucBlock', 'split', 'IBN',
'DualPathSequential', 'ParametricSequential', 'Concurrent', 'SequentialConcurrent', 'ParametricConcurrent',
'Hourglass', 'SesquialteralHourglass', 'MultiOutputSequential', 'ParallelConcurent',
'DualPathParallelConcurent', 'HeatmapMaxDetBlock']
import math
from inspect import isfunction
import mxnet as mx
from mxnet.gluon import nn, HybridBlock
def round_channels(channels,
divisor=8):
"""
Round weighted channel number (make divisible operation).
Parameters:
----------
channels : int or float
Original number of channels.
divisor : int, default 8
Alignment value.
Returns:
-------
int
Weighted number of channels.
"""
rounded_channels = max(int(channels + divisor / 2.0) // divisor * divisor, divisor)
if float(rounded_channels) < 0.9 * channels:
rounded_channels += divisor
return rounded_channels
class BreakBlock(HybridBlock):
"""
Break coonnection block for hourglass.
"""
def __init__(self, prefix=None, params=None):
super(BreakBlock, self).__init__(prefix=prefix, params=params)
def hybrid_forward(self, F, x):
return None
def __repr__(self):
return '{name}()'.format(name=self.__class__.__name__)
class ReLU6(HybridBlock):
"""
ReLU6 activation layer.
"""
def __init__(self, **kwargs):
super(ReLU6, self).__init__(**kwargs)
def hybrid_forward(self, F, x):
return F.clip(x, 0.0, 6.0, name="relu6")
def __repr__(self):
return '{name}()'.format(name=self.__class__.__name__)
class PReLU2(HybridBlock):
"""
Parametric leaky version of a Rectified Linear Unit (with wide alpha).
Parameters:
----------
in_channels : int
Number of input channels.
alpha_initializer : Initializer
Initializer for the `embeddings` matrix.
"""
def __init__(self,
in_channels=1,
alpha_initializer=mx.init.Constant(0.25),
**kwargs):
super(PReLU2, self).__init__(**kwargs)
with self.name_scope():
self.alpha = self.params.get("alpha", shape=(in_channels,), init=alpha_initializer)
def hybrid_forward(self, F, x, alpha):
return F.LeakyReLU(x, gamma=alpha, act_type="prelu", name="fwd")
def __repr__(self):
s = '{name}(in_channels={in_channels})'
return s.format(
name=self.__class__.__name__,
in_channels=self.alpha.shape[0])
class HSigmoid(HybridBlock):
"""
Approximated sigmoid function, so-called hard-version of sigmoid from 'Searching for MobileNetV3,'
https://arxiv.org/abs/1905.02244.
"""
def __init__(self, **kwargs):
super(HSigmoid, self).__init__(**kwargs)
def hybrid_forward(self, F, x):
return F.clip(x + 3.0, 0.0, 6.0, name="relu6") / 6.0
def __repr__(self):
return '{name}()'.format(name=self.__class__.__name__)
class HSwish(HybridBlock):
"""
H-Swish activation function from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
"""
def __init__(self, **kwargs):
super(HSwish, self).__init__(**kwargs)
def hybrid_forward(self, F, x):
return x * F.clip(x + 3.0, 0.0, 6.0, name="relu6") / 6.0
def __repr__(self):
return '{name}()'.format(name=self.__class__.__name__)
class Softmax(HybridBlock):
"""
Softmax activation function.
Parameters:
----------
axis : int, default 1
Axis along which to do softmax.
"""
def __init__(self, axis=1, **kwargs):
super(Softmax, self).__init__(**kwargs)
self.axis = axis
def hybrid_forward(self, F, x):
return x.softmax(axis=self.axis)
def __repr__(self):
return '{name}()'.format(name=self.__class__.__name__)
def get_activation_layer(activation):
"""
Create activation layer from string/function.
Parameters:
----------
activation : function, or str, or HybridBlock
Activation function or name of activation function.
Returns:
-------
HybridBlock
Activation layer.
"""
assert (activation is not None)
if isfunction(activation):
return activation()
elif isinstance(activation, str):
if activation == "relu6":
return ReLU6()
elif activation == "swish":
return nn.Swish()
elif activation == "hswish":
return HSwish()
elif activation == "hsigmoid":
return HSigmoid()
else:
return nn.Activation(activation)
else:
assert (isinstance(activation, HybridBlock))
return activation
class SelectableDense(HybridBlock):
"""
Selectable dense layer.
Parameters:
----------
in_channels : int
Number of input features.
out_channels : int
Number of output features.
use_bias : bool, default False
Whether the layer uses a bias vector.
dtype : str or np.dtype, default 'float32'
Data type of output embeddings.
weight_initializer : str or `Initializer`
Initializer for the `kernel` weights matrix.
bias_initializer: str or `Initializer`
Initializer for the bias vector.
num_options : int, default 1
Number of selectable options.
"""
def __init__(self,
in_channels,
out_channels,
use_bias=False,
dtype="float32",
weight_initializer=None,
bias_initializer="zeros",
num_options=1,
**kwargs):
super(SelectableDense, self).__init__(**kwargs)
self.in_channels = in_channels
self.out_channels = out_channels
self.use_bias = use_bias
self.num_options = num_options
with self.name_scope():
self.weight = self.params.get(
"weight",
shape=(num_options, out_channels, in_channels),
init=weight_initializer,
dtype=dtype,
allow_deferred_init=True)
if use_bias:
self.bias = self.params.get(
"bias",
shape=(num_options, out_channels),
init=bias_initializer,
dtype=dtype,
allow_deferred_init=True)
else:
self.bias = None
def hybrid_forward(self, F, x, indices, weight, bias=None):
weight = F.take(weight, indices=indices, axis=0)
x = x.expand_dims(axis=-1)
x = F.batch_dot(weight, x)
x = x.squeeze(axis=-1)
if self.use_bias:
bias = F.take(bias, indices=indices, axis=0)
x += bias
return x
def __repr__(self):
s = "{name}({layout}, {num_options})"
shape = self.weight.shape
return s.format(name=self.__class__.__name__,
layout="{0} -> {1}".format(shape[1] if shape[1] else None, shape[0]),
num_options=self.num_options)
class BatchNormExtra(nn.BatchNorm):
"""
Batch normalization layer with extra parameters.
"""
def __init__(self, **kwargs):
has_cudnn_off = ("cudnn_off" in kwargs)
if has_cudnn_off:
cudnn_off = kwargs["cudnn_off"]
del kwargs["cudnn_off"]
super(BatchNormExtra, self).__init__(**kwargs)
if has_cudnn_off:
self._kwargs["cudnn_off"] = cudnn_off
class DenseBlock(HybridBlock):
"""
Standard dense block with Batch normalization and activation.
Parameters:
----------
in_channels : int
Number of input features.
out_channels : int
Number of output features.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
out_channels,
use_bias=False,
use_bn=True,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
activation=(lambda: nn.Activation("relu")),
**kwargs):
super(DenseBlock, self).__init__(**kwargs)
self.activate = (activation is not None)
self.use_bn = use_bn
with self.name_scope():
self.fc = nn.Dense(
units=out_channels,
use_bias=use_bias,
in_units=in_channels)
if self.use_bn:
self.bn = BatchNormExtra(
in_channels=out_channels,
epsilon=bn_epsilon,
use_global_stats=bn_use_global_stats,
cudnn_off=bn_cudnn_off)
if self.activate:
self.activ = get_activation_layer(activation)
def hybrid_forward(self, F, x):
x = self.fc(x)
if self.use_bn:
x = self.bn(x)
if self.activate:
x = self.activ(x)
return x
class ConvBlock1d(HybridBlock):
"""
Standard 1D convolution block with Batch normalization and activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int
Convolution window size.
strides : int
Strides of the convolution.
padding : int
Padding value for convolution layer.
dilation : int
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
dilation=1,
groups=1,
use_bias=False,
use_bn=True,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
activation=(lambda: nn.Activation("relu")),
**kwargs):
super(ConvBlock1d, self).__init__(**kwargs)
self.activate = (activation is not None)
self.use_bn = use_bn
with self.name_scope():
self.conv = nn.Conv1D(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
in_channels=in_channels)
if self.use_bn:
self.bn = BatchNormExtra(
in_channels=out_channels,
epsilon=bn_epsilon,
use_global_stats=bn_use_global_stats,
cudnn_off=bn_cudnn_off)
if self.activate:
self.activ = get_activation_layer(activation)
def hybrid_forward(self, F, x):
x = self.conv(x)
if self.use_bn:
x = self.bn(x)
if self.activate:
x = self.activ(x)
return x
def conv1x1(in_channels,
out_channels,
strides=1,
groups=1,
use_bias=False):
"""
Convolution 1x1 layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
"""
return nn.Conv2D(
channels=out_channels,
kernel_size=1,
strides=strides,
groups=groups,
use_bias=use_bias,
in_channels=in_channels)
def conv3x3(in_channels,
out_channels,
strides=1,
padding=1,
dilation=1,
groups=1,
use_bias=False):
"""
Convolution 3x3 layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
"""
return nn.Conv2D(
channels=out_channels,
kernel_size=3,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
in_channels=in_channels)
def depthwise_conv3x3(channels,
strides=1,
padding=1,
dilation=1,
use_bias=False):
"""
Depthwise convolution 3x3 layer.
Parameters:
----------
channels : int
Number of input/output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
use_bias : bool, default False
Whether the layer uses a bias vector.
"""
return nn.Conv2D(
channels=channels,
kernel_size=3,
strides=strides,
padding=padding,
dilation=dilation,
groups=channels,
use_bias=use_bias,
in_channels=channels)
class ConvBlock(HybridBlock):
"""
Standard convolution block with batch normalization and activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
dilation=1,
groups=1,
use_bias=False,
use_bn=True,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
activation=(lambda: nn.Activation("relu")),
**kwargs):
super(ConvBlock, self).__init__(**kwargs)
self.activate = (activation is not None)
self.use_bn = use_bn
with self.name_scope():
self.conv = nn.Conv2D(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
in_channels=in_channels)
if self.use_bn:
self.bn = BatchNormExtra(
in_channels=out_channels,
epsilon=bn_epsilon,
use_global_stats=bn_use_global_stats,
cudnn_off=bn_cudnn_off)
if self.activate:
self.activ = get_activation_layer(activation)
def hybrid_forward(self, F, x):
x = self.conv(x)
if self.use_bn:
x = self.bn(x)
if self.activate:
x = self.activ(x)
return x
def conv1x1_block(in_channels,
out_channels,
strides=1,
padding=0,
groups=1,
use_bias=False,
use_bn=True,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
activation=(lambda: nn.Activation("relu")),
**kwargs):
"""
1x1 version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 0
Padding value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
"""
return ConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
strides=strides,
padding=padding,
groups=groups,
use_bias=use_bias,
use_bn=use_bn,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=activation,
**kwargs)
def conv3x3_block(in_channels,
out_channels,
strides=1,
padding=1,
dilation=1,
groups=1,
use_bias=False,
use_bn=True,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
activation=(lambda: nn.Activation("relu")),
**kwargs):
"""
3x3 version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
"""
return ConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
use_bn=use_bn,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=activation,
**kwargs)
def conv5x5_block(in_channels,
out_channels,
strides=1,
padding=2,
dilation=1,
groups=1,
use_bias=False,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
activation=(lambda: nn.Activation("relu")),
**kwargs):
"""
5x5 version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 2
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
"""
return ConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=5,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=activation,
**kwargs)
def conv7x7_block(in_channels,
out_channels,
strides=1,
padding=3,
use_bias=False,
use_bn=True,
bn_use_global_stats=False,
bn_cudnn_off=False,
activation=(lambda: nn.Activation("relu")),
**kwargs):
"""
7x7 version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 3
Padding value for convolution layer.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
"""
return ConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=7,
strides=strides,
padding=padding,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=activation,
**kwargs)
def dwconv_block(in_channels,
out_channels,
kernel_size,
strides,
padding,
dilation=1,
use_bias=False,
use_bn=True,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
activation=(lambda: nn.Activation("relu")),
**kwargs):
"""
Depthwise version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
"""
return ConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
dilation=dilation,
groups=out_channels,
use_bias=use_bias,
use_bn=use_bn,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=activation,
**kwargs)
def dwconv3x3_block(in_channels,
out_channels,
strides=1,
padding=1,
dilation=1,
use_bias=False,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
activation=(lambda: nn.Activation("relu")),
**kwargs):
"""
3x3 depthwise version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
use_bias : bool, default False
Whether the layer uses a bias vector.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
"""
return dwconv_block(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
strides=strides,
padding=padding,
dilation=dilation,
use_bias=use_bias,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=activation,
**kwargs)
def dwconv5x5_block(in_channels,
out_channels,
strides=1,
padding=2,
dilation=1,
use_bias=False,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
activation=(lambda: nn.Activation("relu")),
**kwargs):
"""
5x5 depthwise version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 2
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
use_bias : bool, default False
Whether the layer uses a bias vector.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
"""
return dwconv_block(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=5,
strides=strides,
padding=padding,
dilation=dilation,
use_bias=use_bias,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=activation,
**kwargs)
class DwsConvBlock(HybridBlock):
"""
Depthwise separable convolution block with BatchNorms and activations at each convolution layers.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
use_bias : bool, default False
Whether the layer uses a bias vector.
dw_use_bn : bool, default True
Whether to use BatchNorm layer (depthwise convolution block).
pw_use_bn : bool, default True
Whether to use BatchNorm layer (pointwise convolution block).
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
dw_activation : function or str or None, default nn.Activation('relu')
Activation function after the depthwise convolution block.
pw_activation : function or str or None, default nn.Activation('relu')
Activation function after the pointwise convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
dilation=1,
use_bias=False,
dw_use_bn=True,
pw_use_bn=True,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
dw_activation=(lambda: nn.Activation("relu")),
pw_activation=(lambda: nn.Activation("relu")),
**kwargs):
super(DwsConvBlock, self).__init__(**kwargs)
with self.name_scope():
self.dw_conv = dwconv_block(
in_channels=in_channels,
out_channels=in_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
dilation=dilation,
use_bias=use_bias,
use_bn=dw_use_bn,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=dw_activation)
self.pw_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
use_bias=use_bias,
use_bn=pw_use_bn,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=pw_activation)
def hybrid_forward(self, F, x):
x = self.dw_conv(x)
x = self.pw_conv(x)
return x
def dwsconv3x3_block(in_channels,
out_channels,
strides=1,
padding=1,
dilation=1,
use_bias=False,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
dw_activation=(lambda: nn.Activation("relu")),
pw_activation=(lambda: nn.Activation("relu")),
**kwargs):
"""
3x3 depthwise separable version of the standard convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
use_bias : bool, default False
Whether the layer uses a bias vector.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
dw_activation : function or str or None, default nn.Activation('relu')
Activation function after the depthwise convolution block.
pw_activation : function or str or None, default nn.Activation('relu')
Activation function after the pointwise convolution block.
"""
return DwsConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
strides=strides,
padding=padding,
dilation=dilation,
use_bias=use_bias,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
dw_activation=dw_activation,
pw_activation=pw_activation,
**kwargs)
class PreConvBlock(HybridBlock):
"""
Convolution block with Batch normalization and ReLU pre-activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
return_preact : bool, default False
Whether return pre-activation. It's used by PreResNet.
activate : bool, default True
Whether activate the convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
dilation=1,
groups=1,
use_bias=False,
use_bn=True,
bn_use_global_stats=False,
return_preact=False,
activate=True,
**kwargs):
super(PreConvBlock, self).__init__(**kwargs)
self.return_preact = return_preact
self.activate = activate
self.use_bn = use_bn
with self.name_scope():
if self.use_bn:
self.bn = nn.BatchNorm(
in_channels=in_channels,
use_global_stats=bn_use_global_stats)
if self.activate:
self.activ = nn.Activation("relu")
self.conv = nn.Conv2D(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
in_channels=in_channels)
def hybrid_forward(self, F, x):
if self.use_bn:
x = self.bn(x)
if self.activate:
x = self.activ(x)
if self.return_preact:
x_pre_activ = x
x = self.conv(x)
if self.return_preact:
return x, x_pre_activ
else:
return x
def pre_conv1x1_block(in_channels,
out_channels,
strides=1,
use_bias=False,
use_bn=True,
bn_use_global_stats=False,
return_preact=False,
activate=True):
"""
1x1 version of the pre-activated convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
return_preact : bool, default False
Whether return pre-activation.
activate : bool, default True
Whether activate the convolution block.
"""
return PreConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
strides=strides,
padding=0,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats,
return_preact=return_preact,
activate=activate)
def pre_conv3x3_block(in_channels,
out_channels,
strides=1,
padding=1,
dilation=1,
groups=1,
use_bias=False,
use_bn=True,
bn_use_global_stats=False,
return_preact=False,
activate=True):
"""
3x3 version of the pre-activated convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
return_preact : bool, default False
Whether return pre-activation.
activate : bool, default True
Whether activate the convolution block.
"""
return PreConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats,
return_preact=return_preact,
activate=activate)
class DeconvBlock(HybridBlock):
"""
Deconvolution block with batch normalization and activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the deconvolution.
padding : int or tuple/list of 2 int
Padding value for deconvolution layer.
out_padding : int or tuple/list of 2 int
Output padding value for deconvolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for deconvolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
out_padding=0,
dilation=1,
groups=1,
use_bias=False,
use_bn=True,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
activation=(lambda: nn.Activation("relu")),
**kwargs):
super(DeconvBlock, self).__init__(**kwargs)
self.activate = (activation is not None)
self.use_bn = use_bn
with self.name_scope():
self.conv = nn.Conv2DTranspose(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
output_padding=out_padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
in_channels=in_channels)
if self.use_bn:
self.bn = BatchNormExtra(
in_channels=out_channels,
epsilon=bn_epsilon,
use_global_stats=bn_use_global_stats,
cudnn_off=bn_cudnn_off)
if self.activate:
self.activ = get_activation_layer(activation)
def hybrid_forward(self, F, x):
x = self.conv(x)
if self.use_bn:
x = self.bn(x)
if self.activate:
x = self.activ(x)
return x
class NormActivation(HybridBlock):
"""
Activation block with preliminary batch normalization. It's used by itself as the final block in PreResNet.
Parameters:
----------
in_channels : int
Number of input channels.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
activation=(lambda: nn.Activation("relu")),
**kwargs):
super(NormActivation, self).__init__(**kwargs)
with self.name_scope():
self.bn = BatchNormExtra(
in_channels=in_channels,
epsilon=bn_epsilon,
use_global_stats=bn_use_global_stats,
cudnn_off=bn_cudnn_off)
self.activ = get_activation_layer(activation)
def hybrid_forward(self, F, x):
x = self.bn(x)
x = self.activ(x)
return x
class InterpolationBlock(HybridBlock):
"""
Interpolation block.
Parameters:
----------
scale_factor : int
Multiplier for spatial size.
out_size : tuple of 2 int, default None
Spatial size of the output tensor for the bilinear interpolation operation.
bilinear : bool, default True
Whether to use bilinear interpolation.
up : bool, default True
Whether to upsample or downsample.
"""
def __init__(self,
scale_factor,
out_size=None,
bilinear=True,
up=True,
**kwargs):
super(InterpolationBlock, self).__init__(**kwargs)
self.scale_factor = scale_factor
self.out_size = out_size
self.bilinear = bilinear
self.up = up
def hybrid_forward(self, F, x, size=None):
if self.bilinear or (size is not None):
out_size = self.calc_out_size(x) if size is None else size
return F.contrib.BilinearResize2D(x, height=out_size[0], width=out_size[1])
else:
return F.UpSampling(x, scale=self.scale_factor, sample_type="nearest")
def calc_out_size(self, x):
if self.out_size is not None:
return self.out_size
if self.up:
return tuple(s * self.scale_factor for s in x.shape[2:])
else:
return tuple(s // self.scale_factor for s in x.shape[2:])
def __repr__(self):
s = '{name}(scale_factor={scale_factor}, out_size={out_size}, bilinear={bilinear}, up={up})'
return s.format(
name=self.__class__.__name__,
scale_factor=self.scale_factor,
out_size=self.out_size,
bilinear=self.bilinear,
up=self.up)
def calc_flops(self, x):
assert (x.shape[0] == 1)
if self.bilinear:
num_flops = 9 * x.size
else:
num_flops = 4 * x.size
num_macs = 0
return num_flops, num_macs
def channel_shuffle(x,
groups):
"""
Channel shuffle operation from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
Parameters:
----------
x : Symbol or NDArray
Input tensor.
groups : int
Number of groups.
Returns:
-------
Symbol or NDArray
Resulted tensor.
"""
return x.reshape((0, -4, groups, -1, -2)).swapaxes(1, 2).reshape((0, -3, -2))
class ChannelShuffle(HybridBlock):
"""
Channel shuffle layer. This is a wrapper over the same operation. It is designed to save the number of groups.
Parameters:
----------
channels : int
Number of channels.
groups : int
Number of groups.
"""
def __init__(self,
channels,
groups,
**kwargs):
super(ChannelShuffle, self).__init__(**kwargs)
assert (channels % groups == 0)
self.groups = groups
def hybrid_forward(self, F, x):
return channel_shuffle(x, self.groups)
def __repr__(self):
s = "{name}(groups={groups})"
return s.format(
name=self.__class__.__name__,
groups=self.groups)
def channel_shuffle2(x,
channels_per_group):
"""
Channel shuffle operation from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083. The alternative version.
Parameters:
----------
x : Symbol or NDArray
Input tensor.
channels_per_group : int
Number of channels per group.
Returns:
-------
Symbol or NDArray
Resulted tensor.
"""
return x.reshape((0, -4, channels_per_group, -1, -2)).swapaxes(1, 2).reshape((0, -3, -2))
class ChannelShuffle2(HybridBlock):
"""
Channel shuffle layer. This is a wrapper over the same operation. It is designed to save the number of groups.
The alternative version.
Parameters:
----------
channels : int
Number of channels.
groups : int
Number of groups.
"""
def __init__(self,
channels,
groups,
**kwargs):
super(ChannelShuffle2, self).__init__(**kwargs)
assert (channels % groups == 0)
self.channels_per_group = channels // groups
def hybrid_forward(self, F, x):
return channel_shuffle2(x, self.channels_per_group)
class SEBlock(HybridBlock):
"""
Squeeze-and-Excitation block from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
channels : int
Number of channels.
reduction : int, default 16
Squeeze reduction value.
mid_channels : int or None, default None
Number of middle channels.
round_mid : bool, default False
Whether to round middle channel number (make divisible by 8).
use_conv : bool, default True
Whether to convolutional layers instead of fully-connected ones.
activation : function, or str, or HybridBlock, default 'relu'
Activation function after the first convolution.
out_activation : function, or str, or HybridBlock, default 'sigmoid'
Activation function after the last convolution.
"""
def __init__(self,
channels,
reduction=16,
mid_channels=None,
round_mid=False,
use_conv=True,
mid_activation=(lambda: nn.Activation("relu")),
out_activation=(lambda: nn.Activation("sigmoid")),
**kwargs):
super(SEBlock, self).__init__(**kwargs)
self.use_conv = use_conv
if mid_channels is None:
mid_channels = channels // reduction if not round_mid else round_channels(float(channels) / reduction)
with self.name_scope():
if use_conv:
self.conv1 = conv1x1(
in_channels=channels,
out_channels=mid_channels,
use_bias=True)
else:
self.fc1 = nn.Dense(
in_units=channels,
units=mid_channels)
self.activ = get_activation_layer(mid_activation)
if use_conv:
self.conv2 = conv1x1(
in_channels=mid_channels,
out_channels=channels,
use_bias=True)
else:
self.fc2 = nn.Dense(
in_units=mid_channels,
units=channels)
self.sigmoid = get_activation_layer(out_activation)
def hybrid_forward(self, F, x):
w = F.contrib.AdaptiveAvgPooling2D(x, output_size=1)
if not self.use_conv:
w = F.Flatten(w)
w = self.conv1(w) if self.use_conv else self.fc1(w)
w = self.activ(w)
w = self.conv2(w) if self.use_conv else self.fc2(w)
w = self.sigmoid(w)
if not self.use_conv:
w = w.expand_dims(2).expand_dims(3)
x = F.broadcast_mul(x, w)
return x
class SABlock(HybridBlock):
"""
Split-Attention block from 'ResNeSt: Split-Attention Networks,' https://arxiv.org/abs/2004.08955.
Parameters:
----------
out_channels : int
Number of output channels.
groups : int
Number of channel groups (cardinality, without radix).
radix : int
Number of splits within a cardinal group.
reduction : int, default 4
Squeeze reduction value.
min_channels : int, default 32
Minimal number of squeezed channels.
use_conv : bool, default True
Whether to convolutional layers instead of fully-connected ones.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
out_channels,
groups,
radix,
reduction=4,
min_channels=32,
use_conv=True,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(SABlock, self).__init__(**kwargs)
self.groups = groups
self.radix = radix
self.use_conv = use_conv
in_channels = out_channels * radix
mid_channels = max(in_channels // reduction, min_channels)
with self.name_scope():
if use_conv:
self.conv1 = conv1x1(
in_channels=out_channels,
out_channels=mid_channels,
use_bias=True)
else:
self.fc1 = nn.Dense(
in_units=out_channels,
units=mid_channels)
self.bn = BatchNormExtra(
in_channels=mid_channels,
epsilon=bn_epsilon,
use_global_stats=bn_use_global_stats,
cudnn_off=bn_cudnn_off)
self.activ = nn.Activation("relu")
if use_conv:
self.conv2 = conv1x1(
in_channels=mid_channels,
out_channels=in_channels,
use_bias=True)
else:
self.fc2 = nn.Dense(
in_units=mid_channels,
units=in_channels)
def hybrid_forward(self, F, x):
x = x.reshape((0, -4, self.radix, -1, -2))
w = x.sum(axis=1)
w = F.contrib.AdaptiveAvgPooling2D(w, output_size=1)
if not self.use_conv:
w = F.Flatten(w)
w = self.conv1(w) if self.use_conv else self.fc1(w)
w = self.bn(w)
w = self.activ(w)
w = self.conv2(w) if self.use_conv else self.fc2(w)
w = w.reshape((0, self.groups, self.radix, -1))
w = w.swapaxes(1, 2)
w = F.softmax(w, axis=1)
w = w.reshape((0, self.radix, -1, 1, 1))
x = F.broadcast_mul(x, w)
x = x.sum(axis=1)
return x
class SAConvBlock(HybridBlock):
"""
Split-Attention convolution block from 'ResNeSt: Split-Attention Networks,' https://arxiv.org/abs/2004.08955.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layer.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
radix : int, default 2
Number of splits within a cardinal group.
reduction : int, default 4
Squeeze reduction value.
min_channels : int, default 32
Minimal number of squeezed channels.
use_conv : bool, default True
Whether to convolutional layers instead of fully-connected ones.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
dilation=1,
groups=1,
use_bias=False,
use_bn=True,
bn_epsilon=1e-5,
bn_use_global_stats=False,
bn_cudnn_off=False,
activation=(lambda: nn.Activation("relu")),
radix=2,
reduction=4,
min_channels=32,
use_conv=True,
**kwargs):
super(SAConvBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv = ConvBlock(
in_channels=in_channels,
out_channels=(out_channels * radix),
kernel_size=kernel_size,
strides=strides,
padding=padding,
dilation=dilation,
groups=(groups * radix),
use_bias=use_bias,
use_bn=use_bn,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=activation)
self.att = SABlock(
out_channels=out_channels,
groups=groups,
radix=radix,
reduction=reduction,
min_channels=min_channels,
use_conv=use_conv,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.att(x)
return x
def saconv3x3_block(in_channels,
out_channels,
strides=1,
padding=1,
**kwargs):
"""
3x3 version of the Split-Attention convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
"""
return SAConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
strides=strides,
padding=padding,
**kwargs)
class PixelShuffle(HybridBlock):
"""
Pixel-shuffle operation from 'Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel
Convolutional Neural Network,' https://arxiv.org/abs/1609.05158.
Parameters:
----------
scale_factor : int
Multiplier for spatial size.
in_size : tuple of 2 int
Spatial size of the input heatmap tensor.
fixed_size : bool
Whether to expect fixed spatial size of input image.
"""
def __init__(self,
channels,
scale_factor,
in_size,
fixed_size,
**kwargs):
super(PixelShuffle, self).__init__(**kwargs)
assert (channels % scale_factor % scale_factor == 0)
self.channels = channels
self.scale_factor = scale_factor
self.in_size = in_size
self.fixed_size = fixed_size
def hybrid_forward(self, F, x):
f1 = self.scale_factor
f2 = self.scale_factor
if not self.fixed_size:
x = x.reshape((0, -4, -1, f1 * f2, 0, 0))
x = x.reshape((0, 0, -4, f1, f2, 0, 0))
x = x.transpose((0, 1, 4, 2, 5, 3))
x = x.reshape((0, 0, -3, -3))
else:
new_channels = self.channels // f1 // f2
h, w = self.in_size
x = x.reshape((0, new_channels, f1 * f2, h, w))
x = x.reshape((0, new_channels, f1, f2, h, w))
x = x.transpose((0, 1, 4, 2, 5, 3))
x = x.reshape((0, new_channels, h * f1, w * f2))
return x
class DucBlock(HybridBlock):
"""
Dense Upsampling Convolution (DUC) block from 'Understanding Convolution for Semantic Segmentation,'
https://arxiv.org/abs/1702.08502.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
scale_factor : int
Multiplier for spatial size.
in_size : tuple of 2 int
Spatial size of the input heatmap tensor.
fixed_size : bool
Whether to expect fixed spatial size of input image.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
scale_factor,
in_size,
fixed_size,
bn_use_global_stats,
bn_cudnn_off,
**kwargs):
super(DucBlock, self).__init__(**kwargs)
mid_channels = (scale_factor * scale_factor) * out_channels
with self.name_scope():
self.conv = conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.pix_shuffle = PixelShuffle(
channels=mid_channels,
scale_factor=scale_factor,
in_size=in_size,
fixed_size=fixed_size)
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.pix_shuffle(x)
return x
def split(x,
sizes,
axis=1):
"""
Splits an array along a particular axis into multiple sub-arrays.
Parameters:
----------
x : Symbol or NDArray
Input tensor.
sizes : tuple/list of int
Sizes of chunks.
axis : int, default 1
Axis along which to split.
Returns:
-------
Tuple of Symbol or NDArray
Resulted tensor.
"""
x_outs = []
begin = 0
for size in sizes:
end = begin + size
x_outs += [x.slice_axis(axis=axis, begin=begin, end=end)]
begin = end
return tuple(x_outs)
class IBN(HybridBlock):
"""
Instance-Batch Normalization block from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
channels : int
Number of channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
inst_fraction : float, default 0.5
The first fraction of channels for normalization.
inst_first : bool, default True
Whether instance normalization be on the first part of channels.
"""
def __init__(self,
channels,
bn_use_global_stats=False,
first_fraction=0.5,
inst_first=True,
**kwargs):
super(IBN, self).__init__(**kwargs)
self.inst_first = inst_first
h1_channels = int(math.floor(channels * first_fraction))
h2_channels = channels - h1_channels
self.split_sections = [h1_channels, h2_channels]
if self.inst_first:
self.inst_norm = nn.InstanceNorm(
in_channels=h1_channels,
scale=True)
self.batch_norm = nn.BatchNorm(
in_channels=h2_channels,
use_global_stats=bn_use_global_stats)
else:
self.batch_norm = nn.BatchNorm(
in_channels=h1_channels,
use_global_stats=bn_use_global_stats)
self.inst_norm = nn.InstanceNorm(
in_channels=h2_channels,
scale=True)
def hybrid_forward(self, F, x):
x1, x2 = split(x, sizes=self.split_sections, axis=1)
if self.inst_first:
x1 = self.inst_norm(x1)
x2 = self.batch_norm(x2)
else:
x1 = self.batch_norm(x1)
x2 = self.inst_norm(x2)
x = F.concat(x1, x2, dim=1)
return x
class DualPathSequential(nn.HybridSequential):
"""
A sequential container for hybrid blocks with dual inputs/outputs.
Blocks will be executed in the order they are added.
Parameters:
----------
return_two : bool, default True
Whether to return two output after execution.
first_ordinals : int, default 0
Number of the first blocks with single input/output.
last_ordinals : int, default 0
Number of the final blocks with single input/output.
dual_path_scheme : function
Scheme of dual path response for a block.
dual_path_scheme_ordinal : function
Scheme of dual path response for an ordinal block.
"""
def __init__(self,
return_two=True,
first_ordinals=0,
last_ordinals=0,
dual_path_scheme=(lambda block, x1, x2: block(x1, x2)),
dual_path_scheme_ordinal=(lambda block, x1, x2: (block(x1), x2)),
**kwargs):
super(DualPathSequential, self).__init__(**kwargs)
self.return_two = return_two
self.first_ordinals = first_ordinals
self.last_ordinals = last_ordinals
self.dual_path_scheme = dual_path_scheme
self.dual_path_scheme_ordinal = dual_path_scheme_ordinal
def hybrid_forward(self, F, x1, x2=None):
length = len(self._children.values())
for i, block in enumerate(self._children.values()):
if (i < self.first_ordinals) or (i >= length - self.last_ordinals):
x1, x2 = self.dual_path_scheme_ordinal(block, x1, x2)
else:
x1, x2 = self.dual_path_scheme(block, x1, x2)
if self.return_two:
return x1, x2
else:
return x1
class ParametricSequential(nn.HybridSequential):
"""
A sequential container for blocks with parameters.
Blocks will be executed in the order they are added.
"""
def __init__(self,
**kwargs):
super(ParametricSequential, self).__init__(**kwargs)
def hybrid_forward(self, F, x, *args, **kwargs):
for block in self._children.values():
x = block(x, *args, **kwargs)
return x
class Concurrent(nn.HybridSequential):
"""
A container for concatenation of blocks on the base of the sequential container.
Parameters:
----------
axis : int, default 1
The axis on which to concatenate the outputs.
stack : bool, default False
Whether to concatenate tensors along a new dimension.
merge_type : str, default None
Type of branch merging.
branches : list of HybridBlock, default None
Whether to concatenate tensors along a new dimension.
"""
def __init__(self,
axis=1,
stack=False,
merge_type=None,
branches=None,
**kwargs):
super(Concurrent, self).__init__(**kwargs)
assert (merge_type is None) or (merge_type in ["cat", "stack", "sum"])
self.axis = axis
self.stack = stack
if merge_type is not None:
self.merge_type = merge_type
else:
self.merge_type = "stack" if stack else "cat"
if branches is not None:
with self.name_scope():
for branch in branches:
self.add(branch)
def hybrid_forward(self, F, x):
out = []
for block in self._children.values():
out.append(block(x))
if self.merge_type == "stack":
out = F.stack(*out, axis=self.axis)
elif self.merge_type == "cat":
out = F.concat(*out, dim=self.axis)
elif self.merge_type == "sum":
out = F.stack(*out, axis=self.axis).sum(axis=self.axis)
else:
raise NotImplementedError()
return out
class SequentialConcurrent(nn.HybridSequential):
"""
A sequential container with concatenated outputs.
Blocks will be executed in the order they are added.
Parameters:
----------
axis : int, default 1
The axis on which to concatenate the outputs.
stack : bool, default False
Whether to concatenate tensors along a new dimension.
cat_input : bool, default True
Whether to concatenate input tensor.
"""
def __init__(self,
axis=1,
stack=False,
cat_input=True,
**kwargs):
super(SequentialConcurrent, self).__init__(**kwargs)
self.axis = axis
self.stack = stack
self.cat_input = cat_input
def hybrid_forward(self, F, x):
out = [x] if self.cat_input else []
for block in self._children.values():
x = block(x)
out.append(x)
if self.stack:
out = F.stack(*out, axis=self.axis)
else:
out = F.concat(*out, dim=self.axis)
return out
class ParametricConcurrent(nn.HybridSequential):
"""
A container for concatenation of blocks with parameters.
Parameters:
----------
axis : int, default 1
The axis on which to concatenate the outputs.
"""
def __init__(self,
axis=1,
**kwargs):
super(ParametricConcurrent, self).__init__(**kwargs)
self.axis = axis
def hybrid_forward(self, F, x, *args, **kwargs):
out = []
for block in self._children.values():
out.append(block(x, *args, **kwargs))
out = F.concat(*out, dim=self.axis)
return out
class Hourglass(HybridBlock):
"""
A hourglass block.
Parameters:
----------
down_seq : nn.HybridSequential
Down modules as sequential.
up_seq : nn.HybridSequential
Up modules as sequential.
skip_seq : nn.HybridSequential
Skip connection modules as sequential.
merge_type : str, default 'add'
Type of concatenation of up and skip outputs.
return_first_skip : bool, default False
Whether return the first skip connection output. Used in ResAttNet.
"""
def __init__(self,
down_seq,
up_seq,
skip_seq,
merge_type="add",
return_first_skip=False,
**kwargs):
super(Hourglass, self).__init__(**kwargs)
self.depth = len(down_seq)
assert (merge_type in ["cat", "add"])
assert (len(up_seq) == self.depth)
assert (len(skip_seq) in (self.depth, self.depth + 1))
self.merge_type = merge_type
self.return_first_skip = return_first_skip
self.extra_skip = (len(skip_seq) == self.depth + 1)
with self.name_scope():
self.down_seq = down_seq
self.up_seq = up_seq
self.skip_seq = skip_seq
def _merge(self, F, x, y):
if y is not None:
if self.merge_type == "cat":
x = F.concat(x, y, dim=1)
elif self.merge_type == "add":
x = x + y
return x
def hybrid_forward(self, F, x):
y = None
down_outs = [x]
for down_module in self.down_seq._children.values():
x = down_module(x)
down_outs.append(x)
for i in range(len(down_outs)):
if i != 0:
y = down_outs[self.depth - i]
skip_module = self.skip_seq[self.depth - i]
y = skip_module(y)
x = self._merge(F, x, y)
if i != len(down_outs) - 1:
if (i == 0) and self.extra_skip:
skip_module = self.skip_seq[self.depth]
x = skip_module(x)
up_module = self.up_seq[self.depth - 1 - i]
x = up_module(x)
if self.return_first_skip:
return x, y
else:
return x
class SesquialteralHourglass(HybridBlock):
"""
A sesquialteral hourglass block.
Parameters:
----------
down1_seq : nn.Sequential
The first down modules as sequential.
skip1_seq : nn.Sequential
The first skip connection modules as sequential.
up_seq : nn.Sequential
Up modules as sequential.
skip2_seq : nn.Sequential
The second skip connection modules as sequential.
down2_seq : nn.Sequential
The second down modules as sequential.
merge_type : str, default 'cat'
Type of concatenation of up and skip outputs.
"""
def __init__(self,
down1_seq,
skip1_seq,
up_seq,
skip2_seq,
down2_seq,
merge_type="cat",
**kwargs):
super(SesquialteralHourglass, self).__init__(**kwargs)
assert (len(down1_seq) == len(up_seq))
assert (len(down1_seq) == len(down2_seq))
assert (len(skip1_seq) == len(skip2_seq))
assert (len(down1_seq) == len(skip1_seq) - 1)
assert (merge_type in ["cat", "add"])
self.merge_type = merge_type
self.depth = len(down1_seq)
with self.name_scope():
self.down1_seq = down1_seq
self.skip1_seq = skip1_seq
self.up_seq = up_seq
self.skip2_seq = skip2_seq
self.down2_seq = down2_seq
def _merge(self, F, x, y):
if y is not None:
if self.merge_type == "cat":
x = F.concat(x, y, dim=1)
elif self.merge_type == "add":
x = x + y
return x
def hybrid_forward(self, F, x):
y = self.skip1_seq[0](x)
skip1_outs = [y]
for i in range(self.depth):
x = self.down1_seq[i](x)
y = self.skip1_seq[i + 1](x)
skip1_outs.append(y)
x = skip1_outs[self.depth]
y = self.skip2_seq[0](x)
skip2_outs = [y]
for i in range(self.depth):
x = self.up_seq[i](x)
y = skip1_outs[self.depth - 1 - i]
x = self._merge(F, x, y)
y = self.skip2_seq[i + 1](x)
skip2_outs.append(y)
x = self.skip2_seq[self.depth](x)
for i in range(self.depth):
x = self.down2_seq[i](x)
y = skip2_outs[self.depth - 1 - i]
x = self._merge(F, x, y)
return x
class MultiOutputSequential(nn.HybridSequential):
"""
A sequential container with multiple outputs.
Blocks will be executed in the order they are added.
Parameters:
----------
multi_output : bool, default True
Whether to return multiple output.
dual_output : bool, default False
Whether to return dual output.
return_last : bool, default True
Whether to forcibly return last value.
"""
def __init__(self,
multi_output=True,
dual_output=False,
return_last=True,
**kwargs):
super(MultiOutputSequential, self).__init__(**kwargs)
self.multi_output = multi_output
self.dual_output = dual_output
self.return_last = return_last
def hybrid_forward(self, F, x):
outs = []
for block in self._children.values():
x = block(x)
if hasattr(block, "do_output") and block.do_output:
outs.append(x)
elif hasattr(block, "do_output2") and block.do_output2:
assert (type(x) == tuple)
outs.extend(x[1])
x = x[0]
if self.multi_output:
return [x] + outs if self.return_last else outs
elif self.dual_output:
return x, outs
else:
return x
class ParallelConcurent(nn.HybridSequential):
"""
A sequential container with multiple inputs and multiple outputs.
Modules will be executed in the order they are added.
Parameters:
----------
axis : int, default 1
The axis on which to concatenate the outputs.
merge_type : str, default 'list'
Type of branch merging.
"""
def __init__(self,
axis=1,
merge_type="list",
**kwargs):
super(ParallelConcurent, self).__init__(**kwargs)
assert (merge_type is None) or (merge_type in ["list", "cat", "stack", "sum"])
self.axis = axis
self.merge_type = merge_type
def hybrid_forward(self, F, x):
out = []
for block, xi in zip(self._children.values(), x):
out.append(block(xi))
if self.merge_type == "list":
pass
elif self.merge_type == "stack":
out = F.stack(*out, axis=self.axis)
elif self.merge_type == "cat":
out = F.concat(*out, dim=self.axis)
elif self.merge_type == "sum":
out = F.stack(*out, axis=self.axis).sum(axis=self.axis)
else:
raise NotImplementedError()
return out
class DualPathParallelConcurent(nn.HybridSequential):
"""
A sequential container with multiple dual-path inputs and single/multiple outputs.
Blocks will be executed in the order they are added.
Parameters:
----------
axis : int, default 1
The axis on which to concatenate the outputs.
merge_type : str, default 'list'
Type of branch merging.
"""
def __init__(self,
axis=1,
merge_type="list",
**kwargs):
super(DualPathParallelConcurent, self).__init__(**kwargs)
assert (merge_type is None) or (merge_type in ["list", "cat", "stack", "sum"])
self.axis = axis
self.merge_type = merge_type
def hybrid_forward(self, F, x1, x2):
x1_out = []
x2_out = []
for block, x1i, x2i in zip(self._children.values(), x1, x2):
y1i, y2i = block(x1i, x2i)
x1_out.append(y1i)
x2_out.append(y2i)
if self.merge_type == "list":
pass
elif self.merge_type == "stack":
x1_out = F.stack(*x1_out, axis=self.axis)
x2_out = F.stack(*x2_out, axis=self.axis)
elif self.merge_type == "cat":
x1_out = F.concat(*x1_out, dim=self.axis)
x2_out = F.concat(*x2_out, dim=self.axis)
elif self.merge_type == "sum":
x1_out = F.stack(*x1_out, axis=self.axis).sum(axis=self.axis)
x2_out = F.stack(*x2_out, axis=self.axis).sum(axis=self.axis)
else:
raise NotImplementedError()
return x1_out, x2_out
class HeatmapMaxDetBlock(HybridBlock):
"""
Heatmap maximum detector block (for human pose estimation task).
Parameters:
----------
channels : int
Number of channels.
in_size : tuple of 2 int
Spatial size of the input heatmap tensor.
fixed_size : bool
Whether to expect fixed spatial size of input image.
tune : bool, default True
Whether to tune point positions.
"""
def __init__(self,
channels,
in_size,
fixed_size,
tune=True,
**kwargs):
super(HeatmapMaxDetBlock, self).__init__(**kwargs)
self.channels = channels
self.in_size = in_size
self.fixed_size = fixed_size
self.tune = tune
def hybrid_forward(self, F, x):
# assert (not self.fixed_size) or (self.in_size == x.shape[2:])
vector_dim = 2
in_size = self.in_size if self.fixed_size else x.shape[2:]
heatmap_vector = x.reshape((0, 0, -3))
indices = heatmap_vector.argmax(axis=vector_dim, keepdims=True)
scores = heatmap_vector.max(axis=vector_dim, keepdims=True)
scores_mask = (scores > 0.0)
pts_x = (indices % in_size[1]) * scores_mask
pts_y = (indices / in_size[1]).floor() * scores_mask
pts = F.concat(pts_x, pts_y, scores, dim=vector_dim)
if self.tune:
batch = x.shape[0]
for b in range(batch):
for k in range(self.channels):
hm = x[b, k, :, :]
px = int(pts[b, k, 0].asscalar())
py = int(pts[b, k, 1].asscalar())
if (0 < px < in_size[1] - 1) and (0 < py < in_size[0] - 1):
pts[b, k, 0] += (hm[py, px + 1] - hm[py, px - 1]).sign() * 0.25
pts[b, k, 1] += (hm[py + 1, px] - hm[py - 1, px]).sign() * 0.25
return pts
def __repr__(self):
s = "{name}(channels={channels}, in_size={in_size}, fixed_size={fixed_size})"
return s.format(
name=self.__class__.__name__,
channels=self.channels,
in_size=self.in_size,
fixed_size=self.fixed_size)
def calc_flops(self, x):
assert (x.shape[0] == 1)
num_flops = x.size + 26 * self.channels
num_macs = 0
return num_flops, num_macs
| 84,759 | 32.501976 | 120 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/lwopenpose_cmupan.py | """
Lightweight OpenPose 2D/3D for CMU Panoptic, implemented in Gluon.
Original paper: 'Real-time 2D Multi-Person Pose Estimation on CPU: Lightweight OpenPose,'
https://arxiv.org/abs/1811.12004.
"""
__all__ = ['LwOpenPose', 'lwopenpose2d_mobilenet_cmupan_coco', 'lwopenpose3d_mobilenet_cmupan_coco',
'LwopDecoderFinalBlock']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1, conv1x1_block, conv3x3_block, dwsconv3x3_block
class LwopResBottleneck(HybridBlock):
"""
Bottleneck block for residual path in the residual unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
use_bias : bool, default True
Whether the layer uses a bias vector.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bottleneck_factor : int, default 2
Bottleneck factor.
squeeze_out : bool, default False
Whether to squeeze the output channels.
"""
def __init__(self,
in_channels,
out_channels,
strides,
use_bias=True,
bn_use_global_stats=False,
bottleneck_factor=2,
squeeze_out=False,
**kwargs):
super(LwopResBottleneck, self).__init__(**kwargs)
mid_channels = out_channels // bottleneck_factor if squeeze_out else in_channels // bottleneck_factor
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
use_bias=use_bias,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
strides=strides,
use_bias=use_bias,
bn_use_global_stats=bn_use_global_stats)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
use_bias=use_bias,
activation=None,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class LwopResUnit(HybridBlock):
"""
ResNet-like residual unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
use_bias : bool, default True
Whether the layer uses a bias vector.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bottleneck_factor : int, default 2
Bottleneck factor.
squeeze_out : bool, default False
Whether to squeeze the output channels.
activate : bool, default False
Whether to activate the sum.
"""
def __init__(self,
in_channels,
out_channels,
strides=1,
use_bias=True,
bn_use_global_stats=False,
bottleneck_factor=2,
squeeze_out=False,
activate=False,
**kwargs):
super(LwopResUnit, self).__init__(**kwargs)
self.activate = activate
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
self.body = LwopResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
use_bias=use_bias,
bn_use_global_stats=bn_use_global_stats,
bottleneck_factor=bottleneck_factor,
squeeze_out=squeeze_out)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
use_bias=use_bias,
bn_use_global_stats=bn_use_global_stats,
activation=None)
if self.activate:
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
if self.activate:
x = self.activ(x)
return x
class LwopEncoderFinalBlock(HybridBlock):
"""
Lightweight OpenPose 2D/3D specific encoder final block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats=False,
**kwargs):
super(LwopEncoderFinalBlock, self).__init__(**kwargs)
with self.name_scope():
self.pre_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
use_bias=True,
use_bn=False,
bn_use_global_stats=bn_use_global_stats)
self.body = nn.HybridSequential(prefix="")
for i in range(3):
self.body.add(dwsconv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
dw_use_bn=False,
pw_use_bn=False,
bn_use_global_stats=bn_use_global_stats,
dw_activation=(lambda: nn.ELU()),
pw_activation=(lambda: nn.ELU())))
self.post_conv = conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
use_bias=True,
use_bn=False,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.pre_conv(x)
x = x + self.body(x)
x = self.post_conv(x)
return x
class LwopRefinementBlock(HybridBlock):
"""
Lightweight OpenPose 2D/3D specific refinement block for decoder units.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats=False,
**kwargs):
super(LwopRefinementBlock, self).__init__(**kwargs)
with self.name_scope():
self.pre_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
use_bias=True,
use_bn=False,
bn_use_global_stats=bn_use_global_stats)
self.body = nn.HybridSequential(prefix="")
self.body.add(conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
use_bias=True,
bn_use_global_stats=bn_use_global_stats))
self.body.add(conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
padding=2,
dilation=2,
use_bias=True,
bn_use_global_stats=bn_use_global_stats))
def hybrid_forward(self, F, x):
x = self.pre_conv(x)
x = x + self.body(x)
return x
class LwopDecoderBend(HybridBlock):
"""
Lightweight OpenPose 2D/3D specific decoder bend block.
Parameters:
----------
in_channels : int
Number of input channels.
mid_channels : int
Number of middle channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
mid_channels,
out_channels,
bn_use_global_stats=False,
**kwargs):
super(LwopDecoderBend, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
use_bias=True,
use_bn=False,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
use_bias=True)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class LwopDecoderInitBlock(HybridBlock):
"""
Lightweight OpenPose 2D/3D specific decoder init block.
Parameters:
----------
in_channels : int
Number of input channels.
keypoints : int
Number of keypoints.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
keypoints,
bn_use_global_stats=False,
**kwargs):
super(LwopDecoderInitBlock, self).__init__(**kwargs)
num_heatmap = keypoints
num_paf = 2 * keypoints
bend_mid_channels = 512
with self.name_scope():
self.body = nn.HybridSequential(prefix="")
for i in range(3):
self.body.add(conv3x3_block(
in_channels=in_channels,
out_channels=in_channels,
use_bias=True,
use_bn=False,
bn_use_global_stats=bn_use_global_stats))
self.heatmap_bend = LwopDecoderBend(
in_channels=in_channels,
mid_channels=bend_mid_channels,
out_channels=num_heatmap,
bn_use_global_stats=bn_use_global_stats)
self.paf_bend = LwopDecoderBend(
in_channels=in_channels,
mid_channels=bend_mid_channels,
out_channels=num_paf,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
y = self.body(x)
heatmap = self.heatmap_bend(y)
paf = self.paf_bend(y)
y = F.concat(x, heatmap, paf, dim=1)
return y
class LwopDecoderUnit(HybridBlock):
"""
Lightweight OpenPose 2D/3D specific decoder init.
Parameters:
----------
in_channels : int
Number of input channels.
keypoints : int
Number of keypoints.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
keypoints,
bn_use_global_stats=False,
**kwargs):
super(LwopDecoderUnit, self).__init__(**kwargs)
num_heatmap = keypoints
num_paf = 2 * keypoints
self.features_channels = in_channels - num_heatmap - num_paf
with self.name_scope():
self.body = nn.HybridSequential(prefix="")
for i in range(5):
self.body.add(LwopRefinementBlock(
in_channels=in_channels,
out_channels=self.features_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = self.features_channels
self.heatmap_bend = LwopDecoderBend(
in_channels=self.features_channels,
mid_channels=self.features_channels,
out_channels=num_heatmap,
bn_use_global_stats=bn_use_global_stats)
self.paf_bend = LwopDecoderBend(
in_channels=self.features_channels,
mid_channels=self.features_channels,
out_channels=num_paf,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
features = F.slice_axis(x, axis=1, begin=0, end=self.features_channels)
y = self.body(x)
heatmap = self.heatmap_bend(y)
paf = self.paf_bend(y)
y = F.concat(features, heatmap, paf, dim=1)
return y
class LwopDecoderFeaturesBend(HybridBlock):
"""
Lightweight OpenPose 2D/3D specific decoder 3D features bend.
Parameters:
----------
in_channels : int
Number of input channels.
mid_channels : int
Number of middle channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
mid_channels,
out_channels,
bn_use_global_stats=False,
**kwargs):
super(LwopDecoderFeaturesBend, self).__init__(**kwargs)
with self.name_scope():
self.body = nn.HybridSequential(prefix="")
for i in range(2):
self.body.add(LwopRefinementBlock(
in_channels=in_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = mid_channels
self.features_bend = LwopDecoderBend(
in_channels=mid_channels,
mid_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.body(x)
x = self.features_bend(x)
return x
class LwopDecoderFinalBlock(HybridBlock):
"""
Lightweight OpenPose 2D/3D specific decoder final block for calcualation 3D poses.
Parameters:
----------
in_channels : int
Number of input channels.
keypoints : int
Number of keypoints.
bottleneck_factor : int
Bottleneck factor.
calc_3d_features : bool
Whether to calculate 3D features.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
keypoints,
bottleneck_factor,
calc_3d_features,
bn_use_global_stats=False,
**kwargs):
super(LwopDecoderFinalBlock, self).__init__(**kwargs)
self.num_heatmap_paf = 3 * keypoints
self.calc_3d_features = calc_3d_features
features_out_channels = self.num_heatmap_paf
features_in_channels = in_channels - features_out_channels
if self.calc_3d_features:
with self.name_scope():
self.body = nn.HybridSequential(prefix="")
for i in range(5):
self.body.add(LwopResUnit(
in_channels=in_channels,
out_channels=features_in_channels,
bottleneck_factor=bottleneck_factor,
bn_use_global_stats=bn_use_global_stats))
in_channels = features_in_channels
self.features_bend = LwopDecoderFeaturesBend(
in_channels=features_in_channels,
mid_channels=features_in_channels,
out_channels=features_out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
heatmap_paf_2d = F.slice_axis(x, axis=1, begin=-self.num_heatmap_paf, end=None)
if not self.calc_3d_features:
return heatmap_paf_2d
x = self.body(x)
x = self.features_bend(x)
y = F.concat(heatmap_paf_2d, x, dim=1)
return y
class LwOpenPose(HybridBlock):
"""
Lightweight OpenPose 2D/3D model from 'Real-time 2D Multi-Person Pose Estimation on CPU: Lightweight OpenPose,'
https://arxiv.org/abs/1811.12004.
Parameters:
----------
encoder_channels : list of list of int
Number of output channels for each encoder unit.
encoder_paddings : list of list of int
Padding/dilation value for each encoder unit.
encoder_init_block_channels : int
Number of output channels for the encoder initial unit.
encoder_final_block_channels : int
Number of output channels for the encoder final unit.
refinement_units : int
Number of refinement blocks in the decoder.
calc_3d_features : bool
Whether to calculate 3D features.
return_heatmap : bool, default True
Whether to return only heatmap.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (256, 192)
Spatial size of the expected input image.
keypoints : int, default 19
Number of keypoints.
"""
def __init__(self,
encoder_channels,
encoder_paddings,
encoder_init_block_channels,
encoder_final_block_channels,
refinement_units,
calc_3d_features,
return_heatmap=True,
bn_use_global_stats=False,
in_channels=3,
in_size=(368, 368),
keypoints=19,
**kwargs):
super(LwOpenPose, self).__init__(**kwargs)
assert (in_channels == 3)
self.in_size = in_size
self.keypoints = keypoints
self.return_heatmap = return_heatmap
self.calc_3d_features = calc_3d_features
num_heatmap_paf = 3 * keypoints
with self.name_scope():
self.encoder = nn.HybridSequential(prefix="")
backbone = nn.HybridSequential(prefix="")
backbone.add(conv3x3_block(
in_channels=in_channels,
out_channels=encoder_init_block_channels,
strides=2,
bn_use_global_stats=bn_use_global_stats))
in_channels = encoder_init_block_channels
for i, channels_per_stage in enumerate(encoder_channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
padding = encoder_paddings[i][j]
stage.add(dwsconv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
padding=padding,
dilation=padding,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
backbone.add(stage)
self.encoder.add(backbone)
self.encoder.add(LwopEncoderFinalBlock(
in_channels=in_channels,
out_channels=encoder_final_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = encoder_final_block_channels
self.decoder = nn.HybridSequential(prefix="")
self.decoder.add(LwopDecoderInitBlock(
in_channels=in_channels,
keypoints=keypoints,
bn_use_global_stats=bn_use_global_stats))
in_channels = encoder_final_block_channels + num_heatmap_paf
for i in range(refinement_units):
self.decoder.add(LwopDecoderUnit(
in_channels=in_channels,
keypoints=keypoints,
bn_use_global_stats=bn_use_global_stats))
self.decoder.add(LwopDecoderFinalBlock(
in_channels=in_channels,
keypoints=keypoints,
bottleneck_factor=2,
calc_3d_features=calc_3d_features,
bn_use_global_stats=bn_use_global_stats))
def hybrid_forward(self, F, x):
x = self.encoder(x)
x = self.decoder(x)
if self.return_heatmap:
return x
else:
return x
def get_lwopenpose(calc_3d_features,
keypoints,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create Lightweight OpenPose 2D/3D model with specific parameters.
Parameters:
----------
calc_3d_features : bool, default False
Whether to calculate 3D features.
keypoints : int
Number of keypoints.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
encoder_channels = [[64], [128, 128], [256, 256, 512, 512, 512, 512, 512, 512]]
encoder_paddings = [[1], [1, 1], [1, 1, 1, 2, 1, 1, 1, 1]]
encoder_init_block_channels = 32
encoder_final_block_channels = 128
refinement_units = 1
net = LwOpenPose(
encoder_channels=encoder_channels,
encoder_paddings=encoder_paddings,
encoder_init_block_channels=encoder_init_block_channels,
encoder_final_block_channels=encoder_final_block_channels,
refinement_units=refinement_units,
calc_3d_features=calc_3d_features,
keypoints=keypoints,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def lwopenpose2d_mobilenet_cmupan_coco(keypoints=19, **kwargs):
"""
Lightweight OpenPose 2D model on the base of MobileNet for CMU Panoptic from 'Real-time 2D Multi-Person Pose
Estimation on CPU: Lightweight OpenPose,' https://arxiv.org/abs/1811.12004.
Parameters:
----------
keypoints : int, default 19
Number of keypoints.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_lwopenpose(calc_3d_features=False, keypoints=keypoints, model_name="lwopenpose2d_mobilenet_cmupan_coco",
**kwargs)
def lwopenpose3d_mobilenet_cmupan_coco(keypoints=19, **kwargs):
"""
Lightweight OpenPose 3D model on the base of MobileNet for CMU Panoptic from 'Real-time 2D Multi-Person Pose
Estimation on CPU: Lightweight OpenPose,' https://arxiv.org/abs/1811.12004.
Parameters:
----------
keypoints : int, default 19
Number of keypoints.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_lwopenpose(calc_3d_features=True, keypoints=keypoints, model_name="lwopenpose3d_mobilenet_cmupan_coco",
**kwargs)
def _test():
import numpy as np
import mxnet as mx
in_size = (368, 368)
keypoints = 19
return_heatmap = True
pretrained = False
models = [
(lwopenpose2d_mobilenet_cmupan_coco, "2d"),
(lwopenpose3d_mobilenet_cmupan_coco, "3d"),
]
for model, model_dim in models:
net = model(pretrained=pretrained, in_size=in_size, return_heatmap=return_heatmap)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != lwopenpose2d_mobilenet_cmupan_coco or weight_count == 4091698)
assert (model != lwopenpose3d_mobilenet_cmupan_coco or weight_count == 5085983)
batch = 14
x = mx.nd.random.normal(shape=(batch, 3, in_size[0], in_size[1]), ctx=ctx)
y = net(x)
if model_dim == "2d":
assert (y.shape == (batch, 3 * keypoints, in_size[0] // 8, in_size[0] // 8))
else:
assert (y.shape == (batch, 6 * keypoints, in_size[0] // 8, in_size[0] // 8))
if __name__ == "__main__":
_test()
| 26,308 | 35.138736 | 119 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/rir_cifar.py | """
RiR for CIFAR/SVHN, implemented in Gluon.
Original paper: 'Resnet in Resnet: Generalizing Residual Architectures,' https://arxiv.org/abs/1603.08029.
"""
__all__ = ['CIFARRiR', 'rir_cifar10', 'rir_cifar100', 'rir_svhn', 'RiRFinalBlock']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1, conv3x3, conv1x1_block, conv3x3_block, DualPathSequential
class PostActivation(HybridBlock):
"""
Pure pre-activation block without convolution layer.
Parameters:
----------
in_channels : int
Number of input channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
bn_use_global_stats,
**kwargs):
super(PostActivation, self).__init__(**kwargs)
with self.name_scope():
self.bn = nn.BatchNorm(
in_channels=in_channels,
use_global_stats=bn_use_global_stats)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
x = self.bn(x)
x = self.activ(x)
return x
class RiRUnit(HybridBlock):
"""
RiR unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats,
**kwargs):
super(RiRUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
self.res_pass_conv = conv3x3(
in_channels=in_channels,
out_channels=out_channels,
strides=strides)
self.trans_pass_conv = conv3x3(
in_channels=in_channels,
out_channels=out_channels,
strides=strides)
self.res_cross_conv = conv3x3(
in_channels=in_channels,
out_channels=out_channels,
strides=strides)
self.trans_cross_conv = conv3x3(
in_channels=in_channels,
out_channels=out_channels,
strides=strides)
self.res_postactiv = PostActivation(
in_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
self.trans_postactiv = PostActivation(
in_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
if self.resize_identity:
self.identity_conv = conv1x1(
in_channels=in_channels,
out_channels=out_channels,
strides=strides)
def hybrid_forward(self, F, x_res, x_trans):
if self.resize_identity:
x_res_identity = self.identity_conv(x_res)
else:
x_res_identity = x_res
y_res = self.res_cross_conv(x_res)
y_trans = self.trans_cross_conv(x_trans)
x_res = self.res_pass_conv(x_res)
x_trans = self.trans_pass_conv(x_trans)
x_res = x_res + x_res_identity + y_trans
x_trans = x_trans + y_res
x_res = self.res_postactiv(x_res)
x_trans = self.trans_postactiv(x_trans)
return x_res, x_trans
class RiRInitBlock(HybridBlock):
"""
RiR initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats,
**kwargs):
super(RiRInitBlock, self).__init__(**kwargs)
with self.name_scope():
self.res_conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
self.trans_conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x, _):
x_res = self.res_conv(x)
x_trans = self.trans_conv(x)
return x_res, x_trans
class RiRFinalBlock(HybridBlock):
"""
RiR final block.
"""
def __init__(self):
super(RiRFinalBlock, self).__init__()
def hybrid_forward(self, F, x_res, x_trans):
x = F.concat(x_res, x_trans, dim=1)
return x, None
class CIFARRiR(HybridBlock):
"""
RiR model for CIFAR from 'Resnet in Resnet: Generalizing Residual Architectures,' https://arxiv.org/abs/1603.08029.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final unit.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
bn_use_global_stats=False,
in_channels=3,
in_size=(32, 32),
classes=10,
**kwargs):
super(CIFARRiR, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = DualPathSequential(
return_two=False,
first_ordinals=0,
last_ordinals=0,
prefix="")
self.features.add(RiRInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = DualPathSequential(prefix="stage{}_".format(i + 1))
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
stage.add(RiRUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(RiRFinalBlock())
in_channels = final_block_channels
self.output = nn.HybridSequential(prefix="")
self.output.add(conv1x1_block(
in_channels=in_channels,
out_channels=classes,
bn_use_global_stats=bn_use_global_stats,
activation=None))
self.output.add(nn.AvgPool2D(
pool_size=8,
strides=1))
self.output.add(nn.Flatten())
def hybrid_forward(self, F, x):
x = self.features(x, x)
x = self.output(x)
return x
def get_rir_cifar(classes,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create RiR model for CIFAR with specific parameters.
Parameters:
----------
classes : int
Number of classification classes.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
channels = [[48, 48, 48, 48], [96, 96, 96, 96, 96, 96], [192, 192, 192, 192, 192, 192]]
init_block_channels = 48
final_block_channels = 384
net = CIFARRiR(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
classes=classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def rir_cifar10(classes=10, **kwargs):
"""
RiR model for CIFAR-10 from 'Resnet in Resnet: Generalizing Residual Architectures,'
https://arxiv.org/abs/1603.08029.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_rir_cifar(classes=classes, model_name="rir_cifar10", **kwargs)
def rir_cifar100(classes=100, **kwargs):
"""
RiR model for CIFAR-100 from 'Resnet in Resnet: Generalizing Residual Architectures,'
https://arxiv.org/abs/1603.08029.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_rir_cifar(classes=classes, model_name="rir_cifar100", **kwargs)
def rir_svhn(classes=10, **kwargs):
"""
RiR model for SVHN from 'Resnet in Resnet: Generalizing Residual Architectures,'
https://arxiv.org/abs/1603.08029.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_rir_cifar(classes=classes, model_name="rir_svhn", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
(rir_cifar10, 10),
(rir_cifar100, 100),
(rir_svhn, 10),
]
for model, classes in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != rir_cifar10 or weight_count == 9492980)
assert (model != rir_cifar100 or weight_count == 9527720)
assert (model != rir_svhn or weight_count == 9492980)
x = mx.nd.zeros((1, 3, 32, 32), ctx=ctx)
y = net(x)
assert (y.shape == (1, classes))
if __name__ == "__main__":
_test()
| 12,481 | 31.761155 | 119 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/diapreresnet.py | """
DIA-PreResNet for ImageNet-1K, implemented in Gluon.
Original papers: 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
"""
__all__ = ['DIAPreResNet', 'diapreresnet10', 'diapreresnet12', 'diapreresnet14', 'diapreresnetbc14b', 'diapreresnet16',
'diapreresnet18', 'diapreresnet26', 'diapreresnetbc26b', 'diapreresnet34', 'diapreresnetbc38b',
'diapreresnet50', 'diapreresnet50b', 'diapreresnet101', 'diapreresnet101b', 'diapreresnet152',
'diapreresnet152b', 'diapreresnet200', 'diapreresnet200b', 'diapreresnet269b', 'DIAPreResUnit']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1, DualPathSequential
from .preresnet import PreResBlock, PreResBottleneck, PreResInitBlock, PreResActivation
from .diaresnet import DIAAttention
class DIAPreResUnit(HybridBlock):
"""
DIA-PreResNet unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer of the block.
attention : nn.Module, default None
Attention module.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats,
bottleneck,
conv1_stride,
attention=None,
**kwargs):
super(DIAPreResUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
if bottleneck:
self.body = PreResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
conv1_stride=conv1_stride)
else:
self.body = PreResBlock(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats)
if self.resize_identity:
self.identity_conv = conv1x1(
in_channels=in_channels,
out_channels=out_channels,
strides=strides)
self.attention = attention
def hybrid_forward(self, F, x, hc=None):
identity = x
x, x_pre_activ = self.body(x)
if self.resize_identity:
identity = self.identity_conv(x_pre_activ)
x, hc = self.attention(x, hc)
x = x + identity
return x, hc
class DIAPreResNet(HybridBlock):
"""
DIA-PreResNet model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(DIAPreResNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(PreResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = DualPathSequential(
return_two=False,
prefix="stage{}_".format(i + 1))
attention = DIAAttention(
in_x_features=channels_per_stage[0],
in_h_features=channels_per_stage[0])
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
stage.add(DIAPreResUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
attention=attention))
in_channels = out_channels
self.features.add(stage)
self.features.add(PreResActivation(
in_channels=in_channels,
bn_use_global_stats=bn_use_global_stats))
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_diapreresnet(blocks,
bottleneck=None,
conv1_stride=True,
width_scale=1.0,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create DIA-PreResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
bottleneck : bool, default None
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
width_scale : float, default 1.0
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if bottleneck is None:
bottleneck = (blocks >= 50)
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14 and not bottleneck:
layers = [2, 2, 1, 1]
elif (blocks == 14) and bottleneck:
layers = [1, 1, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif (blocks == 26) and not bottleneck:
layers = [3, 3, 3, 3]
elif (blocks == 26) and bottleneck:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif (blocks == 38) and bottleneck:
layers = [3, 3, 3, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
elif blocks == 269:
layers = [3, 30, 48, 8]
else:
raise ValueError("Unsupported DIA-PreResNet with number of blocks: {}".format(blocks))
if bottleneck:
assert (sum(layers) * 3 + 2 == blocks)
else:
assert (sum(layers) * 2 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [64, 128, 256, 512]
if bottleneck:
bottleneck_factor = 4
channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) if (i != len(channels) - 1) or (j != len(ci) - 1) else cij
for j, cij in enumerate(ci)] for i, ci in enumerate(channels)]
init_block_channels = int(init_block_channels * width_scale)
net = DIAPreResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def diapreresnet10(**kwargs):
"""
DIA-PreResNet-10 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=10, model_name="diapreresnet10", **kwargs)
def diapreresnet12(**kwargs):
"""
DIA-PreResNet-12 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=12, model_name="diapreresnet12", **kwargs)
def diapreresnet14(**kwargs):
"""
DIA-PreResNet-14 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=14, model_name="diapreresnet14", **kwargs)
def diapreresnetbc14b(**kwargs):
"""
DIA-PreResNet-BC-14b model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model (bottleneck compressed).
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=14, bottleneck=True, conv1_stride=False, model_name="diapreresnetbc14b", **kwargs)
def diapreresnet16(**kwargs):
"""
DIA-PreResNet-16 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=16, model_name="diapreresnet16", **kwargs)
def diapreresnet18(**kwargs):
"""
DIA-PreResNet-18 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=18, model_name="diapreresnet18", **kwargs)
def diapreresnet26(**kwargs):
"""
DIA-PreResNet-26 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=26, bottleneck=False, model_name="diapreresnet26", **kwargs)
def diapreresnetbc26b(**kwargs):
"""
DIA-PreResNet-BC-26b model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model (bottleneck compressed).
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=26, bottleneck=True, conv1_stride=False, model_name="diapreresnetbc26b", **kwargs)
def diapreresnet34(**kwargs):
"""
DIA-PreResNet-34 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=34, model_name="diapreresnet34", **kwargs)
def diapreresnetbc38b(**kwargs):
"""
DIA-PreResNet-BC-38b model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
It's an experimental model (bottleneck compressed).
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=38, bottleneck=True, conv1_stride=False, model_name="diapreresnetbc38b", **kwargs)
def diapreresnet50(**kwargs):
"""
DIA-PreResNet-50 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=50, model_name="diapreresnet50", **kwargs)
def diapreresnet50b(**kwargs):
"""
DIA-PreResNet-50 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=50, conv1_stride=False, model_name="diapreresnet50b", **kwargs)
def diapreresnet101(**kwargs):
"""
DIA-PreResNet-101 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=101, model_name="diapreresnet101", **kwargs)
def diapreresnet101b(**kwargs):
"""
DIA-PreResNet-101 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=101, conv1_stride=False, model_name="diapreresnet101b", **kwargs)
def diapreresnet152(**kwargs):
"""
DIA-PreResNet-152 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=152, model_name="diapreresnet152", **kwargs)
def diapreresnet152b(**kwargs):
"""
DIA-PreResNet-152 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=152, conv1_stride=False, model_name="diapreresnet152b", **kwargs)
def diapreresnet200(**kwargs):
"""
DIA-PreResNet-200 model from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=200, model_name="diapreresnet200", **kwargs)
def diapreresnet200b(**kwargs):
"""
DIA-PreResNet-200 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=200, conv1_stride=False, model_name="diapreresnet200b", **kwargs)
def diapreresnet269b(**kwargs):
"""
DIA-PreResNet-269 model with stride at the second convolution in bottleneck block from 'DIANet: Dense-and-Implicit
Attention Network,' https://arxiv.org/abs/1905.10671.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_diapreresnet(blocks=269, conv1_stride=False, model_name="diapreresnet269b", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
diapreresnet10,
diapreresnet12,
diapreresnet14,
diapreresnetbc14b,
diapreresnet16,
diapreresnet18,
diapreresnet26,
diapreresnetbc26b,
diapreresnet34,
diapreresnetbc38b,
diapreresnet50,
diapreresnet50b,
diapreresnet101,
diapreresnet101b,
diapreresnet152,
diapreresnet152b,
diapreresnet200,
diapreresnet200b,
diapreresnet269b,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != diapreresnet10 or weight_count == 6295688)
assert (model != diapreresnet12 or weight_count == 6369672)
assert (model != diapreresnet14 or weight_count == 6665096)
assert (model != diapreresnetbc14b or weight_count == 24016424)
assert (model != diapreresnet16 or weight_count == 7845768)
assert (model != diapreresnet18 or weight_count == 12566408)
assert (model != diapreresnet26 or weight_count == 18837128)
assert (model != diapreresnetbc26b or weight_count == 29946664)
assert (model != diapreresnet34 or weight_count == 22674568)
assert (model != diapreresnetbc38b or weight_count == 35876904)
assert (model != diapreresnet50 or weight_count == 39508520)
assert (model != diapreresnet50b or weight_count == 39508520)
assert (model != diapreresnet101 or weight_count == 58500648)
assert (model != diapreresnet101b or weight_count == 58500648)
assert (model != diapreresnet152 or weight_count == 74144296)
assert (model != diapreresnet152b or weight_count == 74144296)
assert (model != diapreresnet200 or weight_count == 78625320)
assert (model != diapreresnet200b or weight_count == 78625320)
assert (model != diapreresnet269b or weight_count == 116024872)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 23,989 | 35.293495 | 119 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/jasperdr.py | """
Jasper DR (Dense Residual) for ASR, implemented in Gluon.
Original paper: 'Jasper: An End-to-End Convolutional Neural Acoustic Model,' https://arxiv.org/abs/1904.03288.
"""
__all__ = ['jasperdr10x5_en', 'jasperdr10x5_en_nr']
from .jasper import get_jasper
def jasperdr10x5_en(classes=29, **kwargs):
"""
Jasper DR 10x5 model for English language from 'Jasper: An End-to-End Convolutional Neural Acoustic Model,'
https://arxiv.org/abs/1904.03288.
Parameters:
----------
classes : int, default 29
Number of classification classes (number of graphemes).
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_jasper(classes=classes, version=("jasper", "10x5"), use_dr=True, model_name="jasperdr10x5_en",
**kwargs)
def jasperdr10x5_en_nr(classes=29, **kwargs):
"""
Jasper DR 10x5 model for English language (with presence of noise) from 'Jasper: An End-to-End Convolutional Neural
Acoustic Model,' https://arxiv.org/abs/1904.03288.
Parameters:
----------
classes : int, default 29
Number of classification classes (number of graphemes).
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_jasper(classes=classes, version=("jasper", "10x5"), use_dr=True, model_name="jasperdr10x5_en_nr",
**kwargs)
def _calc_width(net):
import numpy as np
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
return weight_count
def _test():
import numpy as np
import mxnet as mx
pretrained = False
audio_features = 64
models = [
jasperdr10x5_en,
jasperdr10x5_en_nr,
]
for model in models:
net = model(
in_channels=audio_features,
pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != jasperdr10x5_en or weight_count == 332632349)
assert (model != jasperdr10x5_en_nr or weight_count == 332632349)
batch = 3
seq_len = np.random.randint(60, 150, batch)
seq_len_max = seq_len.max() + 2
x = mx.nd.random.normal(shape=(batch, audio_features, seq_len_max), ctx=ctx)
x_len = mx.nd.array(seq_len, ctx=ctx, dtype=np.long)
y, y_len = net(x, x_len)
assert (y.shape[:2] == (batch, net.classes))
assert (y.shape[2] in [seq_len_max // 2, seq_len_max // 2 + 1])
if __name__ == "__main__":
_test()
| 3,244 | 30.504854 | 119 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/deeplabv3.py | """
DeepLabv3 for image segmentation, implemented in Gluon.
Original paper: 'Rethinking Atrous Convolution for Semantic Image Segmentation,' https://arxiv.org/abs/1706.05587.
"""
__all__ = ['DeepLabv3', 'deeplabv3_resnetd50b_voc', 'deeplabv3_resnetd101b_voc', 'deeplabv3_resnetd152b_voc',
'deeplabv3_resnetd50b_coco', 'deeplabv3_resnetd101b_coco', 'deeplabv3_resnetd152b_coco',
'deeplabv3_resnetd50b_ade20k', 'deeplabv3_resnetd101b_ade20k', 'deeplabv3_resnetd50b_cityscapes',
'deeplabv3_resnetd101b_cityscapes']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from mxnet.gluon.contrib.nn import HybridConcurrent
from .common import conv1x1, conv1x1_block, conv3x3_block
from .resnetd import resnetd50b, resnetd101b, resnetd152b
class DeepLabv3FinalBlock(HybridBlock):
"""
DeepLabv3 final block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bottleneck_factor : int, default 4
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
bottleneck_factor=4,
**kwargs):
super(DeepLabv3FinalBlock, self).__init__(**kwargs)
assert (in_channels % bottleneck_factor == 0)
mid_channels = in_channels // bottleneck_factor
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels)
self.dropout = nn.Dropout(rate=0.1)
self.conv2 = conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
use_bias=True)
def hybrid_forward(self, F, x, out_size):
x = self.conv1(x)
x = self.dropout(x)
x = self.conv2(x)
x = F.contrib.BilinearResize2D(x, height=out_size[0], width=out_size[1])
return x
class ASPPAvgBranch(HybridBlock):
"""
ASPP branch with average pooling.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
upscale_out_size : tuple of 2 int or None
Spatial size of output image for the bilinear upsampling operation.
"""
def __init__(self,
in_channels,
out_channels,
upscale_out_size,
**kwargs):
super(ASPPAvgBranch, self).__init__(**kwargs)
self.upscale_out_size = upscale_out_size
with self.name_scope():
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels)
def hybrid_forward(self, F, x):
in_size = self.upscale_out_size if self.upscale_out_size is not None else x.shape[2:]
x = F.contrib.AdaptiveAvgPooling2D(x, output_size=1)
x = self.conv(x)
x = F.contrib.BilinearResize2D(x, height=in_size[0], width=in_size[1])
return x
class AtrousSpatialPyramidPooling(HybridBlock):
"""
Atrous Spatial Pyramid Pooling (ASPP) module.
Parameters:
----------
in_channels : int
Number of input channels.
upscale_out_size : tuple of 2 int
Spatial size of the input tensor for the bilinear upsampling operation.
"""
def __init__(self,
in_channels,
upscale_out_size,
**kwargs):
super(AtrousSpatialPyramidPooling, self).__init__(**kwargs)
atrous_rates = [12, 24, 36]
assert (in_channels % 8 == 0)
mid_channels = in_channels // 8
project_in_channels = 5 * mid_channels
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels))
for atrous_rate in atrous_rates:
self.branches.add(conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels,
padding=atrous_rate,
dilation=atrous_rate))
self.branches.add(ASPPAvgBranch(
in_channels=in_channels,
out_channels=mid_channels,
upscale_out_size=upscale_out_size))
self.conv = conv1x1_block(
in_channels=project_in_channels,
out_channels=mid_channels)
self.dropout = nn.Dropout(rate=0.5)
def hybrid_forward(self, F, x):
x = self.branches(x)
x = self.conv(x)
x = self.dropout(x)
return x
class DeepLabv3(HybridBlock):
"""
DeepLabv3 model from 'Rethinking Atrous Convolution for Semantic Image Segmentation,'
https://arxiv.org/abs/1706.05587.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
backbone_out_channels : int, default 2048
Number of output channels form feature extractor.
aux : bool, default False
Whether to output an auxiliary result.
fixed_size : bool, default True
Whether to expect fixed spatial size of input image.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (480, 480)
Spatial size of the expected input image.
classes : int, default 21
Number of segmentation classes.
"""
def __init__(self,
backbone,
backbone_out_channels=2048,
aux=False,
fixed_size=True,
in_channels=3,
in_size=(480, 480),
classes=21,
**kwargs):
super(DeepLabv3, self).__init__(**kwargs)
assert (in_channels > 0)
assert ((in_size[0] % 8 == 0) and (in_size[1] % 8 == 0))
self.in_size = in_size
self.classes = classes
self.aux = aux
self.fixed_size = fixed_size
with self.name_scope():
self.backbone = backbone
pool_out_size = (self.in_size[0] // 8, self.in_size[1] // 8) if fixed_size else None
self.pool = AtrousSpatialPyramidPooling(
in_channels=backbone_out_channels,
upscale_out_size=pool_out_size)
pool_out_channels = backbone_out_channels // 8
self.final_block = DeepLabv3FinalBlock(
in_channels=pool_out_channels,
out_channels=classes,
bottleneck_factor=1)
if self.aux:
aux_out_channels = backbone_out_channels // 2
self.aux_block = DeepLabv3FinalBlock(
in_channels=aux_out_channels,
out_channels=classes,
bottleneck_factor=4)
def hybrid_forward(self, F, x):
in_size = self.in_size if self.fixed_size else x.shape[2:]
x, y = self.backbone(x)
x = self.pool(x)
x = self.final_block(x, in_size)
if self.aux:
y = self.aux_block(y, in_size)
return x, y
else:
return x
def get_deeplabv3(backbone,
classes,
aux=False,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create DeepLabv3 model with specific parameters.
Parameters:
----------
backbone : nn.Sequential
Feature extractor.
classes : int
Number of segmentation classes.
aux : bool, default False
Whether to output an auxiliary result.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
net = DeepLabv3(
backbone=backbone,
classes=classes,
aux=aux,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx,
ignore_extra=True)
return net
def deeplabv3_resnetd50b_voc(pretrained_backbone=False, classes=21, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-50b for Pascal VOC from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,)).features[:-1]
return get_deeplabv3(backbone=backbone, classes=classes, aux=aux, model_name="deeplabv3_resnetd50b_voc", **kwargs)
def deeplabv3_resnetd101b_voc(pretrained_backbone=False, classes=21, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-101b for Pascal VOC from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,)).features[:-1]
return get_deeplabv3(backbone=backbone, classes=classes, aux=aux, model_name="deeplabv3_resnetd101b_voc", **kwargs)
def deeplabv3_resnetd152b_voc(pretrained_backbone=False, classes=21, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-152b for Pascal VOC from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnetd152b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,)).features[:-1]
return get_deeplabv3(backbone=backbone, classes=classes, aux=aux, model_name="deeplabv3_resnetd152b_voc", **kwargs)
def deeplabv3_resnetd50b_coco(pretrained_backbone=False, classes=21, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-50b for COCO from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,)).features[:-1]
return get_deeplabv3(backbone=backbone, classes=classes, aux=aux, model_name="deeplabv3_resnetd50b_coco", **kwargs)
def deeplabv3_resnetd101b_coco(pretrained_backbone=False, classes=21, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-101b for COCO from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,)).features[:-1]
return get_deeplabv3(backbone=backbone, classes=classes, aux=aux, model_name="deeplabv3_resnetd101b_coco", **kwargs)
def deeplabv3_resnetd152b_coco(pretrained_backbone=False, classes=21, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-152b for COCO from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 21
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnetd152b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,)).features[:-1]
return get_deeplabv3(backbone=backbone, classes=classes, aux=aux, model_name="deeplabv3_resnetd152b_coco", **kwargs)
def deeplabv3_resnetd50b_ade20k(pretrained_backbone=False, classes=150, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-50b for ADE20K from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 150
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,)).features[:-1]
return get_deeplabv3(backbone=backbone, classes=classes, aux=aux, model_name="deeplabv3_resnetd50b_ade20k",
**kwargs)
def deeplabv3_resnetd101b_ade20k(pretrained_backbone=False, classes=150, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-101b for ADE20K from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 150
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,)).features[:-1]
return get_deeplabv3(backbone=backbone, classes=classes, aux=aux, model_name="deeplabv3_resnetd101b_ade20k",
**kwargs)
def deeplabv3_resnetd50b_cityscapes(pretrained_backbone=False, classes=19, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-50b for Cityscapes from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 19
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,)).features[:-1]
return get_deeplabv3(backbone=backbone, classes=classes, aux=aux, model_name="deeplabv3_resnetd50b_cityscapes",
**kwargs)
def deeplabv3_resnetd101b_cityscapes(pretrained_backbone=False, classes=19, aux=True, **kwargs):
"""
DeepLabv3 model on the base of ResNet(D)-101b for Cityscapes from 'Rethinking Atrous Convolution for Semantic Image
Segmentation,' https://arxiv.org/abs/1706.05587.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load the pretrained weights for feature extractor.
classes : int, default 19
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,)).features[:-1]
return get_deeplabv3(backbone=backbone, classes=classes, aux=aux, model_name="deeplabv3_resnetd101b_cityscapes",
**kwargs)
def _test():
import numpy as np
import mxnet as mx
in_size = (480, 480)
aux = False
pretrained = False
models = [
(deeplabv3_resnetd50b_voc, 21),
(deeplabv3_resnetd101b_voc, 21),
(deeplabv3_resnetd152b_voc, 21),
(deeplabv3_resnetd50b_coco, 21),
(deeplabv3_resnetd101b_coco, 21),
(deeplabv3_resnetd152b_coco, 21),
(deeplabv3_resnetd50b_ade20k, 150),
(deeplabv3_resnetd101b_ade20k, 150),
(deeplabv3_resnetd50b_cityscapes, 19),
(deeplabv3_resnetd101b_cityscapes, 19),
]
for model, classes in models:
net = model(pretrained=pretrained, in_size=in_size, aux=aux)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
if aux:
assert (model != deeplabv3_resnetd50b_voc or weight_count == 42127850)
assert (model != deeplabv3_resnetd101b_voc or weight_count == 61119978)
assert (model != deeplabv3_resnetd152b_voc or weight_count == 76763626)
assert (model != deeplabv3_resnetd50b_coco or weight_count == 42127850)
assert (model != deeplabv3_resnetd101b_coco or weight_count == 61119978)
assert (model != deeplabv3_resnetd152b_coco or weight_count == 76763626)
assert (model != deeplabv3_resnetd50b_ade20k or weight_count == 42194156)
assert (model != deeplabv3_resnetd101b_ade20k or weight_count == 61186284)
assert (model != deeplabv3_resnetd50b_cityscapes or weight_count == 42126822)
assert (model != deeplabv3_resnetd101b_cityscapes or weight_count == 61118950)
else:
assert (model != deeplabv3_resnetd50b_voc or weight_count == 39762645)
assert (model != deeplabv3_resnetd101b_voc or weight_count == 58754773)
assert (model != deeplabv3_resnetd152b_voc or weight_count == 74398421)
assert (model != deeplabv3_resnetd50b_coco or weight_count == 39762645)
assert (model != deeplabv3_resnetd101b_coco or weight_count == 58754773)
assert (model != deeplabv3_resnetd152b_coco or weight_count == 74398421)
assert (model != deeplabv3_resnetd50b_ade20k or weight_count == 39795798)
assert (model != deeplabv3_resnetd101b_ade20k or weight_count == 58787926)
assert (model != deeplabv3_resnetd50b_cityscapes or weight_count == 39762131)
assert (model != deeplabv3_resnetd101b_cityscapes or weight_count == 58754259)
x = mx.nd.zeros((1, 3, in_size[0], in_size[1]), ctx=ctx)
ys = net(x)
y = ys[0] if aux else ys
assert ((y.shape[0] == x.shape[0]) and (y.shape[1] == classes) and (y.shape[2] == x.shape[2]) and
(y.shape[3] == x.shape[3]))
if __name__ == "__main__":
_test()
| 22,813 | 38.884615 | 120 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/fpenet.py | """
FPENet for image segmentation, implemented in Gluon.
Original paper: 'Feature Pyramid Encoding Network for Real-time Semantic Segmentation,'
https://arxiv.org/abs/1909.08599.
"""
__all__ = ['FPENet', 'fpenet_cityscapes']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1, conv1x1_block, conv3x3_block, SEBlock, InterpolationBlock, MultiOutputSequential
class FPEBlock(HybridBlock):
"""
FPENet block.
Parameters:
----------
channels : int
Number of input/output channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
channels,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(FPEBlock, self).__init__(**kwargs)
dilations = [1, 2, 4, 8]
assert (channels % len(dilations) == 0)
mid_channels = channels // len(dilations)
with self.name_scope():
self.blocks = nn.HybridSequential(prefix="")
for i, dilation in enumerate(dilations):
self.blocks.add(conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
groups=mid_channels,
dilation=dilation,
padding=dilation,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
def hybrid_forward(self, F, x):
xs = F.split(x, axis=1, num_outputs=len(self.blocks._children))
ys = []
for bi, xsi in zip(self.blocks._children.values(), xs):
if len(ys) == 0:
ys.append(bi(xsi))
else:
ys.append(bi(xsi + ys[-1]))
x = F.concat(*ys, dim=1)
return x
class FPEUnit(HybridBlock):
"""
FPENet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bottleneck_factor : int
Bottleneck factor.
use_se : bool
Whether to use SE-module.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bottleneck_factor,
use_se,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(FPEUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
self.use_se = use_se
mid1_channels = in_channels * bottleneck_factor
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid1_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.block = FPEBlock(channels=mid1_channels)
self.conv2 = conv1x1_block(
in_channels=mid1_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=None)
if self.use_se:
self.se = SEBlock(channels=out_channels)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=None)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.conv1(x)
x = self.block(x)
x = self.conv2(x)
if self.use_se:
x = self.se(x)
x = x + identity
x = self.activ(x)
return x
class FPEStage(HybridBlock):
"""
FPENet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
layers : int
Number of layers.
use_se : bool
Whether to use SE-module.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
layers,
use_se,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(FPEStage, self).__init__(**kwargs)
self.use_block = (layers > 1)
with self.name_scope():
if self.use_block:
self.down = FPEUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=2,
bottleneck_factor=4,
use_se=use_se,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.blocks = nn.HybridSequential(prefix="")
for i in range(layers - 1):
self.blocks.add(FPEUnit(
in_channels=out_channels,
out_channels=out_channels,
strides=1,
bottleneck_factor=1,
use_se=use_se,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
else:
self.down = FPEUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=1,
bottleneck_factor=1,
use_se=use_se,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
def hybrid_forward(self, F, x):
x = self.down(x)
if self.use_block:
y = self.blocks(x)
x = x + y
return x
class MEUBlock(HybridBlock):
"""
FPENet specific mutual embedding upsample (MEU) block.
Parameters:
----------
in_channels_high : int
Number of input channels for x_high.
in_channels_low : int
Number of input channels for x_low.
out_channels : int
Number of output channels.
out_size : tuple of 2 int
Spatial size of output image.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels_high,
in_channels_low,
out_channels,
out_size,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(MEUBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv_high = conv1x1_block(
in_channels=in_channels_high,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=None)
self.conv_low = conv1x1_block(
in_channels=in_channels_low,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=None)
self.conv_w_high = conv1x1(
in_channels=out_channels,
out_channels=out_channels)
self.conv_w_low = conv1x1(
in_channels=1,
out_channels=1)
self.sigmoid = nn.Activation("sigmoid")
self.relu = nn.Activation("relu")
self.up = InterpolationBlock(scale_factor=2, out_size=out_size)
def hybrid_forward(self, F, x_high, x_low):
x_high = self.conv_high(x_high)
x_low = self.conv_low(x_low)
w_high = F.contrib.AdaptiveAvgPooling2D(x_high, output_size=1)
w_high = self.conv_w_high(w_high)
w_high = self.relu(w_high)
w_high = self.sigmoid(w_high)
w_low = x_low.mean(axis=1, keepdims=True)
w_low = self.conv_w_low(w_low)
w_low = self.sigmoid(w_low)
x_high = self.up(x_high)
x_high = F.broadcast_mul(x_high, w_low)
x_low = F.broadcast_mul(x_low, w_high)
out = x_high + x_low
return out
class FPENet(HybridBlock):
"""
FPENet model from 'Feature Pyramid Encoding Network for Real-time Semantic Segmentation,'
https://arxiv.org/abs/1909.08599.
Parameters:
----------
layers : list of int
Number of layers for each unit.
channels : list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
meu_channels : list of int
Number of output channels for MEU blocks.
use_se : bool
Whether to use SE-module.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
aux : bool, default False
Whether to output an auxiliary result.
fixed_size : bool, default False
Whether to expect fixed spatial size of input image.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (1024, 2048)
Spatial size of the expected input image.
classes : int, default 19
Number of segmentation classes.
"""
def __init__(self,
layers,
channels,
init_block_channels,
meu_channels,
use_se,
bn_use_global_stats=False,
bn_cudnn_off=False,
aux=False,
fixed_size=False,
in_channels=3,
in_size=(1024, 2048),
classes=19,
**kwargs):
super(FPENet, self).__init__(**kwargs)
assert (aux is not None)
assert (fixed_size is not None)
assert ((in_size[0] % 8 == 0) and (in_size[1] % 8 == 0))
self.in_size = in_size
self.classes = classes
self.fixed_size = fixed_size
with self.name_scope():
self.stem = conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
strides=2,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
in_channels = init_block_channels
self.encoder = MultiOutputSequential(return_last=False)
for i, (layers_i, out_channels) in enumerate(zip(layers, channels)):
stage = FPEStage(
in_channels=in_channels,
out_channels=out_channels,
layers=layers_i,
use_se=use_se,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
stage.do_output = True
self.encoder.add(stage)
in_channels = out_channels
self.meu1 = MEUBlock(
in_channels_high=channels[-1],
in_channels_low=channels[-2],
out_channels=meu_channels[0],
out_size=((in_size[0] // 4, in_size[1] // 4) if fixed_size else None),
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.meu2 = MEUBlock(
in_channels_high=meu_channels[0],
in_channels_low=channels[-3],
out_channels=meu_channels[1],
out_size=((in_size[0] // 2, in_size[1] // 2) if fixed_size else None),
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
in_channels = meu_channels[1]
self.classifier = conv1x1(
in_channels=in_channels,
out_channels=classes,
use_bias=True)
self.up = InterpolationBlock(
scale_factor=2,
out_size=(in_size if fixed_size else None))
def hybrid_forward(self, F, x):
x = self.stem(x)
y = self.encoder(x)
x = self.meu1(y[2], y[1])
x = self.meu2(x, y[0])
x = self.classifier(x)
x = self.up(x)
return x
def get_fpenet(model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create FPENet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
width = 16
channels = [int(width * (2 ** i)) for i in range(3)]
init_block_channels = width
layers = [1, 3, 9]
meu_channels = [64, 32]
use_se = False
net = FPENet(
layers=layers,
channels=channels,
init_block_channels=init_block_channels,
meu_channels=meu_channels,
use_se=use_se,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx,
ignore_extra=True)
return net
def fpenet_cityscapes(classes=19, **kwargs):
"""
FPENet model for Cityscapes from 'Feature Pyramid Encoding Network for Real-time Semantic Segmentation,'
https://arxiv.org/abs/1909.08599.
Parameters:
----------
classes : int, default 19
Number of segmentation classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_fpenet(classes=classes, model_name="fpenet_cityscapes", **kwargs)
def _calc_width(net):
import numpy as np
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
return weight_count
def _test():
import mxnet as mx
pretrained = False
fixed_size = True
in_size = (1024, 2048)
classes = 19
models = [
fpenet_cityscapes,
]
for model in models:
net = model(pretrained=pretrained, in_size=in_size, fixed_size=fixed_size)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net.hybridize()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != fpenet_cityscapes or weight_count == 115125)
batch = 4
x = mx.nd.random.normal(shape=(batch, 3, in_size[0], in_size[1]), ctx=ctx)
y = net(x)
assert (y.shape == (batch, classes, in_size[0], in_size[1]))
if __name__ == "__main__":
_test()
| 16,864 | 32.662675 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/irevnet.py | """
i-RevNet for ImageNet-1K, implemented in Gluon.
Original paper: 'i-RevNet: Deep Invertible Networks,' https://arxiv.org/abs/1802.07088.
"""
__all__ = ['IRevNet', 'irevnet301', 'IRevDownscale', 'IRevSplitBlock', 'IRevMergeBlock']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv3x3, pre_conv3x3_block, DualPathSequential
class IRevDualPathSequential(DualPathSequential):
"""
An invertible sequential container for hybrid blocks with dual inputs/outputs.
Blocks will be executed in the order they are added.
Parameters:
----------
return_two : bool, default True
Whether to return two output after execution.
first_ordinals : int, default 0
Number of the first blocks with single input/output.
last_ordinals : int, default 0
Number of the final blocks with single input/output.
dual_path_scheme : function
Scheme of dual path response for a block.
dual_path_scheme_ordinal : function
Scheme of dual path response for an ordinal block.
last_noninvertible : int, default 0
Number of the final blocks skipped during inverse.
"""
def __init__(self,
return_two=True,
first_ordinals=0,
last_ordinals=0,
dual_path_scheme=(lambda block, x1, x2: block(x1, x2)),
dual_path_scheme_ordinal=(lambda block, x1, x2: (block(x1), x2)),
last_noninvertible=0,
**kwargs):
super(IRevDualPathSequential, self).__init__(
return_two=return_two,
first_ordinals=first_ordinals,
last_ordinals=last_ordinals,
dual_path_scheme=dual_path_scheme,
dual_path_scheme_ordinal=dual_path_scheme_ordinal,
**kwargs)
self.last_noninvertible = last_noninvertible
def inverse(self, x1, x2=None):
length = len(self._children.values())
for i, block in enumerate(reversed(self._children.values())):
if i < self.last_noninvertible:
pass
elif (i < self.last_ordinals) or (i >= length - self.first_ordinals):
x1, x2 = self.dual_path_scheme_ordinal(block.inverse, x1, x2)
else:
x1, x2 = self.dual_path_scheme(block.inverse, x1, x2)
if self.return_two:
return x1, x2
else:
return x1
class IRevDownscale(HybridBlock):
"""
i-RevNet specific downscale (so-called psi-block).
Parameters:
----------
scale : int
Scale (downscale) value.
"""
def __init__(self,
scale,
**kwargs):
super(IRevDownscale, self).__init__(**kwargs)
self.scale = scale
def hybrid_forward(self, F, x):
batch, x_channels, x_height, x_width = x.shape
y_channels = x_channels * self.scale * self.scale
assert (x_height % self.scale == 0)
y_height = x_height // self.scale
y = x.transpose(axes=(0, 2, 3, 1))
d2_split_seq = y.split(axis=2, num_outputs=(y.shape[2] // self.scale))
d2_split_seq = [t.reshape(batch, y_height, y_channels) for t in d2_split_seq]
y = F.stack(*d2_split_seq, axis=1)
y = y.transpose(axes=(0, 3, 2, 1))
return y
def inverse(self, y):
import mxnet.ndarray as F
scale_sqr = self.scale * self.scale
batch, y_channels, y_height, y_width = y.shape
assert (y_channels % scale_sqr == 0)
x_channels = y_channels // scale_sqr
x_height = y_height * self.scale
x_width = y_width * self.scale
x = y.transpose(axes=(0, 2, 3, 1))
x = x.reshape(batch, y_height, y_width, scale_sqr, x_channels)
d3_split_seq = x.split(axis=3, num_outputs=(x.shape[3] // self.scale))
d3_split_seq = [t.reshape(batch, y_height, x_width, x_channels) for t in d3_split_seq]
x = F.stack(*d3_split_seq, axis=0)
x = x.swapaxes(0, 1).transpose(axes=(0, 2, 1, 3, 4)).reshape(batch, x_height, x_width, x_channels)
x = x.transpose(axes=(0, 3, 1, 2))
return x
class IRevInjectivePad(HybridBlock):
"""
i-RevNet channel zero padding block.
Parameters:
----------
padding : int
Size of the padding.
"""
def __init__(self,
padding,
**kwargs):
super(IRevInjectivePad, self).__init__(**kwargs)
self.padding = padding
def hybrid_forward(self, F, x):
x = x.transpose(axes=(0, 2, 1, 3))
x = F.pad(x, mode="constant", pad_width=(0, 0, 0, 0, 0, self.padding, 0, 0), constant_value=0)
x = x.transpose(axes=(0, 2, 1, 3))
return x
def inverse(self, x):
return x[:, :x.shape[1] - self.padding, :, :]
class IRevSplitBlock(HybridBlock):
"""
iRevNet split block.
"""
def __init__(self,
**kwargs):
super(IRevSplitBlock, self).__init__(**kwargs)
def hybrid_forward(self, F, x, _):
x1, x2 = F.split(x, axis=1, num_outputs=2)
return x1, x2
def inverse(self, x1, x2):
import mxnet.ndarray as F
x = F.concat(x1, x2, dim=1)
return x, None
class IRevMergeBlock(HybridBlock):
"""
iRevNet merge block.
"""
def __init__(self,
**kwargs):
super(IRevMergeBlock, self).__init__(**kwargs)
def hybrid_forward(self, F, x1, x2):
x = F.concat(x1, x2, dim=1)
return x, x
def inverse(self, x, _):
import mxnet.ndarray as F
x1, x2 = F.split(x, axis=1, num_outputs=2)
return x1, x2
class IRevBottleneck(HybridBlock):
"""
iRevNet bottleneck block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the branch convolution layers.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
preactivate : bool
Whether use pre-activation for the first convolution block.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats,
preactivate,
**kwargs):
super(IRevBottleneck, self).__init__(**kwargs)
mid_channels = out_channels // 4
with self.name_scope():
if preactivate:
self.conv1 = pre_conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats)
else:
self.conv1 = conv3x3(
in_channels=in_channels,
out_channels=mid_channels,
strides=strides)
self.conv2 = pre_conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats)
self.conv3 = pre_conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class IRevUnit(HybridBlock):
"""
iRevNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the branch convolution layers.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
preactivate : bool
Whether use pre-activation for the first convolution block.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats,
preactivate,
**kwargs):
super(IRevUnit, self).__init__(**kwargs)
if not preactivate:
in_channels = in_channels // 2
padding = 2 * (out_channels - in_channels)
self.do_padding = (padding != 0) and (strides == 1)
self.do_downscale = (strides != 1)
with self.name_scope():
if self.do_padding:
self.pad = IRevInjectivePad(padding)
self.bottleneck = IRevBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
preactivate=preactivate)
if self.do_downscale:
self.psi = IRevDownscale(strides)
def hybrid_forward(self, F, x1, x2):
if self.do_padding:
x = F.concat(x1, x2, dim=1)
x = self.pad(x)
x1, x2 = F.split(x, axis=1, num_outputs=2)
fx2 = self.bottleneck(x2)
if self.do_downscale:
x1 = self.psi(x1)
x2 = self.psi(x2)
y1 = fx2 + x1
return x2, y1
def inverse(self, x2, y1):
import mxnet.ndarray as F
if self.do_downscale:
x2 = self.psi.inverse(x2)
fx2 = - self.bottleneck(x2)
x1 = fx2 + y1
if self.do_downscale:
x1 = self.psi.inverse(x1)
if self.do_padding:
x = F.concat(x1, x2, dim=1)
x = self.pad.inverse(x)
x1, x2 = F.split(x, axis=1, num_outputs=2)
return x1, x2
class IRevPostActivation(HybridBlock):
"""
iRevNet specific post-activation block.
Parameters:
----------
in_channels : int
Number of input channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
bn_use_global_stats=False,
**kwargs):
super(IRevPostActivation, self).__init__(**kwargs)
with self.name_scope():
self.bn = nn.BatchNorm(
in_channels=in_channels,
use_global_stats=bn_use_global_stats)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
x = self.bn(x)
x = self.activ(x)
return x
class IRevNet(HybridBlock):
"""
i-RevNet model from 'i-RevNet: Deep Invertible Networks,' https://arxiv.org/abs/1802.07088.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final unit.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(IRevNet, self).__init__(**kwargs)
assert (in_channels > 0)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = IRevDualPathSequential(
first_ordinals=1,
last_ordinals=2,
last_noninvertible=2)
self.features.add(IRevDownscale(scale=2))
in_channels = init_block_channels
self.features.add(IRevSplitBlock())
for i, channels_per_stage in enumerate(channels):
stage = IRevDualPathSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) else 1
preactivate = not ((i == 0) and (j == 0))
stage.add(IRevUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
preactivate=preactivate))
in_channels = out_channels
self.features.add(stage)
in_channels = final_block_channels
self.features.add(IRevMergeBlock())
self.features.add(IRevPostActivation(
in_channels=in_channels,
bn_use_global_stats=bn_use_global_stats))
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x, return_out_bij=False):
x, out_bij = self.features(x)
x = self.output(x)
if return_out_bij:
return x, out_bij
else:
return x
def inverse(self, out_bij):
x, _ = self.features.inverse(out_bij)
return x
def get_irevnet(blocks,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create i-RevNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if blocks == 301:
layers = [6, 16, 72, 6]
else:
raise ValueError("Unsupported i-RevNet with number of blocks: {}".format(blocks))
assert (sum(layers) * 3 + 1 == blocks)
channels_per_layers = [24, 96, 384, 1536]
init_block_channels = 12
final_block_channels = 3072
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = IRevNet(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ignore_extra=True,
ctx=ctx)
return net
def irevnet301(**kwargs):
"""
i-RevNet-301 model from 'i-RevNet: Deep Invertible Networks,' https://arxiv.org/abs/1802.07088.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_irevnet(blocks=301, model_name="irevnet301", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
irevnet301,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != irevnet301 or weight_count == 125120356)
x = mx.nd.random.randn(2, 3, 224, 224, ctx=ctx)
y = net(x)
assert (y.shape == (2, 1000))
y, out_bij = net(x, True)
x_ = net.inverse(out_bij)
assert (x_.shape == (2, 3, 224, 224))
assert ((np.max(np.abs(x.asnumpy() - x_.asnumpy())) < 1e-4) or (np.max(np.abs(y.asnumpy()) > 1e10)))
if __name__ == "__main__":
_test()
| 17,306 | 31.59322 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/model_store.py | """
Model store which provides pretrained models.
"""
__all__ = ['get_model_file']
import os
import zipfile
import logging
from mxnet.gluon.utils import download, check_sha1
_model_sha1 = {name: (error, checksum, repo_release_tag) for name, error, checksum, repo_release_tag in [
('alexnet', '1610', '4dd7cfb6275229c3b3889ec7ad29f8d48a499193', 'v0.0.481'),
('alexnetb', '1705', '0181007ac2ba5d5c051346af1eea4a00c36f34e9', 'v0.0.485'),
('zfnet', '1678', '3299fdce9712697f9e03e1a0cf741745553a28cf', 'v0.0.395'),
('zfnetb', '1459', '7a654810eced689323e414030165cf1392c9684f', 'v0.0.400'),
('vgg11', '1016', '3d78e0ec95d358577acf8b2e2f768a72ec319ee3', 'v0.0.381'),
('vgg13', '0950', 'd2bcaaf3704afb47b2818066255b3de65d0c03e1', 'v0.0.388'),
('vgg16', '0832', '22fe503aa438ebfd1f3128b676db21a06de3cd59', 'v0.0.401'),
('vgg19', '0767', 'e198aa1f6519b3331e5ebbe782ca35fd2aca6213', 'v0.0.420'),
('bn_vgg11', '0934', '3f79cab1e9e0bab0d57c0f80a6c9782e5cdc765d', 'v0.0.339'),
('bn_vgg13', '0887', '540243b0a3eb2ae3974c2d75cf82e655fa4f0dda', 'v0.0.353'),
('bn_vgg16', '0757', '90441925c7c19c9db6bf96824c2440774c0e54df', 'v0.0.359'),
('bn_vgg19', '0689', 'cd8f4229e5e757ba951afc6eb1a4ec7a471022f7', 'v0.0.360'),
('bn_vgg11b', '0975', '685ae89dcf3916b9c6e887d4c5bc441a34253744', 'v0.0.407'),
('bn_vgg13b', '0912', 'fc678318391d45465bda4aa17744dc0d148135e3', 'v0.0.488'),
('bn_vgg16b', '0775', '77dad99b4f72176870655ffbf59e96f3b9570a0b', 'v0.0.489'),
('bn_vgg19b', '0735', '8d9a132bfd9230304e588ec159170ee3173d64ba', 'v0.0.490'),
('bninception', '0754', '75225419bae387931f6c8ccc19dc48fb1cc8cdae', 'v0.0.405'),
('resnet10', '1220', '83ebb0937d85142c3f827be56f08a57a5996c90b', 'v0.0.569'),
('resnet12', '1203', 'a41948541130b9ebf8285412b38c668198e4ad4f', 'v0.0.485'),
('resnet14', '1086', '5d9f22a7aa6c821eb69fc043af2da040f36110eb', 'v0.0.491'),
('resnetbc14b', '1033', '4ff348bebc7696cd219be605668bb76546dd9641', 'v0.0.481'),
('resnet16', '0978', '2c28373c9ce1f50ff6a4b47a16a3d1bc2e557c75', 'v0.0.493'),
('resnet18_wd4', '1740', 'a74ea15d056a84133e02706a6c7f8ed8f50c8462', 'v0.0.262'),
('resnet18_wd2', '1284', '9a5154065311c8ffbbc57b20a443b205c7a910fa', 'v0.0.263'),
('resnet18_w3d4', '1066', '1a574a4198a5bbf01572c2b3f091eb824ff8196e', 'v0.0.266'),
('resnet18', '0867', '711ed8ab624c4c580e90321989aef6174ad2991d', 'v0.0.478'),
('resnet26', '0823', 'a2746eb21d73c3c85edacabe36d680988986f890', 'v0.0.489'),
('resnetbc26b', '0758', '2b5e8d0888936a340ea13c7e8ba30b237cd62f1c', 'v0.0.313'),
('resnet34', '0743', '5cdeeccda6f87fe13aed279213006061a8b42037', 'v0.0.291'),
('resnetbc38b', '0672', '820944641ba54f4aaa43d2a305ab52b9dcb740c7', 'v0.0.328'),
('resnet50', '0604', 'a71d1d2a8e8e4259742bbd67c386623233b57c6c', 'v0.0.329'),
('resnet50b', '0611', 'ca12f8d804000bf5202e2e3838dec7ef6b772149', 'v0.0.308'),
('resnet101', '0516', '75a3105c609aedb89d63dd3dc47b578f41fff6be', 'v0.0.499'),
('resnet101b', '0512', 'af5c4233b28c8b7acd3b3ebe02f9f2eda2c77824', 'v0.0.357'),
('resnet152', '0444', '15f2dd80f964225e685e7564cecd04911feb97ee', 'v0.0.518'),
('resnet152b', '0429', '45a3ad0f989852a4456c907fa3b40b00dd24937c', 'v0.0.517'),
('preresnet10', '1401', '2b96c0818dbabc422e98d8fbfc9b684c023922ed', 'v0.0.249'),
('preresnet12', '1321', 'b628efb5415784075e18b6734b1ba1e5c7280dee', 'v0.0.257'),
('preresnet14', '1218', 'd65fa6287414d9412e34ac0df6921eaa5646a2b6', 'v0.0.260'),
('preresnetbc14b', '1151', 'c712a235b75ad4956411bab265dfd924c748726e', 'v0.0.315'),
('preresnet16', '1081', '5b00b55f74adb9ee4a6ba5f946aafd48b4d8aa47', 'v0.0.261'),
('preresnet18_wd4', '1778', '3d949d1ae20b9188a423b56a1f7a89b4bcecc3d2', 'v0.0.272'),
('preresnet18_wd2', '1319', '63e55c24bc0ae93a8f8daefa4b35dc3e70147f65', 'v0.0.273'),
('preresnet18_w3d4', '1068', 'eb5698616757fd0947851f62c33fc4d7b4a5f23a', 'v0.0.274'),
('preresnet18', '0951', '71279a0b7339f1efd12bed737219a9ed76175a9d', 'v0.0.140'),
('preresnet26', '0834', 'c2ecba0948934c28d459b7f87fbc1489420fd4fb', 'v0.0.316'),
('preresnetbc26b', '0786', '265f591f320db0915c18c16f4ed0e2e53ee46567', 'v0.0.325'),
('preresnet34', '0751', 'ba9c829e72d54f8b02cf32ea202c195d36568467', 'v0.0.300'),
('preresnetbc38b', '0633', '809d2defea82276fdd7ff2faafc1f6ffe57c93b5', 'v0.0.348'),
('preresnet50', '0620', '50f13b2d3fd197c8aa721745adaf2d6615fd8c16', 'v0.0.330'),
('preresnet50b', '0632', '951de2dc558f94f489ce62fedf979ccc08361641', 'v0.0.307'),
('preresnet101', '0534', 'ea9a1724662744fe349c0aa8dd0ec42708fe88c7', 'v0.0.504'),
('preresnet101b', '0540', '3839a4733a8a614bb6b7b4f555759bb5b8013d42', 'v0.0.351'),
('preresnet152', '0446', '3b41bd93a7a2807e8cc88ae75ec0cde69af1e786', 'v0.0.510'),
('preresnet152b', '0438', 'ebf71d023e88d006c55946e3c6cf38c5d0cffeb2', 'v0.0.523'),
('preresnet200b', '0446', '70135e6618bd8e870574a2667d3ec592238b3a3c', 'v0.0.529'),
('preresnet269b', '0501', '6e56119dc52a38af690bb41d4ae1683007558233', 'v0.0.545'),
('resnext14_16x4d', '1223', '1f8072e8d01d1427941a06bbca896211e98e2b75', 'v0.0.370'),
('resnext14_32x2d', '1247', '2ca8cc2544045c21d0a7ca740483097491ba0855', 'v0.0.371'),
('resnext14_32x4d', '1110', '9be6190e328c15a06703be3ba922d707c2f4d8e7', 'v0.0.327'),
('resnext26_32x2d', '0850', 'a1fb4451be6336d9f648ccc2c2dedacc5704904a', 'v0.0.373'),
('resnext26_32x4d', '0721', '5264d7efd606e1c95a2480050e9f03a7a2f02b09', 'v0.0.332'),
('resnext50_32x4d', '0545', '748e53b31fe716b5fdd059107d22bdfec3a31839', 'v0.0.498'),
('resnext101_32x4d', '0418', 'c07faa66647bd25dd222b44d8782c59fcc2e3708', 'v0.0.530'),
('resnext101_64x4d', '0439', '178e79057f27afec04219aa1a1a96abbbd8763a9', 'v0.0.544'),
('seresnet10', '1169', '675d4b5bbaaab1b87988df96819cd19e5323512c', 'v0.0.486'),
('seresnet12', '1176', 'df10dd88759750bb042ce7b09dd8a78f32d78e12', 'v0.0.544'),
('seresnet14', '1095', '579e2fecfe37d1c9422f6521fef610bfde6fcaaa', 'v0.0.545'),
('seresnet16', '0972', 'ef50864856c2120082e3db7d4193f31ec77624c6', 'v0.0.545'),
('seresnet18', '0920', '85a6b1da19645419cc3075852588cc7e7da5715f', 'v0.0.355'),
('seresnet26', '0803', '9f9004192240ae0125399d2f6acbb5359027039d', 'v0.0.363'),
('seresnetbc26b', '0682', '15ae6e19b1626107029df18bf3f5140e6fcb2b02', 'v0.0.366'),
('seresnetbc38b', '0575', 'f80f0c3c2612e1334204df1575b8a7cd18f851ff', 'v0.0.374'),
('seresnet50', '0560', 'e75ef498abfc021f356378b2c806de8927287fe7', 'v0.0.441'),
('seresnet50b', '0533', '0d8f0d23bb980621095e41de69e3a68d7aaeba45', 'v0.0.387'),
('seresnet101', '0441', 'f9cb9df623683520522c5fe8577e8a93cf253f46', 'v0.0.533'),
('seresnet101b', '0462', '59fae71a5db6ad1f1b5a79f7339920aa1191ed70', 'v0.0.460'),
('seresnet152', '0430', 'c712f55410938861c32740fe93770b0d54e094a3', 'v0.0.538'),
('sepreresnet10', '1221', 'c3ab94ee5c938f53a8a61849be3a463458444a1f', 'v0.0.544'),
('sepreresnet12', '1180', 'd6b7260b4931e8806368c42b8bb605b9a8afaa23', 'v0.0.543'),
('sepreresnet16', '0956', 'b5e4e06f6f5394f7557986193700a8ecf23ffdc7', 'v0.0.543'),
('sepreresnet18', '0881', 'b018c6e38601b0719445e302ea64196924319814', 'v0.0.543'),
('sepreresnet26', '0804', 'a2e48457a44958ed7f20940997f419080b1d14e8', 'v0.0.543'),
('sepreresnetbc26b', '0636', '33c94c9dd2986d0643f7c432d5203294ecf2124e', 'v0.0.399'),
('sepreresnetbc38b', '0563', 'd8f0fbd35b840743e312b9ec944c7fc141824ace', 'v0.0.409'),
('sepreresnet50b', '0532', '5b620ff7175c674ef41647e2e79992dceefeec19', 'v0.0.461'),
('seresnext50_32x4d', '0433', 'd74d1d0a5bd1449562e9f1de92b1389c647fdd13', 'v0.0.505'),
('seresnext101_32x4d', '0444', '3c89aec5b98c1bfca13bc8c21e07dba82243c012', 'v0.0.529'),
('seresnext101_64x4d', '0408', '2e039a419e4eb84ce93d1515027099c4dc13f5a1', 'v0.0.561'),
('senet16', '0806', 'ba26802160725af926e5a3217f8848bd3a6599fd', 'v0.0.341'),
('senet28', '0591', 'd5297a35a2e56ecc892499c1bd4373125a40b783', 'v0.0.356'),
('senet154', '0440', 'c0e2d2b9e70894e28e4f957296229bdd89b70607', 'v0.0.522'),
('resnestabc14', '0634', '4b0cbe8c59e9d764027f51670096037e2f058970', 'v0.0.493'),
('resnesta18', '0689', '8f37b6927751b27a72c1b8c625de265da9b31570', 'v0.0.489'),
('resnestabc26', '0470', 'f88d49d7bd6cdf1f448afdf4bc5dadd9921798dd', 'v0.0.495'),
('resnesta50', '0438', '6ce54a97d6e6fe8aa66755669b8f47a0790bfeb6', 'v0.0.531'),
('resnesta101', '0399', 'ab6c6f89407d7b2cf89406f7bb62a48e86d7cabc', 'v0.0.465'),
('resnesta152', '0451', '532c448de0011e90924b3c1e829f9525c6a5420e', 'v0.0.540'),
('resnesta200', '0340', '3bd1f0c8d9a2862b89590c1c490a38d6d982522c', 'v0.0.465'),
('resnesta269', '0336', '8333862a0c016432f6cd5b45f7e9de7ee6e3f319', 'v0.0.465'),
('ibn_resnet50', '0559', '0f75710a144ea1483e6235f6909f8b8c3555ec01', 'v0.0.495'),
('ibn_resnet101', '0489', 'db938be9060c0ea48913fa0fa9794bf6bcacea7f', 'v0.0.552'),
('ibnb_resnet50', '0579', '146aa6e143d582cd33af23c942e3e0b2fe152817', 'v0.0.552'),
('ibn_resnext101_32x4d', '0487', '1398597e25f0be2d7b05f190c5c53f7b8d5265e6', 'v0.0.553'),
('ibn_densenet121', '0646', '82ee3ff44fd308107ec07d759c52a99e94af7041', 'v0.0.493'),
('ibn_densenet169', '0608', 'b509f33947b2f205f03e49ce2d5ee87855bbf708', 'v0.0.500'),
('airnet50_1x64d_r2', '0523', '1f982e0e8b3af40a5d67ca854f18ca837aa332f4', 'v0.0.522'),
('airnet50_1x64d_r16', '0544', '09a9f13b9d5f3e27eb26271070cc4bf8dd72cf9f', 'v0.0.519'),
('airnext50_32x4d_r2', '0504', '664dd077a978562a376e8ab70b5d740893873111', 'v0.0.521'),
('bam_resnet50', '0538', 'fa612c3da552cd26094634c359413db69d0ef97b', 'v0.0.499'),
('cbam_resnet50', '0488', 'ebd4af235d763f4ecce6dd4e09b508ba61b561f7', 'v0.0.537'),
('scnet50', '0511', '359d35d017e838d3c3c2bdf1cc83074610dc3c5b', 'v0.0.493'),
('scnet101', '0446', 'bc5cade042e78813db4ce5878d733daa0ce7f89d', 'v0.0.507'),
('scneta50', '0459', 'c1f6f0286ed942bbc468395b82b7be84312f3c73', 'v0.0.509'),
('regnetx002', '1038', '7800b310f45b4666ef6c862bc8a2573f65ddaa40', 'v0.0.475'),
('regnetx004', '0855', 'b933a72fe7304a31391a9e9fcdf7ffc47ea05353', 'v0.0.479'),
('regnetx006', '0756', 'd41aa087bd288266105142b88b03b67d74352a46', 'v0.0.482'),
('regnetx008', '0724', '79309908dee31eda64e824a9b3bd33c0afaaf5a8', 'v0.0.482'),
('regnetx016', '0613', '018dbe2d89d2bac26f41d98b09ba57b049ed4cfe', 'v0.0.486'),
('regnetx032', '0568', '6d4372fcf0b9d6e3edefa99e72dd411b6a0c676c', 'v0.0.492'),
('regnetx040', '0469', 'c22092c7ceeac713a9102c697f23bec0b7cfaec0', 'v0.0.495'),
('regnetx064', '0458', '473342937e02dce6244a62780f98aed1f5eb831d', 'v0.0.535'),
('regnetx080', '0466', '4086910ad9df1693db658c86f874f686a279175c', 'v0.0.515'),
('regnetx120', '0518', 'ea20b368214230ce65c14218aedba07b68235e38', 'v0.0.542'),
('regnetx160', '0456', '941840a38b20e5b5c6ca092bed3f2ea0ff602895', 'v0.0.532'),
('regnetx320', '0394', 'a120c8d2d181dacffde8a3029292ee59da12e9be', 'v0.0.548'),
('regnety002', '0953', 'b37fcac05e59ba5e751701da8e81195bbfbf3db8', 'v0.0.476'),
('regnety004', '0747', '5626bdf45eaf0f23ddc6e1b68f6ad2db7ca119cf', 'v0.0.481'),
('regnety006', '0697', '81372679b5f9601a5bc72caa13aff378d2ac4233', 'v0.0.483'),
('regnety008', '0645', 'd92881be768a267f1cd2b540d087884bbe93f644', 'v0.0.483'),
('regnety016', '0568', 'c4541a25e92ebf31d9bddb4975738c08fe929836', 'v0.0.486'),
('regnety032', '0413', '9066698526cbc930706fe00b21ca56c31ad7e2e4', 'v0.0.473'),
('regnety040', '0467', '6039a215ee79a7855156c5166df4c6b34f8d501d', 'v0.0.494'),
('regnety064', '0445', '8ae16f971eacad369df091e68c26e63b8c6da9a5', 'v0.0.513'),
('regnety080', '0436', '4cd7fc61d54ec63bfeff11246e8258188351e7ed', 'v0.0.516'),
('regnety120', '0431', 'effa35b601ffbdced20342d9bfe3917a8279880a', 'v0.0.526'),
('regnety160', '0430', '8273156944dea5a439ef55e7ed84a10524be090c', 'v0.0.527'),
('regnety320', '0373', 'd26a5f80c1d67e3527ddbdce75683370c5799e06', 'v0.0.550'),
('pyramidnet101_a360', '0520', '3a98a2bfc4e74b00b5fff20783613281121a6d37', 'v0.0.507'),
('diracnet18v2', '1117', '27601f6fa54e3b10d77981f30650d7a9d4bce91e', 'v0.0.111'),
('diracnet34v2', '0946', '1faa6f1245e152d1a3e12de4b5dc1ba554bc3bb8', 'v0.0.111'),
('crunet56', '0536', 'd7112ed431630f4162fb2ebe7a7c0666fa1718a8', 'v0.0.558'),
('densenet121', '0685', 'd3a1fae8b311343498f736e494d60d32e35debfb', 'v0.0.314'),
('densenet161', '0592', '29897d410ea5ae427278df060de578911df74667', 'v0.0.432'),
('densenet169', '0605', '9c045c864828e773f92f998199821fc0c21e0eb4', 'v0.0.406'),
('densenet201', '0590', '89aa8c295b21fdd682df0027d2232e6dabf2cace', 'v0.0.426'),
('condensenet74_c4_g4', '0864', 'cde68fa2fcc9197e336717a17753a15a6efd7596', 'v0.0.4'),
('condensenet74_c8_g8', '1049', '4cf4a08e7fb46f5821049dcae97ae442b0ceb546', 'v0.0.4'),
('peleenet', '0979', '758d3cf992a6c92731069be091be2e8ebd3209e2', 'v0.0.496'),
('wrn50_2', '0606', '5ff344cae22c8ce3f21e042be5a5d899681d89a0', 'v0.0.520'),
('drnc26', '0711', 'e69a4e7bc94aab58e05880c886e8e829584845c3', 'v0.0.508'),
('drnc42', '0614', '6ee5008a3e66476380f4fadf3cf2633c32a596c9', 'v0.0.556'),
('drnc58', '0515', '418d18b26f32347e695b85a60d2bf658409be28d', 'v0.0.559'),
('drnd22', '0744', 'aecf15fc2171d29d8ea765afa540e4ddb40a9b19', 'v0.0.498'),
('drnd38', '0624', '4a86d6ebd970e02792068c46c80ae00686d759cc', 'v0.0.552'),
('drnd54', '0497', '117ca29b47a6e640269d455dfcc12e9958f5f1e1', 'v0.0.554'),
('drnd105', '0487', '52286b345e48cc873bbc0239cdd91b03beae655d', 'v0.0.564'),
('dpn68', '0658', '07251919c08640c94375670cbc5f0fbc312ed59b', 'v0.0.310'),
('dpn98', '0422', '1ace57dc702d5b6ca7eccb657036f682605d7efc', 'v0.0.540'),
('dpn131', '0477', 'e814a53cc6cddc0b6f2a11393a88c44723a8ec0c', 'v0.0.534'),
('darknet_tiny', '1746', '16501793621fbcb137f2dfb901760c1f621fa5ec', 'v0.0.69'),
('darknet_ref', '1668', '3011b4e14b629f80da54ab57bef305d588f748ab', 'v0.0.64'),
('darknet53', '0550', '1d0b4f620071d544a3a1ccbe437267b8925ecc63', 'v0.0.501'),
('irevnet301', '0735', '4378cc1061da0377a3c7fc00c6be49c3875c997a', 'v0.0.564'),
('bagnet9', '2536', '6b5d69dac8fd780e9ac26b2b964370445662c610', 'v0.0.553'),
('bagnet17', '1523', 'cc7b9a74ec742972fc289686bdaf5b1f5731121f', 'v0.0.558'),
('bagnet33', '1041', '3b20fa3a31aa08f216d7091749f59154b6357397', 'v0.0.561'),
('dla34', '0705', '557c5f4f1db66481af6101c75d9ba52b486eda25', 'v0.0.486'),
('dla46c', '1286', '5b38b67fecf2d701b736eb23e1301b6dd7eb5fb9', 'v0.0.282'),
('dla46xc', '1225', 'e570f5f00a098b0de34e657f9d8caeda524d39f3', 'v0.0.293'),
('dla60', '0554', '88b141c4ca81598dbe4333bd4ddd5a1554772348', 'v0.0.494'),
('dla60x', '0553', '58924af84faf6ac0d980b047ccb505619925d97d', 'v0.0.493'),
('dla60xc', '1074', '1b4e4048847e1ba060eb76538ee09e760f40be11', 'v0.0.289'),
('dla102', '0517', '0e5d954cee3bb260a679425524deab61871bd0bf', 'v0.0.505'),
('dla102x', '0470', 'ea82787ce2b3c79cff32ccf54461507cc09c58ce', 'v0.0.528'),
('dla102x2', '0423', 'dde259b3525fb6dae7e445f6e534a13159b3b365', 'v0.0.542'),
('dla169', '0460', '71971da4e881084851c9b581e719ce4edfb8292d', 'v0.0.539'),
('fishnet150', '0466', 'ed21862d14bb0a4e9d1723b7c639e455a7b141c0', 'v0.0.502'),
('espnetv2_wd2', '1971', '2821c339eb68154129e2864f1b5d74d876a08d77', 'v0.0.567'),
('espnetv2_w1', '1383', '3e031b749057f0237b3ebd7954b175b4bb13200f', 'v0.0.569'),
('espnetv2_w5d4', '1226', '2a498c6d631c54dfacdd5cf9b4c6a07a6db82b2d', 'v0.0.564'),
('espnetv2_w3d2', '1086', 'e869dabdd427a4ab38016d375d5e1b2f29758cde', 'v0.0.566'),
('espnetv2_w2', '0941', 'ef6b1cc026609da7a8df81360e36ecb04985ad28', 'v0.0.566'),
('dicenet_wd5', '3051', '46077eac47e2a299dc1d4edc0128bd3cbd8e9ea9', 'v0.0.563'),
('dicenet_wd2', '2308', 'c03d6d00b8f9ecc8ad87c1ee4bd82a0291a0af06', 'v0.0.561'),
('dicenet_w3d4', '1618', 'eefcffc69e24e6ba0df06db03d0fef8be6afdfe1', 'v0.0.567'),
('dicenet_w1', '1411', '93e2e0df3b9cb62c8ba08d3f3d61237e20fce9e2', 'v0.0.513'),
('dicenet_w5d4', '1251', '710737608fb6e2282cdd3903d4a703eb1989b594', 'v0.0.515'),
('dicenet_w3d2', '1144', 'bb2a902d7adbe96472157e131153f48dfea9f37f', 'v0.0.522'),
('dicenet_w7d8', '1081', '37b9276b8b97c87554652d6963a566cbd189b054', 'v0.0.527'),
('dicenet_w2', '0915', 'c301319d2d2867f155227389ea7402106858c6d4', 'v0.0.569'),
('hrnet_w18_small_v1', '0873', '1060c1c562770adb94115de1cad797684dbb5703', 'v0.0.492'),
('hrnet_w18_small_v2', '0602', '1f319e1b1990818754b97104467cfecf3401ae4e', 'v0.0.499'),
('hrnetv2_w18', '0500', '0a70090294c726c1f303e9114d23c9373695eb44', 'v0.0.508'),
('hrnetv2_w30', '0508', 'eb6afc492537295615dc465236934a9a970c1bef', 'v0.0.525'),
('hrnetv2_w32', '0496', '9c6c47dcce100ff006509ed559158862a53436a6', 'v0.0.528'),
('hrnetv2_w40', '0481', '2382694cceff60b32b4702e64945706f183e3e1c', 'v0.0.534'),
('hrnetv2_w44', '0486', 'f5882024ac9513c2d6c2b41bc774862e392f69ad', 'v0.0.541'),
('hrnetv2_w48', '0484', '936bb78f8c187ca3cc96c7564fa3ff8ad9cb68a6', 'v0.0.541'),
('hrnetv2_w64', '0478', '4c18c51411db532c3b8168f0a1ae3e461e703d68', 'v0.0.543'),
('vovnet27s', '0980', '2a44d455a86e740bd1be61d204553af213ca3ac6', 'v0.0.551'),
('vovnet39', '0548', '20b60ee6bb8c59c684f8ffed7fbda3d76b1a7280', 'v0.0.493'),
('vovnet57', '0510', 'ed3cad779b94c4f4f531d6c37f90f1a5209d3b1c', 'v0.0.505'),
('selecsls42b', '0596', 'f5a35c74880fbe94fbe3770a96968fc81186b42b', 'v0.0.493'),
('selecsls60', '0511', '960edec5159b56bdba4ce606df203c8ce14cb8ba', 'v0.0.496'),
('selecsls60b', '0537', '7f83801b1c158502d93a4523bdecda43017448d5', 'v0.0.495'),
('hardnet39ds', '0864', '72e8423ee0b496c10b48ae687a417385d9667394', 'v0.0.485'),
('hardnet68ds', '0738', '012bf3ac31f38c78d5cdef1367cc3c27447236af', 'v0.0.487'),
('hardnet68', '0702', '6667306df893290d38510a76fd42ec82e05e2f68', 'v0.0.557'),
('hardnet85', '0572', '3baa0a7dd204196fd1afa631cf6de082a5cc0a36', 'v0.0.495'),
('squeezenet_v1_0', '1734', 'e6f8b0e8253cef1c5c071dfaf2df5fdfc6a64f8c', 'v0.0.128'),
('squeezenet_v1_1', '1739', 'd7a1483aaa1053c7cd0cf08529b2b87ed2781b35', 'v0.0.88'),
('squeezeresnet_v1_0', '1767', '66474b9b6a771055b28c37b70621c026a1ef6ef4', 'v0.0.178'),
('squeezeresnet_v1_1', '1784', '26064b82773e7a7175d6038976a73abfcd5ed2be', 'v0.0.70'),
('sqnxt23_w1', '1866', '73b700c40de5f7be9d2cf4ed30cc8935c670a3c3', 'v0.0.171'),
('sqnxt23v5_w1', '1743', '7a83722e7d362cef950d8534020f837caf9e6314', 'v0.0.172'),
('sqnxt23_w3d2', '1321', '4d733bcd19f1e502ebc46b52f0b69d959636902e', 'v0.0.210'),
('sqnxt23v5_w3d2', '1268', '4f98bbd3841d8d09a067100841f64ce3eccf184a', 'v0.0.212'),
('sqnxt23_w2', '1063', '95d9b55a5e857298bdb7974db6e3dbd9ecc94401', 'v0.0.240'),
('sqnxt23v5_w2', '1024', '707246f323bc95d0ea2d5608e9e85ae9fe59773a', 'v0.0.216'),
('shufflenet_g1_wd4', '3677', 'ee58f36811d023e1b2e651469c470e588c93f9d3', 'v0.0.134'),
('shufflenet_g3_wd4', '3617', 'bd08e3ed6aff4993cf5363fe8acaf0b22394bea0', 'v0.0.135'),
('shufflenet_g1_wd2', '2238', 'f77dcd18d3b759a3046bd4a2443c40e4ff455313', 'v0.0.174'),
('shufflenet_g3_wd2', '2060', 'ea6737a54bce651a0e8c0b533b982799842cb1c8', 'v0.0.167'),
('shufflenet_g1_w3d4', '1675', '2f1530aa72ee04e3599c5296b590a835d9d50e7f', 'v0.0.218'),
('shufflenet_g3_w3d4', '1609', 'e008e926f370af28e587f349384238d240a0fc02', 'v0.0.219'),
('shufflenet_g1_w1', '1350', '01934ee8f4bf7eaf4e36dd6442debb84ca2a2849', 'v0.0.223'),
('shufflenet_g2_w1', '1332', 'f5a1479fd8523032ee17a4de00fefd33ff4d31e6', 'v0.0.241'),
('shufflenet_g3_w1', '1329', 'ac58d62c5f277c0e9e5a119cc1f48cb1fcfc8306', 'v0.0.244'),
('shufflenet_g4_w1', '1310', '73c039ebf56f9561dd6eecc4cbad1ab1db168ed1', 'v0.0.245'),
('shufflenet_g8_w1', '1319', '9a50ddd9ce67ec697e3ed085d6c39e3d265f5719', 'v0.0.250'),
('shufflenetv2_wd2', '1830', '156953de22d0e749c987da4a58e0e53a5fb18291', 'v0.0.90'),
('shufflenetv2_w1', '1123', '27435039ab7794c86ceab11bd93a19a5ecab78d2', 'v0.0.133'),
('shufflenetv2_w3d2', '0913', 'f132506c9fa5f0eb27398f9936b53423d0cd5b66', 'v0.0.288'),
('shufflenetv2_w2', '0823', '2d67ac62057103fd2ed4790ea0058e0922abdd0f', 'v0.0.301'),
('shufflenetv2b_wd2', '1782', '845a9c43cf4a9873f89c6116634e74329b977e64', 'v0.0.157'),
('shufflenetv2b_w1', '1101', 'f679702f7c626161413320160c6c9c199de9b667', 'v0.0.161'),
('shufflenetv2b_w3d2', '0879', '4022da3a5922127b1acf5327bd9f1d4d55726e05', 'v0.0.203'),
('shufflenetv2b_w2', '0810', '7429df751916bf24bd7fb86bc137ae36275b9d19', 'v0.0.242'),
('menet108_8x1_g3', '2030', 'aa07f925180834389cfd3bf50cb22d2501225118', 'v0.0.89'),
('menet128_8x1_g4', '1913', '0c890a76fb23c0af50fdec076cb16d0f0ee70355', 'v0.0.103'),
('menet160_8x1_g8', '2028', '4f28279a94e631f6a51735de5ea29703cca69845', 'v0.0.154'),
('menet228_12x1_g3', '1289', '2dc2eec7c9ebb41c459450e1843503b5ac7ecb3a', 'v0.0.131'),
('menet256_12x1_g4', '1216', '7caf63d15190648e266a4e7520c3ad677716f388', 'v0.0.152'),
('menet348_12x1_g3', '0936', '62c72b0b56460f062d4da7155bd64a524f42fb88', 'v0.0.173'),
('menet352_12x1_g8', '1167', '5892fea4e44eb27814a9b092a1a06eb81cea7844', 'v0.0.198'),
('menet456_24x1_g3', '0780', '7a89b32c89f878ac63fc96ddc71cb1a5e91c84d6', 'v0.0.237'),
('mobilenet_wd4', '2218', '3185cdd29b3b964ad51fdd7820bd65f091cf281f', 'v0.0.62'),
('mobilenet_wd2', '1330', '94f13ae1375b48892d8ecbb4a253bb583fe27277', 'v0.0.156'),
('mobilenet_w3d4', '1051', '6361d4b4192b5fc68f3409100d825e8edb28876b', 'v0.0.130'),
('mobilenet_w1', '0865', 'eafd91e9369abb09726f2168aba24453b17fc22e', 'v0.0.155'),
('mobilenetb_wd4', '2165', '2070764e0b3be74922eb5fa0a4342c693821ba90', 'v0.0.481'),
('mobilenetb_wd2', '1271', '799ef980b2726a77d4b68d99f520d9d6bc7d86dc', 'v0.0.480'),
('mobilenetb_w3d4', '1020', 'b01c8bacda6f8e26b34a0313a4dc3883511760f7', 'v0.0.481'),
('mobilenetb_w1', '0788', '82664eb4c1f2ddd0ac163f50263237f7667223f3', 'v0.0.489'),
('fdmobilenet_wd4', '3053', 'd4f18e5b4ed63e5426eafbf5db7f8e2a97c28581', 'v0.0.177'),
('fdmobilenet_wd2', '1969', '242b9fa82d54f54f08b4bdbb194b7c89030e7bc4', 'v0.0.83'),
('fdmobilenet_w3d4', '1601', 'cb10c3e129706d3023d752e7402965af08f91ca7', 'v0.0.159'),
('fdmobilenet_w1', '1312', '95fa0092aac013c88243771faf66ef1134b7574d', 'v0.0.162'),
('mobilenetv2_wd4', '2412', 'd92b5b2dbb52e27354ddd673e6fd240a0cf27175', 'v0.0.137'),
('mobilenetv2_wd2', '1442', 'd7c586c716e3ea85e793f7c5aaf9cae2a907117b', 'v0.0.170'),
('mobilenetv2_w3d4', '1044', '768454f4bdaae337c180bb81248b8c5b8d31040b', 'v0.0.230'),
('mobilenetv2_w1', '0864', '6e58b1cb96852e4c6de6fc9cd11241384af21df9', 'v0.0.213'),
('mobilenetv2b_wd4', '2338', '77ba7e8d41542d311e240dab75e4d29fa0677fb9', 'v0.0.483'),
('mobilenetv2b_wd2', '1373', '3bfc8a592a0881c2cb025f52a09fb5057a7896be', 'v0.0.486'),
('mobilenetv2b_w3d4', '1064', '5d4dc4e5622043697382272183a3d0bd43dbc218', 'v0.0.483'),
('mobilenetv2b_w1', '0884', 'ab0ea3993e7c533f0aea5793331dc6302d715e9c', 'v0.0.483'),
('mobilenetv3_large_w1', '0729', 'db741a9938acc8a5fd9544aaf53b41aebb98e021', 'v0.0.491'),
('igcv3_wd4', '2830', '71abf6e0b6bff1d3a3938bfea7c752b59ac05e9d', 'v0.0.142'),
('igcv3_wd2', '1703', '145b7089e1d0e0ce88f17393a357d5bb4ae37734', 'v0.0.132'),
('igcv3_w3d4', '1096', '3c7c86fc43df2e5cf95a451ebe07fccf2d9dc076', 'v0.0.207'),
('igcv3_w1', '0900', 'e2c3da1cffd8e42da7a052b80db2f86758c8d35b', 'v0.0.243'),
('mnasnet_b1', '0723', 'a6f74cf912fa5b1ee4bb9825f3143a0c1ced03be', 'v0.0.493'),
('mnasnet_a1', '0705', '3efe98a3bd6ea0a8cb0902a4dba424c134145d5f', 'v0.0.486'),
('darts', '0756', 'c2c7c33ba60d1052f95bcae72128fc47b1214cff', 'v0.0.485'),
('proxylessnas_cpu', '0750', '256da7c8a05cd87a59e30e314b22dc1d4565946e', 'v0.0.324'),
('proxylessnas_gpu', '0724', 'd9ce80964e37fb30bddcc552f1d68361b1a94873', 'v0.0.333'),
('proxylessnas_mobile', '0780', 'b8bb5a64f333562475dcfc09eeb7e603d6e66afb', 'v0.0.326'),
('proxylessnas_mobile14', '0651', 'f08baec85343104994b821581cde3ee965a2c593', 'v0.0.331'),
('fbnet_cb', '0761', '3db688f2fa465bc93bc546b4432389fe33aec5b3', 'v0.0.486'),
('xception', '0511', '9755eb77589d627d816fe9806a2b2aa931b6c2f6', 'v0.0.544'),
('inceptionv3', '0533', '4a05a7ffcb5963d44678933596ef85a0f724ebab', 'v0.0.552'),
('inceptionv4', '0488', 'a828ae6ccccb3178257d20e5f17cc8c6ac4348cc', 'v0.0.543'),
('inceptionresnetv1', '0481', '3cc3b4959349e56d6b29619b07ae020e19039f67', 'v0.0.552'),
('inceptionresnetv2', '0470', '4ea29355ae39ececb733e949dfdcbdff72272559', 'v0.0.547'),
('polynet', '0453', '742803144e5a2a6148212570726350da09adf3f6', 'v0.0.96'),
('nasnet_4a1056', '0790', 'f89dd74f47e42c35c9a1182f248df1d319524db7', 'v0.0.495'),
('nasnet_6a4032', '0424', '73cca5fee009db77412c5fca7c826b3563752757', 'v0.0.101'),
('pnasnet5large', '0428', '998a548f44ac1b1ac6c4959a721f2675ab5c48b9', 'v0.0.114'),
('spnasnet', '0776', '09cc881e024d69ab3bd88bef332becb6147a0651', 'v0.0.490'),
('efficientnet_b0', '0722', '041a8346ad6a13dbb66384d9a41ed20d959d3e77', 'v0.0.364'),
('efficientnet_b1', '0626', '455dcb2a05a1295c8f6b728d4f6c72c507e1369a', 'v0.0.376'),
('efficientnet_b0b', '0670', '8892ba581b0d81dbc8fe56c49d81d3dd007b1db8', 'v0.0.403'),
('efficientnet_b1b', '0565', 'c29a1b67804b70856ed3cc329256b80e3afc04ad', 'v0.0.403'),
('efficientnet_b2b', '0516', '7532826e5c14f7ade9e8ea9ac92044d817575b06', 'v0.0.403'),
('efficientnet_b3b', '0431', '1e342ec2160e6de813f9bd4d0ab9ce3b5749780e', 'v0.0.403'),
('efficientnet_b4b', '0376', 'b60e177974539fc6dcc9fef3b90591bfc9949514', 'v0.0.403'),
('efficientnet_b5b', '0334', 'cd70ae717ddca72430efe91cf7a3c4e28bcd61ac', 'v0.0.403'),
('efficientnet_b6b', '0312', 'f581d9f046032e28e532082fa49bfd373952db4f', 'v0.0.403'),
('efficientnet_b7b', '0311', '2b8a6040588aea44b57df89e2d9239d906737508', 'v0.0.403'),
('efficientnet_b0c', '0646', '81eabd2992ba7bb80c1c1a7e20373e7c65aa1286', 'v0.0.433'),
('efficientnet_b1c', '0555', '10b5589de6ee9af3c67f0ae35a424b4adc0a9e35', 'v0.0.433'),
('efficientnet_b2c', '0489', '6f649ece72d0334e5191da78767f2ac9149e85f0', 'v0.0.433'),
('efficientnet_b3c', '0434', 'e1e2a1b7f3457bdd8f46a5858472ad4acd3d2362', 'v0.0.433'),
('efficientnet_b4c', '0359', 'cdb2012d6688b0208527d36817589095a1db1031', 'v0.0.433'),
('efficientnet_b5c', '0302', '3240f368eb5e7ed78b9ac0d68800fbea9b220e9b', 'v0.0.433'),
('efficientnet_b6c', '0285', 'e71a1ccc3e876a7d64818c83518dd0e64c630d3e', 'v0.0.433'),
('efficientnet_b7c', '0277', 'feea7daf3478645131c94319c71141df559dce19', 'v0.0.433'),
('efficientnet_b8c', '0270', '050ec6358583d0a48c74b02563474ecc1d9dacba', 'v0.0.433'),
('efficientnet_edge_small_b', '0629', '5b398abc73c4c4870d88c62452ff919bec2440c9', 'v0.0.434'),
('efficientnet_edge_medium_b', '0553', '0b3c86d49b3684d19e6589030aeceb918faa648c', 'v0.0.434'),
('efficientnet_edge_large_b', '0477', '055436da0fa440933b906c528cb34b200e28f73c', 'v0.0.434'),
('mixnet_s', '0703', '135aa0426712a9f60afe2cfff2df9607f3fc2d68', 'v0.0.493'),
('mixnet_m', '0631', '0881aba9281e3cae3e7cddd75d385c3cccdf7e25', 'v0.0.493'),
('mixnet_l', '0557', '94cbf10cb34c3e3940117d86c28bcc6dbfe9e005', 'v0.0.500'),
('resneta10', '1159', 'a66e01d9f567ce747e7c255adac848a33c54a3a5', 'v0.0.484'),
('resnetabc14b', '0956', '6f8c36067feb2d27b5e0813bf18ef29038db0d70', 'v0.0.477'),
('resneta18', '0802', '225dd3ae0eac3ce3815732ac4ab0e25df709a75c', 'v0.0.486'),
('resneta50b', '0534', '28eff48a72d892802dde424db3fd0e1a9c12be16', 'v0.0.492'),
('resneta101b', '0442', 'cdf5f7ac2ad291cdc35b351e9220a490c8cc996c', 'v0.0.532'),
('resneta152b', '0424', 'deaaaabf413821eb543621826c368493b9041438', 'v0.0.524'),
('resnetd50b', '0549', '17d6004b5c6c1b97cfb47377ae5076810c5d88be', 'v0.0.296'),
('resnetd101b', '0461', 'fead1bcb86bba2be4ed7f0033fa972dc613e3280', 'v0.0.296'),
('resnetd152b', '0467', 'd0fe2fe09c6462de17aca4a72bbcb08b76a66e02', 'v0.0.296'),
('nin_cifar10', '0743', '9696dc1a8f67e7aa233836bcbdb99625769b1e86', 'v0.0.175'),
('nin_cifar100', '2839', 'eed0e9af2cd8e5aa77bb063204525812dbd9190f', 'v0.0.183'),
('nin_svhn', '0376', '7cb750180b0a981007194461bf57cfd90eb59c88', 'v0.0.270'),
('resnet20_cifar10', '0597', '13c5ab19145591d75873da3497be1dd1bd2afd46', 'v0.0.163'),
('resnet20_cifar100', '2964', '4e1443526ee96648bfe4d4954871a97a9c9622f4', 'v0.0.180'),
('resnet20_svhn', '0343', '7ac0d94a4563c9611092ce08f2124a3828103139', 'v0.0.265'),
('resnet56_cifar10', '0452', 'a73e63e9d0f3f7adde59b4142323c0dd05930de7', 'v0.0.163'),
('resnet56_cifar100', '2488', '590977100774a289b91088245dd2bd0cbe6567e6', 'v0.0.181'),
('resnet56_svhn', '0275', 'e676e4216a771b7d0339e87284c7ebb03af8ed25', 'v0.0.265'),
('resnet110_cifar10', '0369', 'f89f1c4d9fdd9e5cd00949a872211376979ff703', 'v0.0.163'),
('resnet110_cifar100', '2280', '6c5fa14bb4ced2dffe6ee1536306687aae57f9cb', 'v0.0.190'),
('resnet110_svhn', '0245', '0570b5942680cf88c66ae9a76c0e7ff0a41e71a6', 'v0.0.265'),
('resnet164bn_cifar10', '0368', 'e7941eeeddef9336664522eaa3af92d77128cac0', 'v0.0.179'),
('resnet164bn_cifar100', '2044', 'c7db7b5e6fbe6dc0f9501d25784f1a107c6e0315', 'v0.0.182'),
('resnet164bn_svhn', '0242', '8cdce67452d2780c7c69f4d0b979e80189d4bff8', 'v0.0.267'),
('resnet272bn_cifar10', '0333', '99dc36ca2abc91f3f82db181a14c5364cd5526be', 'v0.0.368'),
('resnet272bn_cifar100', '2007', '088af5c23634fe75206081d946fc82fdc9e999ad', 'v0.0.368'),
('resnet272bn_svhn', '0243', '39d741c8d081ebd2266a114e82363839ffdf8ebb', 'v0.0.368'),
('resnet542bn_cifar10', '0343', 'e687b254e1eace223ceef39ad17106e61b8649ba', 'v0.0.369'),
('resnet542bn_cifar100', '1932', 'df8bd5264c1db11dd545f62e9c750c7976edccc9', 'v0.0.369'),
('resnet542bn_svhn', '0234', '4f78075cbcba196fc8f5297b71730906c1bf7d8a', 'v0.0.369'),
('resnet1001_cifar10', '0328', 'bb979d53089138b5060b418cad6c8ad9a940bf81', 'v0.0.201'),
('resnet1001_cifar100', '1979', '692d9516620bc8b7a4da30a98ebcb7432243f5e9', 'v0.0.254'),
('resnet1001_svhn', '0241', '031fb0ce5e5ddbebca2fd7d856d63ddd147fe933', 'v0.0.408'),
('resnet1202_cifar10', '0353', '377510a63595e544333f6f57523222cd845744a8', 'v0.0.214'),
('resnet1202_cifar100', '2156', '1d94f9ccdd81e1785ea6ec02a861a4a05f39e5c9', 'v0.0.410'),
('preresnet20_cifar10', '0651', 'daa895737a34edda75c40f2d8566660590c84a3f', 'v0.0.164'),
('preresnet20_cifar100', '3022', '37f15365d48768f792f4551bd6ccf5259bc70530', 'v0.0.187'),
('preresnet20_svhn', '0322', '608cee12c0bc3cb59feea96386f6c12c6da91ba5', 'v0.0.269'),
('preresnet56_cifar10', '0449', 'cb37cb9d4524d4e0f5724aeed9face455f527efc', 'v0.0.164'),
('preresnet56_cifar100', '2505', '4c39e83f567f15d6ee0d69bf2dcaccd62067dfe5', 'v0.0.188'),
('preresnet56_svhn', '0280', 'b974c2c96a18ff2278f1d33df58c8537f9139ed9', 'v0.0.269'),
('preresnet110_cifar10', '0386', 'd6d4b7bd9f154eca242482a7559413d5c7b6d465', 'v0.0.164'),
('preresnet110_cifar100', '2267', '18cf4161c67c03e50cff7eb30988a559f3f97260', 'v0.0.191'),
('preresnet110_svhn', '0279', '6804450b744fa922d9ec22aa4c792d3a5da812f6', 'v0.0.269'),
('preresnet164bn_cifar10', '0364', '7ecf30cb818f80908ef4a77af4660c1080d0df81', 'v0.0.196'),
('preresnet164bn_cifar100', '2018', 'a20557c8968c04d8d07e40fdc5b0d1ec1fb3339d', 'v0.0.192'),
('preresnet164bn_svhn', '0258', '4aeee06affea89767c058fe1650b7476f05d8563', 'v0.0.269'),
('preresnet272bn_cifar10', '0325', '944ba29df55afcf2789399de552e91578edd4295', 'v0.0.389'),
('preresnet272bn_cifar100', '1963', '38e296beff0cd92697235c717a801ec422cdafe3', 'v0.0.389'),
('preresnet272bn_svhn', '0234', '7ff97873447fbfb1d823fd43439e34351f149c13', 'v0.0.389'),
('preresnet542bn_cifar10', '0314', 'ac40a67bb3b7f02179ff3c4fa0d6533ff3e2dd9f', 'v0.0.391'),
('preresnet542bn_cifar100', '1871', 'd536ad01fc40fe19605a3409efb995bf8593aa29', 'v0.0.391'),
('preresnet542bn_svhn', '0236', '3a4633f14e96cce30086ef4149b52c0b7cbccce6', 'v0.0.391'),
('preresnet1001_cifar10', '0265', '50507ff74b6047abe6d04af6471d9bacafa05e24', 'v0.0.209'),
('preresnet1001_cifar100', '1841', '185e033d77e61cec588196e3fe8bf8dcb43acfab', 'v0.0.283'),
('preresnet1202_cifar10', '0339', '942cf6f22d80b5428256825234a252b8d6ebbe9d', 'v0.0.246'),
('resnext20_1x64d_cifar10', '0433', '0661d12e534a87bd5f3305d541afce5730d45492', 'v0.0.365'),
('resnext20_1x64d_cifar100', '2197', 'e7073542469be79876e3b3aeccb767638a136b93', 'v0.0.365'),
('resnext20_1x64d_svhn', '0298', '3c7febc8eee0887ebc54d5e1a4411a46066f0624', 'v0.0.365'),
('resnext20_2x32d_cifar10', '0453', 'afb48ca4764efaff92e4cc50ec11566993180ac1', 'v0.0.365'),
('resnext20_2x32d_cifar100', '2255', '995281ee5b0d021bf6e9e984802e30a0042e0290', 'v0.0.365'),
('resnext20_2x32d_svhn', '0296', '54189677f599b4f42d2469ad75921165f84d82dc', 'v0.0.365'),
('resnext20_2x64d_cifar10', '0403', '6f0c138fe13a73c9f149053065f1f430761e75be', 'v0.0.365'),
('resnext20_2x64d_cifar100', '2060', '5f6dfa3ff5f1b0e3e1441f554a80c504c1991a03', 'v0.0.365'),
('resnext20_2x64d_svhn', '0283', '9c77f074dcd6333a859da6ddd833a662031406ea', 'v0.0.365'),
('resnext20_4x16d_cifar10', '0470', 'ae1ba8697ec0a62a58edb9c87ef0d9f290d3c857', 'v0.0.365'),
('resnext20_4x16d_cifar100', '2304', '2c9d578ab797ef887b3e8c51d897a8e720880bfd', 'v0.0.365'),
('resnext20_4x16d_svhn', '0317', '6691c8f56f7a63b5638408356a7f9fe4931d7ac9', 'v0.0.365'),
('resnext20_4x32d_cifar10', '0373', 'cf6960607fb51269cb80d6900eadefd16c6bb511', 'v0.0.365'),
('resnext20_4x32d_cifar100', '2131', '2c558efca7c66c412843603cff137e9565d7c016', 'v0.0.365'),
('resnext20_4x32d_svhn', '0298', '1da9a7bf6bed55f89b1c19a9b6ff97f7fa674c81', 'v0.0.365'),
('resnext20_8x8d_cifar10', '0466', '280e5f89e24ca765a771e733f53377ede244207f', 'v0.0.365'),
('resnext20_8x8d_cifar100', '2282', '363f03e8040da3a2f1cfe88df99481b23382e28c', 'v0.0.365'),
('resnext20_8x8d_svhn', '0318', 'c1536efbb2d7c78ee5b9323b43e3d0d56e9d2aa4', 'v0.0.365'),
('resnext20_8x16d_cifar10', '0404', '4d7f72818137674c3c17257427b0c5788b250320', 'v0.0.365'),
('resnext20_8x16d_cifar100', '2172', '3fc47c7072039fd5437ed276e92a0840c94fe82e', 'v0.0.365'),
('resnext20_8x16d_svhn', '0301', '41b28fd308e8195ee74050a2c56e2085552a55e0', 'v0.0.365'),
('resnext20_16x4d_cifar10', '0404', '426b5b2f994bc8154cb17957cf7d487b156d4fe2', 'v0.0.365'),
('resnext20_16x4d_cifar100', '2282', '508d32271ea1d34d40305a67d64cf1547ca58ae6', 'v0.0.365'),
('resnext20_16x4d_svhn', '0321', '854df3b71743fe871b5cd9b72ff6197b34c57b5e', 'v0.0.365'),
('resnext20_16x8d_cifar10', '0394', 'f81d05668bf293e5d84150ec54f94c4a50b79d9c', 'v0.0.365'),
('resnext20_16x8d_cifar100', '2173', 'a246aea51d1fd165c9f6db2aa528a2afa6a03dcd', 'v0.0.365'),
('resnext20_16x8d_svhn', '0293', '31f4b14e3113085a6b9a8e384a3131af764afe82', 'v0.0.365'),
('resnext20_32x2d_cifar10', '0461', '2d6ee8362c497b7782b91f85d5c9fd0f4ac0470e', 'v0.0.365'),
('resnext20_32x2d_cifar100', '2322', 'ce65201429a93cf9175c0e2b8601ceaf538a2438', 'v0.0.365'),
('resnext20_32x2d_svhn', '0327', '2499ff6de736f1241bc58422ae9d1d39d8ac1014', 'v0.0.365'),
('resnext20_32x4d_cifar10', '0420', 'a365893948daea8ef5b20b61bc3519fe199381af', 'v0.0.365'),
('resnext20_32x4d_cifar100', '2213', '5b2ffba877ea3dd0aa86d7c38ab5467d4ed856e6', 'v0.0.365'),
('resnext20_32x4d_svhn', '0309', 'ddbef9ac7da748e162ac886621833a5aef84cb86', 'v0.0.365'),
('resnext20_64x1d_cifar10', '0493', '6618e9ac6df3bc2614c23ba0e39ea0d0d5d21eec', 'v0.0.365'),
('resnext20_64x1d_cifar100', '2353', '9c789af45dd1455b4b7fe94a21709bb9dc8c411b', 'v0.0.365'),
('resnext20_64x1d_svhn', '0342', '2591ea440078f6c089513ace548ed79fb0f9bb76', 'v0.0.365'),
('resnext20_64x2d_cifar10', '0438', '32fe188b44b9e7f80ddec8024799be871dd63c4e', 'v0.0.365'),
('resnext20_64x2d_cifar100', '2235', '62fcc38a8e37550ace0f67927d2f5a74990de920', 'v0.0.365'),
('resnext20_64x2d_svhn', '0314', '4c01490b9566eeb2aaf27446ca8f5bac621894f0', 'v0.0.365'),
('resnext29_32x4d_cifar10', '0315', 'c8a1beda8ba616dc9af682d3ac172bfdd7a2472d', 'v0.0.169'),
('resnext29_32x4d_cifar100', '1950', '5f2eedcdd5cea6fdec1508f261f556a953ae28c2', 'v0.0.200'),
('resnext29_32x4d_svhn', '0280', 'dcb6aef96fbd76aa249e8f834093e2384b898404', 'v0.0.275'),
('resnext29_16x64d_cifar10', '0241', '76b97a4dd6185602a8ca8bdd77a70f8ddfcd4e83', 'v0.0.176'),
('resnext29_16x64d_cifar100', '1693', '1fcec90d6425e0405c61a1e90a80701ea556beca', 'v0.0.322'),
('resnext29_16x64d_svhn', '0268', 'c57307f3bf70d0f39d6cfb1dc2c82d8ef9e89603', 'v0.0.358'),
('resnext56_1x64d_cifar10', '0287', '8edd977c69cfec45604f1b0dbbe36fb2b65f122d', 'v0.0.367'),
('resnext56_1x64d_cifar100', '1825', 'b78642c10e21afc477c27076e2ab9ec6854cca13', 'v0.0.367'),
('resnext56_1x64d_svhn', '0242', '860c610caa23e742093d7c7677253ee5b917af44', 'v0.0.367'),
('resnext56_2x32d_cifar10', '0301', 'd0284dff7382d969c59e602f66b25a72b8d9e232', 'v0.0.367'),
('resnext56_2x32d_cifar100', '1786', '32205070280db6bd6431a6b7ad0537524af5a6f0', 'v0.0.367'),
('resnext56_2x32d_svhn', '0246', 'ffb8df9ba6a5053c79dbdecf7d0b6f1d248fcfdf', 'v0.0.367'),
('resnext56_4x16d_cifar10', '0311', 'add022e7dd21245720e789a0a16a7475d15b5702', 'v0.0.367'),
('resnext56_4x16d_cifar100', '1809', '366de7b5abba9b09d1ffde87e3e9f379db73d691', 'v0.0.367'),
('resnext56_4x16d_svhn', '0244', 'f7b697f924eeb64ed14d21f576a4a82007937bbe', 'v0.0.367'),
('resnext56_8x8d_cifar10', '0307', '4f0b72469f9890079471db355e9bfb405d443317', 'v0.0.367'),
('resnext56_8x8d_cifar100', '1806', '827a485e2d5f3154251d6453563a73a511028445', 'v0.0.367'),
('resnext56_8x8d_svhn', '0247', 'f0550cd045d9f4a4f8648f0c9c517421a34f4a11', 'v0.0.367'),
('resnext56_16x4d_cifar10', '0312', '93d71b610a356f8e285dde08ad4fe96d79efcadd', 'v0.0.367'),
('resnext56_16x4d_cifar100', '1824', '9cb7a1326870878315dccb50b0be51968d6ddfa7', 'v0.0.367'),
('resnext56_16x4d_svhn', '0256', '943386bd2e0fabba153955d80171016a95482609', 'v0.0.367'),
('resnext56_32x2d_cifar10', '0314', 'ea8b43351206a567f865a9a53ecae65790da8a60', 'v0.0.367'),
('resnext56_32x2d_cifar100', '1860', '3f65de935e532fe3c18324f645260983c61c0c76', 'v0.0.367'),
('resnext56_32x2d_svhn', '0253', 'ba8c809dcaa9f6f6e3b2e12dfd9df1b123d11be7', 'v0.0.367'),
('resnext56_64x1d_cifar10', '0341', '12a684ad58d1d3407d61b7de4b2cedc042225d20', 'v0.0.367'),
('resnext56_64x1d_cifar100', '1816', 'b80f4315d53963dd3d1ac856d3c2dbf660b836eb', 'v0.0.367'),
('resnext56_64x1d_svhn', '0255', '144bab62a5ed27bcb2465d9ab8b9b4ce0bf31dc5', 'v0.0.367'),
('resnext272_1x64d_cifar10', '0255', 'c1a3fddc4de9f6ebee2a588bd585ede68974da4f', 'v0.0.372'),
('resnext272_1x64d_cifar100', '1911', 'e0b3656a204c40e0b4ee6ade1e8d262c521e842d', 'v0.0.372'),
('resnext272_1x64d_svhn', '0235', '025ee7b915fa25d617e9774b0303f35488445d78', 'v0.0.372'),
('resnext272_2x32d_cifar10', '0274', '23b391ce58d9694ea35240ec3b76ce8b0ebf66b8', 'v0.0.375'),
('resnext272_2x32d_cifar100', '1834', '4802083b5fda38a4a30b8a2b1f24eb4b8fdf55ad', 'v0.0.375'),
('resnext272_2x32d_svhn', '0244', 'b65ddfe317dabceb4d4d7e910ca07c0c575ad9b8', 'v0.0.375'),
('seresnet20_cifar10', '0601', '3411e5ad1060975c45fe6d0d836755a92e3bb27c', 'v0.0.362'),
('seresnet20_cifar100', '2854', '184ad148171fd9244bf8570eee6647a996678ab4', 'v0.0.362'),
('seresnet20_svhn', '0323', 'a3a3c67731eb8bea0cd3af3b8b2f88c1cc70987e', 'v0.0.362'),
('seresnet56_cifar10', '0413', '21bac136e4cac21abb3e08b60254c73b16f0190f', 'v0.0.362'),
('seresnet56_cifar100', '2294', '989d4d9227c4fc33440c267f1e1ac324fd246ad4', 'v0.0.362'),
('seresnet56_svhn', '0264', '63a155acd6407b5e96516b86f6a7cd9e6855c372', 'v0.0.362'),
('seresnet110_cifar10', '0363', 'fa3f09a88d24282e938488c4588968e273770605', 'v0.0.362'),
('seresnet110_cifar100', '2086', '5345be4166268ce2cd44d88eb9edba9f86ccc864', 'v0.0.362'),
('seresnet110_svhn', '0235', 'd129498ad625983d92048f32b80de5d16987779a', 'v0.0.362'),
('seresnet164bn_cifar10', '0339', '11c923152587746a5539a9e4f140db847b9b61c1', 'v0.0.362'),
('seresnet164bn_cifar100', '1995', '6c9dc66b86de6be67df1e59d4aff4a592d7d98b8', 'v0.0.362'),
('seresnet164bn_svhn', '0245', 'd97ea6c83b0fd1da3a976d518977b19bd466d015', 'v0.0.362'),
('seresnet272bn_cifar10', '0339', 'da4073add21614f22b231d8663867007f3f2312d', 'v0.0.390'),
('seresnet272bn_cifar100', '1907', '754af9375f060f55f8c3393a70659df460b8d47d', 'v0.0.390'),
('seresnet272bn_svhn', '0238', '9ffe8acad2a03cd98f6746d3f1528fe5f294aea4', 'v0.0.390'),
('seresnet542bn_cifar10', '0347', 'e64d9ca4b98349973b802572af6625879bc3c4a4', 'v0.0.385'),
('seresnet542bn_cifar100', '1887', 'cd76c769c06b886d2a94268c95691dfc905bac64', 'v0.0.385'),
('seresnet542bn_svhn', '0226', '05ce3771c46aa8b7af7c2056398f83b2b9f116db', 'v0.0.385'),
('sepreresnet20_cifar10', '0618', 'e55551e6e35d04fe8e35d24a5e3d608a08e8dfa2', 'v0.0.379'),
('sepreresnet20_cifar100', '2831', 'ee5d3bd66ce643950e54d54825036b98b13b31cd', 'v0.0.379'),
('sepreresnet20_svhn', '0324', 'd5bb6768cc3134137371a832c5ebc289d982a8db', 'v0.0.379'),
('sepreresnet56_cifar10', '0451', '56c299345242bcfca52c83f77cfff80b7058b1fe', 'v0.0.379'),
('sepreresnet56_cifar100', '2305', '313a7a30a129c174ecaf3de6a94a5fd34dc8d711', 'v0.0.379'),
('sepreresnet56_svhn', '0271', 'f556af3db771e6e4e5b847bd4eddef71b879b8d0', 'v0.0.379'),
('sepreresnet110_cifar10', '0454', '67eea1cc03f76ee0054d39f004ab10f7a70978bb', 'v0.0.379'),
('sepreresnet110_cifar100', '2261', '3291a56be67afd1154d9d2d05e2e1411c12dcb4a', 'v0.0.379'),
('sepreresnet110_svhn', '0259', '5c09cacbcf786e18509947c40de695883d6b3328', 'v0.0.379'),
('sepreresnet164bn_cifar10', '0373', 'ac72ac7fa9d78e66a719717f922f738bbe7f9699', 'v0.0.379'),
('sepreresnet164bn_cifar100', '2005', 'd93993672a414e8f19cb12d2489be930e8605b8f', 'v0.0.379'),
('sepreresnet164bn_svhn', '0256', 'a45d1a65092900bb768969c52f26c61292838caa', 'v0.0.379'),
('sepreresnet272bn_cifar10', '0339', '3e47d575280a70c1726d6b2eb8d0d7c069a3e472', 'v0.0.379'),
('sepreresnet272bn_cifar100', '1913', 'd243b0580717b197bf9eb32a8959c83d21a3124f', 'v0.0.379'),
('sepreresnet272bn_svhn', '0249', '34b910cdfa34bf318f58c3312bc074059c7c669f', 'v0.0.379'),
('sepreresnet542bn_cifar10', '0308', '05f7d4a6bfb1af1825b734eac99b3b46dd8c4b91', 'v0.0.382'),
('sepreresnet542bn_cifar100', '1945', '4dd0e21d02fef2ae1fe3fb3a8cd8c72db11bb685', 'v0.0.382'),
('sepreresnet542bn_svhn', '0247', '456035daf4daecd909e957da090078deba6cb449', 'v0.0.382'),
('pyramidnet110_a48_cifar10', '0372', '35b94d0575c2081a142e71955c8ceea8c51ec5e5', 'v0.0.184'),
('pyramidnet110_a48_cifar100', '2095', '00fd42a00492b2bbb28cacfb7b1a6c63072c37a3', 'v0.0.186'),
('pyramidnet110_a48_svhn', '0247', 'd8a5c6e20b6cc01989a52f9e307caf640169ed0a', 'v0.0.281'),
('pyramidnet110_a84_cifar10', '0298', '81710d7ab90838a8a299bf5f50aed2a3fa41f0e3', 'v0.0.185'),
('pyramidnet110_a84_cifar100', '1887', '6712d5dc69452f2fde1fcc3ee32c3164dcaffc4e', 'v0.0.199'),
('pyramidnet110_a84_svhn', '0243', '473cc640c4ad0a1642500c84f2ef848498d12a37', 'v0.0.392'),
('pyramidnet110_a270_cifar10', '0251', '1e769ce50ef915a807ee99907912c87766fff60f', 'v0.0.194'),
('pyramidnet110_a270_cifar100', '1710', '2732fc6430085192189fd7ccfd287881cc5a6c0d', 'v0.0.319'),
('pyramidnet110_a270_svhn', '0238', '034be5421b598e84f395f421182f664495ca62ca', 'v0.0.393'),
('pyramidnet164_a270_bn_cifar10', '0242', 'c4a79ea3d84344b9d352074122e37f593ee98fd2', 'v0.0.264'),
('pyramidnet164_a270_bn_cifar100', '1670', '08f46c7ff99e9c3fd7b5262e34dc8a00b316646f', 'v0.0.312'),
('pyramidnet164_a270_bn_svhn', '0233', '27b67f1494ed508e0192e3e0f09ac86e32e1e734', 'v0.0.396'),
('pyramidnet200_a240_bn_cifar10', '0244', '52f4d43ec4d952f847c3a8e0503d5a4e6286679c', 'v0.0.268'),
('pyramidnet200_a240_bn_cifar100', '1609', 'e61e7e7eb6675aaf7a18461fea9bb3a53538d43b', 'v0.0.317'),
('pyramidnet200_a240_bn_svhn', '0232', '02bf262e70d9b3ce8038255d0abdec2bc5161f6d', 'v0.0.397'),
('pyramidnet236_a220_bn_cifar10', '0247', '1bd295a7fb834f639b238ffee818b3bde4126c81', 'v0.0.285'),
('pyramidnet236_a220_bn_cifar100', '1634', 'f066b3c6a4d217c42f5e8872fe23d343afe378ec', 'v0.0.312'),
('pyramidnet236_a220_bn_svhn', '0235', '1a0c0711f013035c0e05145501c93fa2519603ea', 'v0.0.398'),
('pyramidnet272_a200_bn_cifar10', '0239', 'd7b23c5460f059ac82ebc7b2cd992a203e098476', 'v0.0.284'),
('pyramidnet272_a200_bn_cifar100', '1619', '486e942734d91cd62d6bcbc283e1d7b56b734507', 'v0.0.312'),
('pyramidnet272_a200_bn_svhn', '0240', 'dcd9af34f57708f598bba723824bf3525f6e42c7', 'v0.0.404'),
('densenet40_k12_cifar10', '0561', '28dc0035549e51dcb53d1360707bd6f1558a5dcd', 'v0.0.193'),
('densenet40_k12_cifar100', '2490', '908f02ba7dbd7b8138f264193189e762a5590b1c', 'v0.0.195'),
('densenet40_k12_svhn', '0305', '645564c186a4e807293a68fb388803e36916e7b2', 'v0.0.278'),
('densenet40_k12_bc_cifar10', '0643', '7fdeda31c5accbddf47ab0f0b9a32cff723bf70d', 'v0.0.231'),
('densenet40_k12_bc_cifar100', '2841', '35cd8e6a2ae0896a8af2b689e076057fa19efa9b', 'v0.0.232'),
('densenet40_k12_bc_svhn', '0320', '6f2f98243fac9da22be26681bcd0a4d08e0f4baf', 'v0.0.279'),
('densenet40_k24_bc_cifar10', '0452', '13fa807e095b44ecaf3882e488b33a890d9d1e29', 'v0.0.220'),
('densenet40_k24_bc_cifar100', '2267', '2c4ef7c4bbe7f64784ad18b3845f4bf533f2ce57', 'v0.0.221'),
('densenet40_k24_bc_svhn', '0290', '03e136dd71bc85966fd2a4cb15692cfff3886df2', 'v0.0.280'),
('densenet40_k36_bc_cifar10', '0404', '4c154567e25619994a2f86371afbf1ad1e7475e9', 'v0.0.224'),
('densenet40_k36_bc_cifar100', '2050', 'd7275d39bcf439151c3bbeb707efa54943714b03', 'v0.0.225'),
('densenet40_k36_bc_svhn', '0260', 'b81ec8d662937851beecc62f36209fd8db464265', 'v0.0.311'),
('densenet100_k12_cifar10', '0366', '4e371ccb315d0fcd727a76255ca62ae9e92059cc', 'v0.0.205'),
('densenet100_k12_cifar100', '1964', '2ed5ec27a4d4a63876a4cacf52be53c91fbecb5f', 'v0.0.206'),
('densenet100_k12_svhn', '0260', '3e2b34b2087fe507a3672bfce1520747fca58046', 'v0.0.311'),
('densenet100_k24_cifar10', '0313', '9f795bac946d1390cf59f686b730fe512c406bd2', 'v0.0.252'),
('densenet100_k24_cifar100', '1808', '9bfa3e9c736a80906d163380cb361b940c2188bf', 'v0.0.318'),
('densenet100_k12_bc_cifar10', '0416', '6685d1f4844b092471f7d03dfc3fa64a302008e6', 'v0.0.189'),
('densenet100_k12_bc_cifar100', '2119', 'fbd8a54c1c9e4614f950b8473f8524d25caba4a7', 'v0.0.208'),
('densenet190_k40_bc_cifar10', '0252', '87b15be0620c0adff249d33540c20314188b16d7', 'v0.0.286'),
('densenet250_k24_bc_cifar10', '0267', 'dad68693d83a276d14a87dce6cebc5aceebca775', 'v0.0.290'),
('densenet250_k24_bc_cifar100', '1739', '598e91b7906f427296ab72cf40032f0846a52d91', 'v0.0.303'),
('xdensenet40_2_k24_bc_cifar10', '0531', '66c9d384d3ef4ec4095c9759bb8b7986f2f58e26', 'v0.0.226'),
('xdensenet40_2_k24_bc_cifar100', '2396', '73d5ba88a39b971457b9cea2cd72d1e05ab4d165', 'v0.0.227'),
('xdensenet40_2_k24_bc_svhn', '0287', '745f374b398bce378903af8c71cb3c67f6891d7f', 'v0.0.306'),
('xdensenet40_2_k36_bc_cifar10', '0437', 'e9bf419295f833b56fa3da27218107ed42310307', 'v0.0.233'),
('xdensenet40_2_k36_bc_cifar100', '2165', '78b6e754d90774d7b6ec3d811e6e57192148cfbf', 'v0.0.234'),
('xdensenet40_2_k36_bc_svhn', '0274', '4377e8918c1e008201aafc448f642642474eab14', 'v0.0.306'),
('wrn16_10_cifar10', '0293', 'ecf1c17c0814763095df562cb27d15a5aeb51836', 'v0.0.166'),
('wrn16_10_cifar100', '1895', 'bcb5c89ca71ffc99bc09b861b339724047724659', 'v0.0.204'),
('wrn16_10_svhn', '0278', '76f4e1361f9eca82fa4c2764b530f57280a34cfe', 'v0.0.271'),
('wrn28_10_cifar10', '0239', '16f3c8a249993f23b0f81d9ce3650faef5e455d8', 'v0.0.166'),
('wrn28_10_cifar100', '1788', '67ec43c6e913d43c8936809f04b0780035a24835', 'v0.0.320'),
('wrn28_10_svhn', '0271', 'fcd7a6b03a552b22ec25ee9a3833dc260976a757', 'v0.0.276'),
('wrn40_8_cifar10', '0237', '3b81d261706b751f5b731149b05fa92f500218e8', 'v0.0.166'),
('wrn40_8_cifar100', '1803', '114f6be2d5f8d561a5e3b4106fac30028defe300', 'v0.0.321'),
('wrn40_8_svhn', '0254', 'be7a21da6bc958c79725d7a29502c6a781cc67d9', 'v0.0.277'),
('wrn20_10_1bit_cifar10', '0326', 'c1a8ba4f1e1336a289c4b2eec75e25445b511ca6', 'v0.0.302'),
('wrn20_10_1bit_cifar100', '1904', 'adae01d6bec92d4fe388cddbb7f7eb598b1655d1', 'v0.0.302'),
('wrn20_10_1bit_svhn', '0273', 'ce9f819cf117fa66af112d9cbb0b65568623118d', 'v0.0.302'),
('wrn20_10_32bit_cifar10', '0314', '355496184493a55323c99bad9f79b0803548d373', 'v0.0.302'),
('wrn20_10_32bit_cifar100', '1812', 'd064f38aeaa14e9a2f4e9893ef6cca65615c53f9', 'v0.0.302'),
('wrn20_10_32bit_svhn', '0259', 'd9e8b46e180a34c0a765e22d24741f3849fca13a', 'v0.0.302'),
('ror3_56_cifar10', '0543', 'ee31a69a0503b41878c49d8925ac8e7ee813293b', 'v0.0.228'),
('ror3_56_cifar100', '2549', '4334559313cd9291af3d6ec0df144b21e695228b', 'v0.0.229'),
('ror3_56_svhn', '0269', '56617cf90e0902e88686af14939605c45d1170cf', 'v0.0.287'),
('ror3_110_cifar10', '0435', '0359916596cba01dfa481f105094c1047f592980', 'v0.0.235'),
('ror3_110_cifar100', '2364', 'b8c4d317241f54990180443d7fd9702d79c57ccc', 'v0.0.236'),
('ror3_110_svhn', '0257', '0677b7dfee32659a92719a5a16a7f387a5635f0b', 'v0.0.287'),
('ror3_164_cifar10', '0393', 'cc11aa06d928d0805279baccbf2b82371c31f503', 'v0.0.294'),
('ror3_164_cifar100', '2234', 'eb6a7fb8128240d84843a8e39adb00f606b6e2cf', 'v0.0.294'),
('ror3_164_svhn', '0273', 'b008c1b01386aca1803a1286607c5e1f843fc919', 'v0.0.294'),
('rir_cifar10', '0328', '5bed6f3506055b3ab5c4780a540cfebe014490ec', 'v0.0.292'),
('rir_cifar100', '1923', 'c42563834a971e18eacfc2287585aa2efa8af3eb', 'v0.0.292'),
('rir_svhn', '0268', '1c0718deaef5836efca4d5ded6140f0cd51424ab', 'v0.0.292'),
('shakeshakeresnet20_2x16d_cifar10', '0515', 'a7b8a2f77457e151da5d5ad3b9a2473594fecfc0', 'v0.0.215'),
('shakeshakeresnet20_2x16d_cifar100', '2922', 'e46e31a7d8308b57d9c0687000c40f15623998c2', 'v0.0.247'),
('shakeshakeresnet20_2x16d_svhn', '0317', '7a48fde5e1ccd5ff695892adf7094c15368ec778', 'v0.0.295'),
('shakeshakeresnet26_2x32d_cifar10', '0317', '21e60e626765001aaaf4eb26f7cb8f4a69ea3dc1', 'v0.0.217'),
('shakeshakeresnet26_2x32d_cifar100', '1880', 'bd46a7418374e3b3c844b33e12b09b6a98eb4e6e', 'v0.0.222'),
('shakeshakeresnet26_2x32d_svhn', '0262', 'f1dbb8ef162d9ec56478e2579272f85ed78ad896', 'v0.0.295'),
('diaresnet20_cifar10', '0622', '3e47641d76c1992652d8f973294f4763ecef1987', 'v0.0.340'),
('diaresnet20_cifar100', '2771', '3a58490ea95538ad5809c05739b4362088ea6961', 'v0.0.342'),
('diaresnet20_svhn', '0323', '579535ddc8b7c9becfe9bf97393ab33d9d5e7d0b', 'v0.0.342'),
('diaresnet56_cifar10', '0505', '45df69745c9692168697a7b980ade080ef7af07d', 'v0.0.340'),
('diaresnet56_cifar100', '2435', 'e45b7f281bb63c90104ff79d1519b4785a975a92', 'v0.0.342'),
('diaresnet56_svhn', '0268', '8f2c0574380bf14b0e9711d6370b2898f337cab0', 'v0.0.342'),
('diaresnet110_cifar10', '0410', '56f547ec833f419ea216f51439de50287dfef3c3', 'v0.0.340'),
('diaresnet110_cifar100', '2211', 'e99fad4ef0b2e7f09376beb314d672db7c3b6a55', 'v0.0.342'),
('diaresnet110_svhn', '0247', 'c587ac09f45fd7a29adfc1da62ad50174fd248ec', 'v0.0.342'),
('diaresnet164bn_cifar10', '0350', '533e7c6a30fce31c4f65686782cf761e7913750c', 'v0.0.340'),
('diaresnet164bn_cifar100', '1953', '43fa3821ab72e94187c12f7f950a2343649b3657', 'v0.0.342'),
('diaresnet164bn_svhn', '0244', 'eba062dce4033fd85ff78c2530b363b3768c036e', 'v0.0.342'),
('diapreresnet20_cifar10', '0642', 'ec36098cfbbb889fdd124083e785d0e21ba34792', 'v0.0.343'),
('diapreresnet20_cifar100', '2837', '32f0f1be9aa1da73f8fdb74f27ebaa49e7f9ace6', 'v0.0.343'),
('diapreresnet20_svhn', '0303', 'e33be387b0e71a4b0597558157ffbdb79c6db30c', 'v0.0.343'),
('diapreresnet56_cifar10', '0483', 'cba6950f21643a70b8e61b7197ca9cee9b2d0545', 'v0.0.343'),
('diapreresnet56_cifar100', '2505', 'c9f8bd4380d35e3806e1697c1c8d80bf7341c04e', 'v0.0.343'),
('diapreresnet56_svhn', '0280', '98a2a0bab42ff2605bd2cd4e63280b3631b042cb', 'v0.0.343'),
('diapreresnet110_cifar10', '0425', 'f4eae5abe2edebb1e224f7cf092ba02a873eb781', 'v0.0.343'),
('diapreresnet110_cifar100', '2269', '78d79bab215a5dc7221859d0b2688d040a55afb2', 'v0.0.343'),
('diapreresnet110_svhn', '0242', 'decb3765e92f5620580fe6b440ee2a82811d412e', 'v0.0.343'),
('diapreresnet164bn_cifar10', '0356', '9cf07392dc9714324e470fd50efb92ef286296ac', 'v0.0.343'),
('diapreresnet164bn_cifar100', '1999', '1625154f3cce7e131f25d8ee0b315b3fcc6fb760', 'v0.0.343'),
('diapreresnet164bn_svhn', '0256', '8476c5c9176abf21ea380dd00074b0ec30bbc530', 'v0.0.343'),
('resnet10_cub', '2765', '9dab9a498c380e6b7447827e00996d7cc61cc414', 'v0.0.335'),
('resnet12_cub', '2658', 'a46b8ec2d8dcd66a628dcfcb617acb15ef786b95', 'v0.0.336'),
('resnet14_cub', '2435', '0b9801b2e3aa3908bbc98f50d3ae3e986652742b', 'v0.0.337'),
('resnet16_cub', '2321', '031374ada9830869372a63e132c2477a04425444', 'v0.0.338'),
('resnet18_cub', '2330', 'e72712003928ed70ccf44b953e9cec4f78a75eea', 'v0.0.344'),
('resnet26_cub', '2252', '61cce1ea575f650a7e12a08b1a09335afa6cb605', 'v0.0.345'),
('seresnet10_cub', '2739', '7060c03f78bc60df09288b433eb6117c0e167210', 'v0.0.361'),
('seresnet12_cub', '2604', 'ee095118bde6e05ea102f5b945401a7221b7b7fb', 'v0.0.361'),
('seresnet14_cub', '2363', '5d2049d53c0445d7c66c849a5cd805ce39a37ddb', 'v0.0.361'),
('seresnet16_cub', '2321', '576e58eff57730a516094b8ba79452092187b693', 'v0.0.361'),
('seresnet18_cub', '2308', '3d2496d66efd6a00ca516c1a7a5a091f90043237', 'v0.0.361'),
('seresnet26_cub', '2251', '8d54edb2800b2ff071ee5beedde285eb9553bc22', 'v0.0.361'),
('mobilenet_w1_cub', '2346', 'efcad3dcf1975552f15028255a15f86a16b60987', 'v0.0.346'),
('proxylessnas_mobile_cub', '2188', '36d33231029b466638b3b1f8b2d1392e22d1afa7', 'v0.0.347'),
('ntsnet_cub', '1326', '75ae8cdcf4beb1ab60c1a983c9f143baaebbdea0', 'v0.0.334'),
('pspnet_resnetd101b_voc', '8144', 'e15319bf5428637e7fc00dcd426dd458ac937b08', 'v0.0.297'),
('pspnet_resnetd50b_ade20k', '3687', 'f0dcdf734f8f32a879dec3c4e7fe61d629244030', 'v0.0.297'),
('pspnet_resnetd101b_ade20k', '3797', 'c1280aeab8daa31c0893f7551d70130c2b68214a', 'v0.0.297'),
('pspnet_resnetd101b_cityscapes', '7172', 'd5ad2fa4c4208f439ab0b98267babe0c4d9e6e94', 'v0.0.297'),
('pspnet_resnetd101b_coco', '6741', '87582b79c48c4e995de808ff0cbc162c55b52031', 'v0.0.297'),
('deeplabv3_resnetd101b_voc', '8024', '8ee3099c5c983ef1cc0ce23b23d91db40b2986b8', 'v0.0.298'),
('deeplabv3_resnetd152b_voc', '8120', '88fb315dc3c58a84f325e63105fbfe322932073f', 'v0.0.298'),
('deeplabv3_resnetd50b_ade20k', '3713', '5d5e2f74008ab3637a05b6b1357c9c339296188c', 'v0.0.298'),
('deeplabv3_resnetd101b_ade20k', '3784', '6224836f8f31a00be1718a530a20670136bb3958', 'v0.0.298'),
('deeplabv3_resnetd101b_coco', '6773', '74dc9914078e47feb3ff64fba717d1d4040d8235', 'v0.0.298'),
('deeplabv3_resnetd152b_coco', '6899', 'edd79b4ca095f1674e7a68ee0dc8ed8bcd0b6a26', 'v0.0.298'),
('fcn8sd_resnetd101b_voc', '8040', 'f6c67c75bce4f9a3e17bf555369c0c9332ab5c1f', 'v0.0.299'),
('fcn8sd_resnetd50b_ade20k', '3339', '9856c5ee8186d1ac4b0eb5177c73e76c4cd63bb0', 'v0.0.299'),
('fcn8sd_resnetd101b_ade20k', '3588', '081774b2fb373d7b759cda2160fa0d2599b1c5f1', 'v0.0.299'),
('fcn8sd_resnetd101b_coco', '6011', '05e97cc5f5fcdf1c5ec5c617062d43adfe150d88', 'v0.0.299'),
('icnet_resnetd50b_cityscapes', '6402', '6c8f86a53526ae107e58d5f645bc4de0da9c1bb1', 'v0.0.457'),
('fastscnn_cityscapes', '6576', '9e0d75e56bde8d1643d3ff0053e55114c0a77ee9', 'v0.0.474'),
('sinet_cityscapes', '6031', '47d8ae7824bd297bbf25c2f33e3d4a86a503aefa', 'v0.0.437'),
('bisenet_resnet18_celebamaskhq', '0000', 'd72f0cf3101625bb4265e4cf5ae557b994f84d67', 'v0.0.462'),
('danet_resnetd50b_cityscapes', '6799', '9880a0eb9523ba2c1f98025f7d7115a2a4c1f376', 'v0.0.468'),
('danet_resnetd101b_cityscapes', '6810', 'ea69dcea31f5b250254a226f70df130875ff18b2', 'v0.0.468'),
('alphapose_fastseresnet101b_coco', '7415', '70082a53d3cdeb7ebe4c7d8c16a6a39830f1ed23', 'v0.0.454'),
('simplepose_resnet18_coco', '6631', '5a6198e5103a28faab4e49c687121634c7f7d196', 'v0.0.455'),
('simplepose_resnet50b_coco', '7102', '6315ffa72993eea3f573ae1cc23f84d0275f0fbe', 'v0.0.455'),
('simplepose_resnet101b_coco', '7244', '0491ab951827782492ffbd8fa57aa6dd599c7e9f', 'v0.0.455'),
('simplepose_resnet152b_coco', '7253', '4590c1c555eb54c4e9afdc83fa8a199132afd212', 'v0.0.455'),
('simplepose_resneta50b_coco', '7170', 'fa09a84ee2e085ad6b641c4fe0cc483651861789', 'v0.0.455'),
('simplepose_resneta101b_coco', '7297', '7ddd6cb20bcd626e05e8a627601bf19b704ba6a9', 'v0.0.455'),
('simplepose_resneta152b_coco', '7344', '9ec1a3dc2a23a19cb7f5ac5466cebba8069a0f93', 'v0.0.455'),
('simplepose_mobile_resnet18_coco', '6625', '8ff93eed70ac73503c8c1e346ddd1ade5d9e3edf', 'v0.0.456'),
('simplepose_mobile_resnet50b_coco', '7110', 'e0f2e587ffdf5e074a29f877890b13b99a58c6c2', 'v0.0.456'),
('simplepose_mobile_mobilenet_w1_coco', '6410', '0867e5aa76d5ec37cde08c71de8324a9c2913922', 'v0.0.456'),
('simplepose_mobile_mobilenetv2b_w1_coco', '6374', '07e9c6295a8aa2b7bb9a1d0b7c716141e7ee71dc', 'v0.0.456'),
('simplepose_mobile_mobilenetv3_small_w1_coco', '5434', 'cb837c0e32edec68dc8598d71599ea7404936f96', 'v0.0.456'),
('simplepose_mobile_mobilenetv3_large_w1_coco', '6367', '7ba036a5ade736042531a0fe500ecec368dbf157', 'v0.0.456'),
('lwopenpose2d_mobilenet_cmupan_coco', '3999', 'b4a22e7c2a05e53fe22185002c48e81f76c2d918', 'v0.0.458'),
('lwopenpose3d_mobilenet_cmupan_coco', '3999', '4658738ec27d46ee01f2cad4aa975914e9f7108c', 'v0.0.458'),
('ibppose_coco', '6486', '024d1fafb7471572129ccbb07d662f6d8ccdc758', 'v0.0.459'),
('jasperdr10x5_en', '2190', '1ce0ab1cd891294988d7f34d2153fabd968aa876', 'v0.0.555'),
('jasperdr10x5_en_nr', '1789', '49b0b7718e69265c288c163fa6bbb68eb4db79e4', 'v0.0.555'),
('quartznet5x5_en_ls', '4468', 'b37c8cb2e84b2573ed4364d3786e5d06f36cba92', 'v0.0.555'),
('quartznet15x5_en', '1677', 'bf63d3ffbd117d7e6c36bcd7725c998b8ab06754', 'v0.0.555'),
('quartznet15x5_en_nr', '1774', '5a70b9ec078945392c9e5a4161a36f431b1966ab', 'v0.0.555'),
('quartznet15x5_de', '1166', '5e254c91fe57bb2ed5bae62eb5067fc4922f4184', 'v0.0.555'),
('quartznet15x5_fr', '1388', 'f2236953caa996832118c7a412c839395237b5c2', 'v0.0.555'),
('quartznet15x5_it', '1502', '2df788c3c06415237e254ea91ab2994b35c32e71', 'v0.0.555'),
('quartznet15x5_es', '1295', '117352a802814689275b03a161c537ae91e68a9f', 'v0.0.555'),
('quartznet15x5_ca', '0842', 'da40489e324b6a790638d8ed164be3728f4caf3c', 'v0.0.555'),
('quartznet15x5_pl', '1359', '0df08d125314b5a728cd22b77bb8c6dc2b9c2cd1', 'v0.0.555'),
('quartznet15x5_ru', '1648', 'aecf49e137f8041cebc5fcfe8d1834420f03d98b', 'v0.0.555'),
('quartznet15x5_ru34', '0968', 'ff446c0cca42687330ade49dfb6bac05d7251803', 'v0.0.555'),
]}
imgclsmob_repo_url = 'https://github.com/osmr/imgclsmob'
def get_model_name_suffix_data(model_name):
if model_name not in _model_sha1:
raise ValueError("Pretrained model for {name} is not available.".format(name=model_name))
error, sha1_hash, repo_release_tag = _model_sha1[model_name]
return error, sha1_hash, repo_release_tag
def get_model_file(model_name,
local_model_store_dir_path=os.path.join("~", ".mxnet", "models")):
"""
Return location for the pretrained on local file system. This function will download from online model zoo when
model cannot be found or has mismatch. The root directory will be created if it doesn't exist.
Parameters:
----------
model_name : str
Name of the model.
local_model_store_dir_path : str, default $MXNET_HOME/models
Location for keeping the model parameters.
Returns:
-------
file_path
Path to the requested pretrained model file.
"""
error, sha1_hash, repo_release_tag = get_model_name_suffix_data(model_name)
short_sha1 = sha1_hash[:8]
file_name = "{name}-{error}-{short_sha1}.params".format(
name=model_name,
error=error,
short_sha1=short_sha1)
local_model_store_dir_path = os.path.expanduser(local_model_store_dir_path)
file_path = os.path.join(local_model_store_dir_path, file_name)
if os.path.exists(file_path):
if check_sha1(file_path, sha1_hash):
return file_path
else:
logging.warning("Mismatch in the content of model file detected. Downloading again.")
else:
logging.info("Model file not found. Downloading to {}.".format(file_path))
if not os.path.exists(local_model_store_dir_path):
os.makedirs(local_model_store_dir_path)
zip_file_path = file_path + ".zip"
download(
url="{repo_url}/releases/download/{repo_release_tag}/{file_name}.zip".format(
repo_url=imgclsmob_repo_url,
repo_release_tag=repo_release_tag,
file_name=file_name),
path=zip_file_path,
overwrite=True)
with zipfile.ZipFile(zip_file_path) as zf:
zf.extractall(local_model_store_dir_path)
os.remove(zip_file_path)
if check_sha1(file_path, sha1_hash):
return file_path
else:
raise ValueError("Downloaded file has different hash. Please try again.")
| 61,759 | 83.718793 | 116 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/fastseresnet.py | """
Fast-SE-ResNet for ImageNet-1K, implemented in Gluon.
Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
"""
__all__ = ['FastSEResNet', 'fastseresnet101b']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block, SEBlock
from .resnet import ResBlock, ResBottleneck, ResInitBlock
class FastSEResUnit(HybridBlock):
"""
Fast-SE-ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer of the block.
use_se : bool
Whether to use SE-module.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats,
bottleneck,
conv1_stride,
use_se,
**kwargs):
super(FastSEResUnit, self).__init__(**kwargs)
self.use_se = use_se
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
if bottleneck:
self.body = ResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
conv1_stride=conv1_stride)
else:
self.body = ResBlock(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats)
if self.use_se:
self.se = SEBlock(
channels=out_channels,
reduction=1,
use_conv=False)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
activation=None)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
if self.use_se:
x = self.se(x)
x = x + identity
x = self.activ(x)
return x
class FastSEResNet(HybridBlock):
"""
Fast-SE-ResNet model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(FastSEResNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
use_se = (j == 0)
stage.add(FastSEResUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
use_se=use_se))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_fastseresnet(blocks,
bottleneck=None,
conv1_stride=True,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create Fast-SE-ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
bottleneck : bool, default None
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if bottleneck is None:
bottleneck = (blocks >= 50)
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14 and not bottleneck:
layers = [2, 2, 1, 1]
elif (blocks == 14) and bottleneck:
layers = [1, 1, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif (blocks == 26) and not bottleneck:
layers = [3, 3, 3, 3]
elif (blocks == 26) and bottleneck:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif (blocks == 38) and bottleneck:
layers = [3, 3, 3, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
else:
raise ValueError("Unsupported Fast-SE-ResNet with number of blocks: {}".format(blocks))
if bottleneck:
assert (sum(layers) * 3 + 2 == blocks)
else:
assert (sum(layers) * 2 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [64, 128, 256, 512]
if bottleneck:
bottleneck_factor = 4
channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = FastSEResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def fastseresnet101b(**kwargs):
"""
Fast-SE-ResNet-101 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_fastseresnet(blocks=101, conv1_stride=False, model_name="fastseresnet101b", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
fastseresnet101b,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != fastseresnet101b or weight_count == 55697960)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 10,500 | 32.336508 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/ibnbresnet.py | """
IBN(b)-ResNet for ImageNet-1K, implemented in Gluon.
Original paper: 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
"""
__all__ = ['IBNbResNet', 'ibnb_resnet50', 'ibnb_resnet101', 'ibnb_resnet152']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block
from .resnet import ResBottleneck
class IBNbConvBlock(HybridBlock):
"""
IBN(b)-ResNet specific convolution block with Instance normalization and ReLU activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
activate : bool, default True
Whether activate the convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
dilation=1,
groups=1,
use_bias=False,
activate=True,
**kwargs):
super(IBNbConvBlock, self).__init__(**kwargs)
self.activate = activate
with self.name_scope():
self.conv = nn.Conv2D(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
in_channels=in_channels)
self.inst_norm = nn.InstanceNorm(
in_channels=out_channels,
scale=True)
if self.activate:
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.inst_norm(x)
if self.activate:
x = self.activ(x)
return x
def ibnb_conv7x7_block(in_channels,
out_channels,
strides=1,
padding=3,
use_bias=False,
activate=True):
"""
7x7 version of the IBN(b)-ResNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 3
Padding value for convolution layer.
use_bias : bool, default False
Whether the layer uses a bias vector.
activate : bool, default True
Whether activate the convolution block.
"""
return IBNbConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=7,
strides=strides,
padding=padding,
use_bias=use_bias,
activate=activate)
class IBNbResUnit(HybridBlock):
"""
IBN(b)-ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
use_inst_norm : bool
Whether to use instance normalization.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
use_inst_norm,
bn_use_global_stats,
**kwargs):
super(IBNbResUnit, self).__init__(**kwargs)
self.use_inst_norm = use_inst_norm
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
self.body = ResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
conv1_stride=False)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
activation=None)
if self.use_inst_norm:
self.inst_norm = nn.InstanceNorm(
in_channels=out_channels,
scale=True)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
if self.use_inst_norm:
x = self.inst_norm(x)
x = self.activ(x)
return x
class IBNbResInitBlock(HybridBlock):
"""
IBN(b)-ResNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels,
**kwargs):
super(IBNbResInitBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv = ibnb_conv7x7_block(
in_channels=in_channels,
out_channels=out_channels,
strides=2)
self.pool = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=1)
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.pool(x)
return x
class IBNbResNet(HybridBlock):
"""
IBN(b)-ResNet model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(IBNbResNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(IBNbResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
use_inst_norm = (i < 2) and (j == len(channels_per_stage) - 1)
stage.add(IBNbResUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
use_inst_norm=use_inst_norm,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_ibnbresnet(blocks,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create IBN(b)-ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
else:
raise ValueError("Unsupported IBN(b)-ResNet with number of blocks: {}".format(blocks))
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = IBNbResNet(
channels=channels,
init_block_channels=init_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def ibnb_resnet50(**kwargs):
"""
IBN(b)-ResNet-50 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ibnbresnet(blocks=50, model_name="ibnb_resnet50", **kwargs)
def ibnb_resnet101(**kwargs):
"""
IBN(b)-ResNet-101 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ibnbresnet(blocks=101, model_name="ibnb_resnet101", **kwargs)
def ibnb_resnet152(**kwargs):
"""
IBN(b)-ResNet-152 model from 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,'
https://arxiv.org/abs/1807.09441.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ibnbresnet(blocks=152, model_name="ibnb_resnet152", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
ibnb_resnet50,
ibnb_resnet101,
ibnb_resnet152,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != ibnb_resnet50 or weight_count == 25558568)
assert (model != ibnb_resnet101 or weight_count == 44550696)
assert (model != ibnb_resnet152 or weight_count == 60194344)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 13,442 | 31.007143 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/polynet.py | """
PolyNet for ImageNet-1K, implemented in Gluon.
Original paper: 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks,'
https://arxiv.org/abs/1611.05725.
"""
__all__ = ['PolyNet', 'polynet']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from mxnet.gluon.contrib.nn import HybridConcurrent
from .common import ConvBlock, conv1x1_block, conv3x3_block, ParametricSequential, ParametricConcurrent
class PolyConv(HybridBlock):
"""
PolyNet specific convolution block. A block that is used inside poly-N (poly-2, poly-3, and so on) modules.
The Convolution layer is shared between all Inception blocks inside a poly-N module. BatchNorm layers are not
shared between Inception blocks and therefore the number of BatchNorm layers is equal to the number of Inception
blocks inside a poly-N module.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
num_blocks : int
Number of blocks (BatchNorm layers).
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
bn_use_global_stats,
num_blocks,
**kwargs):
super(PolyConv, self).__init__(**kwargs)
with self.name_scope():
self.conv = nn.Conv2D(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
use_bias=False,
in_channels=in_channels)
for i in range(num_blocks):
setattr(self, "bn{}".format(i + 1), nn.BatchNorm(
in_channels=out_channels,
use_global_stats=bn_use_global_stats))
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x, index):
x = self.conv(x)
bn = getattr(self, "bn{}".format(index + 1))
x = bn(x)
x = self.activ(x)
return x
def poly_conv1x1(in_channels,
out_channels,
bn_use_global_stats,
num_blocks):
"""
1x1 version of the PolyNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
num_blocks : int
Number of blocks (BatchNorm layers).
"""
return PolyConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
strides=1,
padding=0,
bn_use_global_stats=bn_use_global_stats,
num_blocks=num_blocks)
class MaxPoolBranch(HybridBlock):
"""
PolyNet specific max pooling branch block.
"""
def __init__(self,
**kwargs):
super(MaxPoolBranch, self).__init__(**kwargs)
with self.name_scope():
self.pool = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=0)
def hybrid_forward(self, F, x):
x = self.pool(x)
return x
class Conv1x1Branch(HybridBlock):
"""
PolyNet specific convolutional 1x1 branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats,
**kwargs):
super(Conv1x1Branch, self).__init__(**kwargs)
with self.name_scope():
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv(x)
return x
class Conv3x3Branch(HybridBlock):
"""
PolyNet specific convolutional 3x3 branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats,
**kwargs):
super(Conv3x3Branch, self).__init__(**kwargs)
with self.name_scope():
self.conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
strides=2,
padding=0,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv(x)
return x
class ConvSeqBranch(HybridBlock):
"""
PolyNet specific convolutional sequence branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of tuple of int
List of numbers of output channels.
kernel_size_list : list of tuple of int or tuple of tuple/list of 2 int
List of convolution window sizes.
strides_list : list of tuple of int or tuple of tuple/list of 2 int
List of strides of the convolution.
padding_list : list of tuple of int or tuple of tuple/list of 2 int
List of padding values for convolution layers.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels_list,
kernel_size_list,
strides_list,
padding_list,
bn_use_global_stats,
**kwargs):
super(ConvSeqBranch, self).__init__(**kwargs)
assert (len(out_channels_list) == len(kernel_size_list))
assert (len(out_channels_list) == len(strides_list))
assert (len(out_channels_list) == len(padding_list))
with self.name_scope():
self.conv_list = nn.HybridSequential(prefix="")
for i, (out_channels, kernel_size, strides, padding) in enumerate(zip(
out_channels_list, kernel_size_list, strides_list, padding_list)):
self.conv_list.add(ConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
def hybrid_forward(self, F, x):
x = self.conv_list(x)
return x
class PolyConvSeqBranch(HybridBlock):
"""
PolyNet specific convolutional sequence branch block with internal PolyNet specific convolution blocks.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of tuple of int
List of numbers of output channels.
kernel_size_list : list of tuple of int or tuple of tuple/list of 2 int
List of convolution window sizes.
strides_list : list of tuple of int or tuple of tuple/list of 2 int
List of strides of the convolution.
padding_list : list of tuple of int or tuple of tuple/list of 2 int
List of padding values for convolution layers.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
num_blocks : int
Number of blocks for PolyConv.
"""
def __init__(self,
in_channels,
out_channels_list,
kernel_size_list,
strides_list,
padding_list,
bn_use_global_stats,
num_blocks,
**kwargs):
super(PolyConvSeqBranch, self).__init__(**kwargs)
assert (len(out_channels_list) == len(kernel_size_list))
assert (len(out_channels_list) == len(strides_list))
assert (len(out_channels_list) == len(padding_list))
with self.name_scope():
self.conv_list = ParametricSequential(prefix="")
for i, (out_channels, kernel_size, strides, padding) in enumerate(zip(
out_channels_list, kernel_size_list, strides_list, padding_list)):
self.conv_list.add(PolyConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
bn_use_global_stats=bn_use_global_stats,
num_blocks=num_blocks))
in_channels = out_channels
def hybrid_forward(self, F, x, index):
x = self.conv_list(x, index)
return x
class TwoWayABlock(HybridBlock):
"""
PolyNet type Inception-A block.
Parameters:
----------
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
bn_use_global_stats,
**kwargs):
super(TwoWayABlock, self).__init__(**kwargs)
in_channels = 384
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(32, 48, 64),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 1),
padding_list=(0, 1, 1),
bn_use_global_stats=bn_use_global_stats))
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(32, 32),
kernel_size_list=(1, 3),
strides_list=(1, 1),
padding_list=(0, 1),
bn_use_global_stats=bn_use_global_stats))
self.branches.add(Conv1x1Branch(
in_channels=in_channels,
out_channels=32,
bn_use_global_stats=bn_use_global_stats))
self.conv = conv1x1_block(
in_channels=128,
out_channels=in_channels,
bn_use_global_stats=bn_use_global_stats,
activation=None)
def hybrid_forward(self, F, x):
x = self.branches(x)
x = self.conv(x)
return x
class TwoWayBBlock(HybridBlock):
"""
PolyNet type Inception-B block.
Parameters:
----------
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
bn_use_global_stats,
**kwargs):
super(TwoWayBBlock, self).__init__(**kwargs)
in_channels = 1152
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(128, 160, 192),
kernel_size_list=(1, (1, 7), (7, 1)),
strides_list=(1, 1, 1),
padding_list=(0, (0, 3), (3, 0)),
bn_use_global_stats=bn_use_global_stats))
self.branches.add(Conv1x1Branch(
in_channels=in_channels,
out_channels=192,
bn_use_global_stats=bn_use_global_stats))
self.conv = conv1x1_block(
in_channels=384,
out_channels=in_channels,
bn_use_global_stats=bn_use_global_stats,
activation=None)
def hybrid_forward(self, F, x):
x = self.branches(x)
x = self.conv(x)
return x
class TwoWayCBlock(HybridBlock):
"""
PolyNet type Inception-C block.
Parameters:
----------
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
bn_use_global_stats,
**kwargs):
super(TwoWayCBlock, self).__init__(**kwargs)
in_channels = 2048
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(192, 224, 256),
kernel_size_list=(1, (1, 3), (3, 1)),
strides_list=(1, 1, 1),
padding_list=(0, (0, 1), (1, 0)),
bn_use_global_stats=bn_use_global_stats))
self.branches.add(Conv1x1Branch(
in_channels=in_channels,
out_channels=192,
bn_use_global_stats=bn_use_global_stats))
self.conv = conv1x1_block(
in_channels=448,
out_channels=in_channels,
bn_use_global_stats=bn_use_global_stats,
activation=None)
def hybrid_forward(self, F, x):
x = self.branches(x)
x = self.conv(x)
return x
class PolyPreBBlock(HybridBlock):
"""
PolyNet type PolyResidual-Pre-B block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
num_blocks : int
Number of blocks (BatchNorm layers).
"""
def __init__(self,
bn_use_global_stats,
num_blocks,
**kwargs):
super(PolyPreBBlock, self).__init__(**kwargs)
in_channels = 1152
with self.name_scope():
self.branches = ParametricConcurrent(axis=1, prefix="")
self.branches.add(PolyConvSeqBranch(
in_channels=in_channels,
out_channels_list=(128, 160, 192),
kernel_size_list=(1, (1, 7), (7, 1)),
strides_list=(1, 1, 1),
padding_list=(0, (0, 3), (3, 0)),
bn_use_global_stats=bn_use_global_stats,
num_blocks=num_blocks))
self.branches.add(poly_conv1x1(
in_channels=in_channels,
out_channels=192,
bn_use_global_stats=bn_use_global_stats,
num_blocks=num_blocks))
def hybrid_forward(self, F, x, index):
x = self.branches(x, index)
return x
class PolyPreCBlock(HybridBlock):
"""
PolyNet type PolyResidual-Pre-C block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
num_blocks : int
Number of blocks (BatchNorm layers).
"""
def __init__(self,
bn_use_global_stats,
num_blocks,
**kwargs):
super(PolyPreCBlock, self).__init__(**kwargs)
in_channels = 2048
with self.name_scope():
self.branches = ParametricConcurrent(axis=1, prefix="")
self.branches.add(PolyConvSeqBranch(
in_channels=in_channels,
out_channels_list=(192, 224, 256),
kernel_size_list=(1, (1, 3), (3, 1)),
strides_list=(1, 1, 1),
padding_list=(0, (0, 1), (1, 0)),
bn_use_global_stats=bn_use_global_stats,
num_blocks=num_blocks))
self.branches.add(poly_conv1x1(
in_channels=in_channels,
out_channels=192,
bn_use_global_stats=bn_use_global_stats,
num_blocks=num_blocks))
def hybrid_forward(self, F, x, index):
x = self.branches(x, index)
return x
def poly_res_b_block(bn_use_global_stats):
"""
PolyNet type PolyResidual-Res-B block.
Parameters:
----------
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
return conv1x1_block(
in_channels=384,
out_channels=1152,
strides=1,
bn_use_global_stats=bn_use_global_stats,
activation=None)
def poly_res_c_block(bn_use_global_stats):
"""
PolyNet type PolyResidual-Res-C block.
Parameters:
----------
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
return conv1x1_block(
in_channels=448,
out_channels=2048,
strides=1,
bn_use_global_stats=bn_use_global_stats,
activation=None)
class MultiResidual(HybridBlock):
"""
Base class for constructing N-way modules (2-way, 3-way, and so on). Actually it is for 2-way modules.
Parameters:
----------
scale : float, default 1.0
Scale value for each residual branch.
res_block : HybridBlock class
Residual branch block.
num_blocks : int
Number of residual branches.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
scale,
res_block,
num_blocks,
bn_use_global_stats,
**kwargs):
super(MultiResidual, self).__init__(**kwargs)
assert (num_blocks >= 1)
self.scale = scale
self.num_blocks = num_blocks
with self.name_scope():
for i in range(num_blocks):
setattr(self, "res_block{}".format(i + 1), res_block(bn_use_global_stats=bn_use_global_stats))
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
out = x
for i in range(self.num_blocks):
res_block = getattr(self, "res_block{}".format(i + 1))
out = out + self.scale * res_block(x)
out = self.activ(out)
return out
class PolyResidual(HybridBlock):
"""
The other base class for constructing N-way poly-modules. Actually it is for 3-way poly-modules.
Parameters:
----------
scale : float, default 1.0
Scale value for each residual branch.
res_block : HybridBlock class
Residual branch block.
num_blocks : int
Number of residual branches.
pre_block : HybridBlock class
Preliminary block.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
scale,
res_block,
num_blocks,
pre_block,
bn_use_global_stats,
**kwargs):
super(PolyResidual, self).__init__(**kwargs)
assert (num_blocks >= 1)
self.scale = scale
self.num_blocks = num_blocks
with self.name_scope():
self.pre_block = pre_block(
bn_use_global_stats=bn_use_global_stats,
num_blocks=num_blocks)
for i in range(num_blocks):
setattr(self, "res_block{}".format(i + 1), res_block(bn_use_global_stats=bn_use_global_stats))
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
out = x
for index in range(self.num_blocks):
x = self.pre_block(x, index)
res_block = getattr(self, "res_block{}".format(index + 1))
x = res_block(x)
out = out + self.scale * x
x = self.activ(x)
out = self.activ(out)
return out
class PolyBaseUnit(HybridBlock):
"""
PolyNet unit base class.
Parameters:
----------
two_way_scale : float
Scale value for 2-way stage.
two_way_block : HybridBlock class
Residual branch block for 2-way-stage.
poly_scale : float, default 0.0
Scale value for 2-way stage.
poly_res_block : HybridBlock class, default None
Residual branch block for poly-stage.
poly_pre_block : HybridBlock class, default None
Preliminary branch block for poly-stage.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
two_way_scale,
two_way_block,
poly_scale=0.0,
poly_res_block=None,
poly_pre_block=None,
bn_use_global_stats=False,
**kwargs):
super(PolyBaseUnit, self).__init__(**kwargs)
with self.name_scope():
if poly_res_block is not None:
assert (poly_scale != 0.0)
assert (poly_pre_block is not None)
self.poly = PolyResidual(
scale=poly_scale,
res_block=poly_res_block,
num_blocks=3,
pre_block=poly_pre_block,
bn_use_global_stats=bn_use_global_stats)
else:
assert (poly_scale == 0.0)
assert (poly_pre_block is None)
self.poly = None
self.twoway = MultiResidual(
scale=two_way_scale,
res_block=two_way_block,
num_blocks=2,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
if self.poly is not None:
x = self.poly(x)
x = self.twoway(x)
return x
class PolyAUnit(PolyBaseUnit):
"""
PolyNet type A unit.
Parameters:
----------
two_way_scale : float
Scale value for 2-way stage.
poly_scale : float
Scale value for 2-way stage.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
two_way_scale,
poly_scale=0.0,
bn_use_global_stats=False,
**kwargs):
super(PolyAUnit, self).__init__(
two_way_scale=two_way_scale,
two_way_block=TwoWayABlock,
bn_use_global_stats=bn_use_global_stats,
**kwargs)
assert (poly_scale == 0.0)
class PolyBUnit(PolyBaseUnit):
"""
PolyNet type B unit.
Parameters:
----------
two_way_scale : float
Scale value for 2-way stage.
poly_scale : float
Scale value for 2-way stage.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
two_way_scale,
poly_scale,
bn_use_global_stats,
**kwargs):
super(PolyBUnit, self).__init__(
two_way_scale=two_way_scale,
two_way_block=TwoWayBBlock,
poly_scale=poly_scale,
poly_res_block=poly_res_b_block,
poly_pre_block=PolyPreBBlock,
bn_use_global_stats=bn_use_global_stats,
**kwargs)
class PolyCUnit(PolyBaseUnit):
"""
PolyNet type C unit.
Parameters:
----------
two_way_scale : float
Scale value for 2-way stage.
poly_scale : float
Scale value for 2-way stage.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
two_way_scale,
poly_scale,
bn_use_global_stats,
**kwargs):
super(PolyCUnit, self).__init__(
two_way_scale=two_way_scale,
two_way_block=TwoWayCBlock,
poly_scale=poly_scale,
poly_res_block=poly_res_c_block,
poly_pre_block=PolyPreCBlock,
bn_use_global_stats=bn_use_global_stats,
**kwargs)
class ReductionAUnit(HybridBlock):
"""
PolyNet type Reduction-A unit.
Parameters:
----------
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
bn_use_global_stats,
**kwargs):
super(ReductionAUnit, self).__init__(**kwargs)
in_channels = 384
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(256, 256, 384),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 2),
padding_list=(0, 1, 0),
bn_use_global_stats=bn_use_global_stats))
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(384,),
kernel_size_list=(3,),
strides_list=(2,),
padding_list=(0,),
bn_use_global_stats=bn_use_global_stats))
self.branches.add(MaxPoolBranch())
def hybrid_forward(self, F, x):
x = self.branches(x)
return x
class ReductionBUnit(HybridBlock):
"""
PolyNet type Reduction-B unit.
Parameters:
----------
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
bn_use_global_stats,
**kwargs):
super(ReductionBUnit, self).__init__(**kwargs)
in_channels = 1152
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(256, 256, 256),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 2),
padding_list=(0, 1, 0),
bn_use_global_stats=bn_use_global_stats))
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(256, 256),
kernel_size_list=(1, 3),
strides_list=(1, 2),
padding_list=(0, 0),
bn_use_global_stats=bn_use_global_stats))
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(256, 384),
kernel_size_list=(1, 3),
strides_list=(1, 2),
padding_list=(0, 0),
bn_use_global_stats=bn_use_global_stats))
self.branches.add(MaxPoolBranch())
def hybrid_forward(self, F, x):
x = self.branches(x)
return x
class PolyBlock3a(HybridBlock):
"""
PolyNet type Mixed-3a block.
Parameters:
----------
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
bn_use_global_stats,
**kwargs):
super(PolyBlock3a, self).__init__(**kwargs)
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(MaxPoolBranch())
self.branches.add(Conv3x3Branch(
in_channels=64,
out_channels=96,
bn_use_global_stats=bn_use_global_stats))
def hybrid_forward(self, F, x):
x = self.branches(x)
return x
class PolyBlock4a(HybridBlock):
"""
PolyNet type Mixed-4a block.
Parameters:
----------
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
bn_use_global_stats,
**kwargs):
super(PolyBlock4a, self).__init__(**kwargs)
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(ConvSeqBranch(
in_channels=160,
out_channels_list=(64, 96),
kernel_size_list=(1, 3),
strides_list=(1, 1),
padding_list=(0, 0),
bn_use_global_stats=bn_use_global_stats))
self.branches.add(ConvSeqBranch(
in_channels=160,
out_channels_list=(64, 64, 64, 96),
kernel_size_list=(1, (7, 1), (1, 7), 3),
strides_list=(1, 1, 1, 1),
padding_list=(0, (3, 0), (0, 3), 0),
bn_use_global_stats=bn_use_global_stats))
def hybrid_forward(self, F, x):
x = self.branches(x)
return x
class PolyBlock5a(HybridBlock):
"""
PolyNet type Mixed-5a block.
Parameters:
----------
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
bn_use_global_stats,
**kwargs):
super(PolyBlock5a, self).__init__(**kwargs)
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(MaxPoolBranch())
self.branches.add(Conv3x3Branch(
in_channels=192,
out_channels=192,
bn_use_global_stats=bn_use_global_stats))
def hybrid_forward(self, F, x):
x = self.branches(x)
return x
class PolyInitBlock(HybridBlock):
"""
PolyNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
bn_use_global_stats,
**kwargs):
super(PolyInitBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=32,
strides=2,
padding=0,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = conv3x3_block(
in_channels=32,
out_channels=32,
padding=0,
bn_use_global_stats=bn_use_global_stats)
self.conv3 = conv3x3_block(
in_channels=32,
out_channels=64,
bn_use_global_stats=bn_use_global_stats)
self.block1 = PolyBlock3a(bn_use_global_stats=bn_use_global_stats)
self.block2 = PolyBlock4a(bn_use_global_stats=bn_use_global_stats)
self.block3 = PolyBlock5a(bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
return x
class PolyNet(HybridBlock):
"""
PolyNet model from 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks,'
https://arxiv.org/abs/1611.05725.
Parameters:
----------
two_way_scales : list of list of floats
Two way scale values for each normal unit.
poly_scales : list of list of floats
Three way scale values for each normal unit.
dropout_rate : float, default 0.2
Fraction of the input units to drop. Must be a number between 0 and 1.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (331, 331)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
two_way_scales,
poly_scales,
dropout_rate=0.2,
bn_use_global_stats=False,
in_channels=3,
in_size=(331, 331),
classes=1000,
**kwargs):
super(PolyNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
normal_units = [PolyAUnit, PolyBUnit, PolyCUnit]
reduction_units = [ReductionAUnit, ReductionBUnit]
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(PolyInitBlock(
in_channels=in_channels,
bn_use_global_stats=bn_use_global_stats))
for i, (two_way_scales_per_stage, poly_scales_per_stage) in enumerate(zip(two_way_scales, poly_scales)):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, (two_way_scale, poly_scale) in enumerate(zip(two_way_scales_per_stage, poly_scales_per_stage)):
if (j == 0) and (i != 0):
unit = reduction_units[i - 1]
stage.add(unit(bn_use_global_stats=bn_use_global_stats))
else:
unit = normal_units[i]
stage.add(unit(
two_way_scale=two_way_scale,
poly_scale=poly_scale,
bn_use_global_stats=bn_use_global_stats))
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=9,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dropout(rate=dropout_rate))
self.output.add(nn.Dense(
units=classes,
in_units=2048))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_polynet(model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create PolyNet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
two_way_scales = [
[1.000000, 0.992308, 0.984615, 0.976923, 0.969231, 0.961538, 0.953846, 0.946154, 0.938462, 0.930769],
[0.000000, 0.915385, 0.900000, 0.884615, 0.869231, 0.853846, 0.838462, 0.823077, 0.807692, 0.792308, 0.776923],
[0.000000, 0.761538, 0.746154, 0.730769, 0.715385, 0.700000]]
poly_scales = [
[0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],
[0.000000, 0.923077, 0.907692, 0.892308, 0.876923, 0.861538, 0.846154, 0.830769, 0.815385, 0.800000, 0.784615],
[0.000000, 0.769231, 0.753846, 0.738462, 0.723077, 0.707692]]
net = PolyNet(
two_way_scales=two_way_scales,
poly_scales=poly_scales,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def polynet(**kwargs):
"""
PolyNet model from 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks,'
https://arxiv.org/abs/1611.05725.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_polynet(model_name="polynet", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
polynet,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != polynet or weight_count == 95366600)
x = mx.nd.zeros((1, 3, 331, 331), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 38,413 | 32.52007 | 122 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/resnet_cifar.py | """
ResNet for CIFAR/SVHN, implemented in Gluon.
Original paper: 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
"""
__all__ = ['CIFARResNet', 'resnet20_cifar10', 'resnet20_cifar100', 'resnet20_svhn',
'resnet56_cifar10', 'resnet56_cifar100', 'resnet56_svhn',
'resnet110_cifar10', 'resnet110_cifar100', 'resnet110_svhn',
'resnet164bn_cifar10', 'resnet164bn_cifar100', 'resnet164bn_svhn',
'resnet272bn_cifar10', 'resnet272bn_cifar100', 'resnet272bn_svhn',
'resnet542bn_cifar10', 'resnet542bn_cifar100', 'resnet542bn_svhn',
'resnet1001_cifar10', 'resnet1001_cifar100', 'resnet1001_svhn',
'resnet1202_cifar10', 'resnet1202_cifar100', 'resnet1202_svhn']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv3x3_block
from .resnet import ResUnit
class CIFARResNet(HybridBlock):
"""
ResNet model for CIFAR from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
bn_use_global_stats=False,
in_channels=3,
in_size=(32, 32),
classes=10,
**kwargs):
super(CIFARResNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
stage.add(ResUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bottleneck=bottleneck,
conv1_stride=False))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=8,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_resnet_cifar(classes,
blocks,
bottleneck,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create ResNet model for CIFAR with specific parameters.
Parameters:
----------
classes : int
Number of classification classes.
blocks : int
Number of blocks.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
assert (classes in [10, 100])
if bottleneck:
assert ((blocks - 2) % 9 == 0)
layers = [(blocks - 2) // 9] * 3
else:
assert ((blocks - 2) % 6 == 0)
layers = [(blocks - 2) // 6] * 3
channels_per_layers = [16, 32, 64]
init_block_channels = 16
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if bottleneck:
channels = [[cij * 4 for cij in ci] for ci in channels]
net = CIFARResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
classes=classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def resnet20_cifar10(classes=10, **kwargs):
"""
ResNet-20 model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="resnet20_cifar10", **kwargs)
def resnet20_cifar100(classes=100, **kwargs):
"""
ResNet-20 model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="resnet20_cifar100", **kwargs)
def resnet20_svhn(classes=10, **kwargs):
"""
ResNet-20 model for SVHN from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="resnet20_svhn", **kwargs)
def resnet56_cifar10(classes=10, **kwargs):
"""
ResNet-56 model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name="resnet56_cifar10", **kwargs)
def resnet56_cifar100(classes=100, **kwargs):
"""
ResNet-56 model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name="resnet56_cifar100", **kwargs)
def resnet56_svhn(classes=10, **kwargs):
"""
ResNet-56 model for SVHN from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name="resnet56_svhn", **kwargs)
def resnet110_cifar10(classes=10, **kwargs):
"""
ResNet-110 model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name="resnet110_cifar10", **kwargs)
def resnet110_cifar100(classes=100, **kwargs):
"""
ResNet-110 model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name="resnet110_cifar100", **kwargs)
def resnet110_svhn(classes=10, **kwargs):
"""
ResNet-110 model for SVHN from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name="resnet110_svhn", **kwargs)
def resnet164bn_cifar10(classes=10, **kwargs):
"""
ResNet-164(BN) model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name="resnet164bn_cifar10", **kwargs)
def resnet164bn_cifar100(classes=100, **kwargs):
"""
ResNet-164(BN) model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name="resnet164bn_cifar100", **kwargs)
def resnet164bn_svhn(classes=10, **kwargs):
"""
ResNet-164(BN) model for SVHN from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name="resnet164bn_svhn", **kwargs)
def resnet272bn_cifar10(classes=10, **kwargs):
"""
ResNet-272(BN) model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name="resnet272bn_cifar10", **kwargs)
def resnet272bn_cifar100(classes=100, **kwargs):
"""
ResNet-272(BN) model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name="resnet272bn_cifar100", **kwargs)
def resnet272bn_svhn(classes=10, **kwargs):
"""
ResNet-272(BN) model for SVHN from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name="resnet272bn_svhn", **kwargs)
def resnet542bn_cifar10(classes=10, **kwargs):
"""
ResNet-542(BN) model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name="resnet542bn_cifar10", **kwargs)
def resnet542bn_cifar100(classes=100, **kwargs):
"""
ResNet-542(BN) model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name="resnet542bn_cifar100", **kwargs)
def resnet542bn_svhn(classes=10, **kwargs):
"""
ResNet-272(BN) model for SVHN from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name="resnet542bn_svhn", **kwargs)
def resnet1001_cifar10(classes=10, **kwargs):
"""
ResNet-1001 model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="resnet1001_cifar10", **kwargs)
def resnet1001_cifar100(classes=100, **kwargs):
"""
ResNet-1001 model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="resnet1001_cifar100", **kwargs)
def resnet1001_svhn(classes=10, **kwargs):
"""
ResNet-1001 model for SVHN from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="resnet1001_svhn", **kwargs)
def resnet1202_cifar10(classes=10, **kwargs):
"""
ResNet-1202 model for CIFAR-10 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name="resnet1202_cifar10", **kwargs)
def resnet1202_cifar100(classes=100, **kwargs):
"""
ResNet-1202 model for CIFAR-100 from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name="resnet1202_cifar100", **kwargs)
def resnet1202_svhn(classes=10, **kwargs):
"""
ResNet-1202 model for SVHN from 'Deep Residual Learning for Image Recognition,'
https://arxiv.org/abs/1512.03385.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name="resnet1202_svhn", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
(resnet20_cifar10, 10),
(resnet20_cifar100, 100),
(resnet20_svhn, 10),
(resnet56_cifar10, 10),
(resnet56_cifar100, 100),
(resnet56_svhn, 10),
(resnet110_cifar10, 10),
(resnet110_cifar100, 100),
(resnet110_svhn, 10),
(resnet164bn_cifar10, 10),
(resnet164bn_cifar100, 100),
(resnet164bn_svhn, 10),
(resnet272bn_cifar10, 10),
(resnet272bn_cifar100, 100),
(resnet272bn_svhn, 10),
(resnet542bn_cifar10, 10),
(resnet542bn_cifar100, 100),
(resnet542bn_svhn, 10),
(resnet1001_cifar10, 10),
(resnet1001_cifar100, 100),
(resnet1001_svhn, 10),
(resnet1202_cifar10, 10),
(resnet1202_cifar100, 100),
(resnet1202_svhn, 10),
]
for model, classes in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != resnet20_cifar10 or weight_count == 272474)
assert (model != resnet20_cifar100 or weight_count == 278324)
assert (model != resnet20_svhn or weight_count == 272474)
assert (model != resnet56_cifar10 or weight_count == 855770)
assert (model != resnet56_cifar100 or weight_count == 861620)
assert (model != resnet56_svhn or weight_count == 855770)
assert (model != resnet110_cifar10 or weight_count == 1730714)
assert (model != resnet110_cifar100 or weight_count == 1736564)
assert (model != resnet110_svhn or weight_count == 1730714)
assert (model != resnet164bn_cifar10 or weight_count == 1704154)
assert (model != resnet164bn_cifar100 or weight_count == 1727284)
assert (model != resnet164bn_svhn or weight_count == 1704154)
assert (model != resnet272bn_cifar10 or weight_count == 2816986)
assert (model != resnet272bn_cifar100 or weight_count == 2840116)
assert (model != resnet272bn_svhn or weight_count == 2816986)
assert (model != resnet542bn_cifar10 or weight_count == 5599066)
assert (model != resnet542bn_cifar100 or weight_count == 5622196)
assert (model != resnet542bn_svhn or weight_count == 5599066)
assert (model != resnet1001_cifar10 or weight_count == 10328602)
assert (model != resnet1001_cifar100 or weight_count == 10351732)
assert (model != resnet1001_svhn or weight_count == 10328602)
assert (model != resnet1202_cifar10 or weight_count == 19424026)
assert (model != resnet1202_cifar100 or weight_count == 19429876)
assert (model != resnet1202_svhn or weight_count == 19424026)
x = mx.nd.zeros((1, 3, 32, 32), ctx=ctx)
y = net(x)
assert (y.shape == (1, classes))
if __name__ == "__main__":
_test()
| 25,521 | 36.09593 | 120 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/nasnet.py | """
NASNet-A for ImageNet-1K, implemented in Gluon.
Original paper: 'Learning Transferable Architectures for Scalable Image Recognition,'
https://arxiv.org/abs/1707.07012.
"""
__all__ = ['NASNet', 'nasnet_4a1056', 'nasnet_6a4032', 'nasnet_dual_path_sequential']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1, DualPathSequential
class NasDualPathScheme(object):
"""
NASNet specific scheme of dual path response for a block in a DualPathSequential module.
Parameters:
----------
can_skip_input : bool
Whether can skip input for some blocks.
"""
def __init__(self,
can_skip_input):
super(NasDualPathScheme, self).__init__()
self.can_skip_input = can_skip_input
"""
Scheme function.
Parameters:
----------
block : nn.HybridBlock
A block.
x : Tensor
Current processed tensor.
x_prev : Tensor
Previous processed tensor.
Returns:
-------
x_next : Tensor
Next processed tensor.
x : Tensor
Current processed tensor.
"""
def __call__(self,
block,
x,
x_prev):
x_next = block(x, x_prev)
if type(x_next) == tuple:
x_next, x = x_next
if self.can_skip_input and hasattr(block, 'skip_input') and block.skip_input:
x = x_prev
return x_next, x
def nasnet_dual_path_scheme_ordinal(block,
x,
_):
"""
NASNet specific scheme of dual path response for an ordinal block with dual inputs/outputs in a DualPathSequential
block.
Parameters:
----------
block : nn.HybridBlock
A block.
x : Tensor
Current processed tensor.
Returns:
-------
x_next : Tensor
Next processed tensor.
x : Tensor
Current processed tensor.
"""
return block(x), x
def nasnet_dual_path_sequential(return_two=True,
first_ordinals=0,
last_ordinals=0,
can_skip_input=False,
**kwargs):
"""
NASNet specific dual path sequential container.
Parameters:
----------
return_two : bool, default True
Whether to return two output after execution.
first_ordinals : int, default 0
Number of the first blocks with single input/output.
last_ordinals : int, default 0
Number of the final blocks with single input/output.
dual_path_scheme : function
Scheme of dual path response for a block.
dual_path_scheme_ordinal : function
Scheme of dual path response for an ordinal block.
can_skip_input : bool, default False
Whether can skip input for some blocks.
"""
return DualPathSequential(
return_two=return_two,
first_ordinals=first_ordinals,
last_ordinals=last_ordinals,
dual_path_scheme=NasDualPathScheme(can_skip_input=can_skip_input),
dual_path_scheme_ordinal=nasnet_dual_path_scheme_ordinal,
**kwargs)
def nasnet_batch_norm(channels):
"""
NASNet specific Batch normalization layer.
Parameters:
----------
channels : int
Number of channels in input data.
"""
return nn.BatchNorm(
momentum=0.1,
epsilon=0.001,
in_channels=channels)
def nasnet_avgpool1x1_s2():
"""
NASNet specific 1x1 Average pooling layer with stride 2.
"""
return nn.AvgPool2D(
pool_size=1,
strides=2,
count_include_pad=False)
def nasnet_avgpool3x3_s1():
"""
NASNet specific 3x3 Average pooling layer with stride 1.
"""
return nn.AvgPool2D(
pool_size=3,
strides=1,
padding=1,
count_include_pad=False)
def nasnet_avgpool3x3_s2():
"""
NASNet specific 3x3 Average pooling layer with stride 2.
"""
return nn.AvgPool2D(
pool_size=3,
strides=2,
padding=1,
count_include_pad=False)
def process_with_padding(x,
F,
process=(lambda x: x),
pad_width=(0, 0, 0, 0, 1, 0, 1, 0)):
"""
Auxiliary decorator for layer with NASNet specific extra padding.
Parameters:
----------
x : NDArray
Input tensor.
F : module
Gluon API module.
process : function, default (lambda x: x)
a decorated layer
pad_width : tuple of int, default (0, 0, 0, 0, 1, 0, 1, 0)
Whether the layer uses a bias vector.
Returns:
-------
NDArray
Resulted tensor.
"""
x = F.pad(x, mode="constant", pad_width=pad_width, constant_value=0)
x = process(x)
x = F.slice(x, begin=(None, None, 1, 1), end=(None, None, None, None))
return x
class NasMaxPoolBlock(HybridBlock):
"""
NASNet specific Max pooling layer with extra padding.
Parameters:
----------
extra_padding : bool, default False
Whether to use extra padding.
"""
def __init__(self,
extra_padding=False,
**kwargs):
super(NasMaxPoolBlock, self).__init__(**kwargs)
self.extra_padding = extra_padding
with self.name_scope():
self.pool = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=1)
def hybrid_forward(self, F, x):
if self.extra_padding:
x = process_with_padding(x, F, self.pool)
else:
x = self.pool(x)
return x
class NasAvgPoolBlock(HybridBlock):
"""
NASNet specific 3x3 Average pooling layer with extra padding.
Parameters:
----------
extra_padding : bool, default False
Whether to use extra padding.
"""
def __init__(self,
extra_padding=False,
**kwargs):
super(NasAvgPoolBlock, self).__init__(**kwargs)
self.extra_padding = extra_padding
with self.name_scope():
self.pool = nn.AvgPool2D(
pool_size=3,
strides=2,
padding=1,
count_include_pad=False)
def hybrid_forward(self, F, x):
if self.extra_padding:
x = process_with_padding(x, F, self.pool)
else:
x = self.pool(x)
return x
class NasConv(HybridBlock):
"""
NASNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
groups : int
Number of groups.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
groups,
**kwargs):
super(NasConv, self).__init__(**kwargs)
with self.name_scope():
self.activ = nn.Activation("relu")
self.conv = nn.Conv2D(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
groups=groups,
use_bias=False,
in_channels=in_channels)
self.bn = nasnet_batch_norm(channels=out_channels)
def hybrid_forward(self, F, x):
x = self.activ(x)
x = self.conv(x)
x = self.bn(x)
return x
def nas_conv1x1(in_channels,
out_channels):
"""
1x1 version of the NASNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
return NasConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
strides=1,
padding=0,
groups=1)
class DwsConv(HybridBlock):
"""
Standard depthwise separable convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
use_bias : bool, default False
Whether the layers use a bias vector.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
use_bias=False,
**kwargs):
super(DwsConv, self).__init__(**kwargs)
with self.name_scope():
self.dw_conv = nn.Conv2D(
channels=in_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
groups=in_channels,
use_bias=use_bias,
in_channels=in_channels)
self.pw_conv = conv1x1(
in_channels=in_channels,
out_channels=out_channels,
use_bias=use_bias)
def hybrid_forward(self, F, x):
x = self.dw_conv(x)
x = self.pw_conv(x)
return x
class NasDwsConv(HybridBlock):
"""
NASNet specific depthwise separable convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
extra_padding : bool, default False
Whether to use extra padding.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
extra_padding=False,
**kwargs):
super(NasDwsConv, self).__init__(**kwargs)
self.extra_padding = extra_padding
with self.name_scope():
self.activ = nn.Activation(activation="relu")
self.conv = DwsConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
use_bias=False)
self.bn = nasnet_batch_norm(channels=out_channels)
def hybrid_forward(self, F, x):
x = self.activ(x)
if self.extra_padding:
x = process_with_padding(x, F, self.conv)
else:
x = self.conv(x)
x = self.bn(x)
return x
class DwsBranch(HybridBlock):
"""
NASNet specific block with depthwise separable convolution layers.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
extra_padding : bool, default False
Whether to use extra padding.
stem : bool, default False
Whether to use squeeze reduction if False.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
extra_padding=False,
stem=False,
**kwargs):
super(DwsBranch, self).__init__(**kwargs)
assert (not stem) or (not extra_padding)
mid_channels = out_channels if stem else in_channels
with self.name_scope():
self.conv1 = NasDwsConv(
in_channels=in_channels,
out_channels=mid_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
extra_padding=extra_padding)
self.conv2 = NasDwsConv(
in_channels=mid_channels,
out_channels=out_channels,
kernel_size=kernel_size,
strides=1,
padding=padding)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
return x
def dws_branch_k3_s1_p1(in_channels,
out_channels,
extra_padding=False):
"""
3x3/1/1 version of the NASNet specific depthwise separable convolution branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
extra_padding : bool, default False
Whether to use extra padding.
"""
return DwsBranch(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
strides=1,
padding=1,
extra_padding=extra_padding)
def dws_branch_k5_s1_p2(in_channels,
out_channels,
extra_padding=False):
"""
5x5/1/2 version of the NASNet specific depthwise separable convolution branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
extra_padding : bool, default False
Whether to use extra padding.
"""
return DwsBranch(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=5,
strides=1,
padding=2,
extra_padding=extra_padding)
def dws_branch_k5_s2_p2(in_channels,
out_channels,
extra_padding=False,
stem=False):
"""
5x5/2/2 version of the NASNet specific depthwise separable convolution branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
extra_padding : bool, default False
Whether to use extra padding.
stem : bool, default False
Whether to use squeeze reduction if False.
"""
return DwsBranch(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=5,
strides=2,
padding=2,
extra_padding=extra_padding,
stem=stem)
def dws_branch_k7_s2_p3(in_channels,
out_channels,
extra_padding=False,
stem=False):
"""
7x7/2/3 version of the NASNet specific depthwise separable convolution branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
extra_padding : bool, default False
Whether to use extra padding.
stem : bool, default False
Whether to use squeeze reduction if False.
"""
return DwsBranch(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=7,
strides=2,
padding=3,
extra_padding=extra_padding,
stem=stem)
class NasPathBranch(HybridBlock):
"""
NASNet specific `path` branch (auxiliary block).
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
extra_padding : bool, default False
Whether to use extra padding.
"""
def __init__(self,
in_channels,
out_channels,
extra_padding=False,
**kwargs):
super(NasPathBranch, self).__init__(**kwargs)
self.extra_padding = extra_padding
with self.name_scope():
self.avgpool = nasnet_avgpool1x1_s2()
self.conv = conv1x1(
in_channels=in_channels,
out_channels=out_channels)
def hybrid_forward(self, F, x):
if self.extra_padding:
x = process_with_padding(x, F, pad_width=(0, 0, 0, 0, 0, 1, 0, 1))
x = self.avgpool(x)
x = self.conv(x)
return x
class NasPathBlock(HybridBlock):
"""
NASNet specific `path` block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels,
**kwargs):
super(NasPathBlock, self).__init__(**kwargs)
mid_channels = out_channels // 2
with self.name_scope():
self.activ = nn.Activation("relu")
self.path1 = NasPathBranch(
in_channels=in_channels,
out_channels=mid_channels)
self.path2 = NasPathBranch(
in_channels=in_channels,
out_channels=mid_channels,
extra_padding=True)
self.bn = nasnet_batch_norm(channels=out_channels)
def hybrid_forward(self, F, x):
x = self.activ(x)
x1 = self.path1(x)
x2 = self.path2(x)
x = F.concat(x1, x2, dim=1)
x = self.bn(x)
return x
class Stem1Unit(HybridBlock):
"""
NASNet Stem1 unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels,
**kwargs):
super(Stem1Unit, self).__init__(**kwargs)
mid_channels = out_channels // 4
with self.name_scope():
self.conv1x1 = nas_conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.comb0_left = dws_branch_k5_s2_p2(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb0_right = dws_branch_k7_s2_p3(
in_channels=in_channels,
out_channels=mid_channels,
stem=True)
self.comb1_left = NasMaxPoolBlock(extra_padding=False)
self.comb1_right = dws_branch_k7_s2_p3(
in_channels=in_channels,
out_channels=mid_channels,
stem=True)
self.comb2_left = nasnet_avgpool3x3_s2()
self.comb2_right = dws_branch_k5_s2_p2(
in_channels=in_channels,
out_channels=mid_channels,
stem=True)
self.comb3_right = nasnet_avgpool3x3_s1()
self.comb4_left = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb4_right = NasMaxPoolBlock(extra_padding=False)
def hybrid_forward(self, F, x, _=None):
x_left = self.conv1x1(x)
x_right = x
x0 = self.comb0_left(x_left) + self.comb0_right(x_right)
x1 = self.comb1_left(x_left) + self.comb1_right(x_right)
x2 = self.comb2_left(x_left) + self.comb2_right(x_right)
x3 = x1 + self.comb3_right(x0)
x4 = self.comb4_left(x0) + self.comb4_right(x_left)
x_out = F.concat(x1, x2, x3, x4, dim=1)
return x_out
class Stem2Unit(HybridBlock):
"""
NASNet Stem2 unit.
Parameters:
----------
in_channels : int
Number of input channels.
prev_in_channels : int
Number of input channels in previous input.
out_channels : int
Number of output channels.
extra_padding : bool
Whether to use extra padding.
"""
def __init__(self,
in_channels,
prev_in_channels,
out_channels,
extra_padding,
**kwargs):
super(Stem2Unit, self).__init__(**kwargs)
mid_channels = out_channels // 4
with self.name_scope():
self.conv1x1 = nas_conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.path = NasPathBlock(
in_channels=prev_in_channels,
out_channels=mid_channels)
self.comb0_left = dws_branch_k5_s2_p2(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb0_right = dws_branch_k7_s2_p3(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb1_left = NasMaxPoolBlock(extra_padding=extra_padding)
self.comb1_right = dws_branch_k7_s2_p3(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb2_left = NasAvgPoolBlock(extra_padding=extra_padding)
self.comb2_right = dws_branch_k5_s2_p2(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb3_right = nasnet_avgpool3x3_s1()
self.comb4_left = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb4_right = NasMaxPoolBlock(extra_padding=extra_padding)
def hybrid_forward(self, F, x, x_prev):
x_left = self.conv1x1(x)
x_right = self.path(x_prev)
x0 = self.comb0_left(x_left) + self.comb0_right(x_right)
x1 = self.comb1_left(x_left) + self.comb1_right(x_right)
x2 = self.comb2_left(x_left) + self.comb2_right(x_right)
x3 = x1 + self.comb3_right(x0)
x4 = self.comb4_left(x0) + self.comb4_right(x_left)
x_out = F.concat(x1, x2, x3, x4, dim=1)
return x_out
class FirstUnit(HybridBlock):
"""
NASNet First unit.
Parameters:
----------
in_channels : int
Number of input channels.
prev_in_channels : int
Number of input channels in previous input.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
prev_in_channels,
out_channels,
**kwargs):
super(FirstUnit, self).__init__(**kwargs)
mid_channels = out_channels // 6
with self.name_scope():
self.conv1x1 = nas_conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.path = NasPathBlock(
in_channels=prev_in_channels,
out_channels=mid_channels)
self.comb0_left = dws_branch_k5_s1_p2(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb0_right = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb1_left = dws_branch_k5_s1_p2(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb1_right = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb2_left = nasnet_avgpool3x3_s1()
self.comb3_left = nasnet_avgpool3x3_s1()
self.comb3_right = nasnet_avgpool3x3_s1()
self.comb4_left = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels)
def hybrid_forward(self, F, x, x_prev):
x_left = self.conv1x1(x)
x_right = self.path(x_prev)
x0 = self.comb0_left(x_left) + self.comb0_right(x_right)
x1 = self.comb1_left(x_right) + self.comb1_right(x_right)
x2 = self.comb2_left(x_left) + x_right
x3 = self.comb3_left(x_right) + self.comb3_right(x_right)
x4 = self.comb4_left(x_left) + x_left
x_out = F.concat(x_right, x0, x1, x2, x3, x4, dim=1)
return x_out
class NormalUnit(HybridBlock):
"""
NASNet Normal unit.
Parameters:
----------
in_channels : int
Number of input channels.
prev_in_channels : int
Number of input channels in previous input.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
prev_in_channels,
out_channels,
**kwargs):
super(NormalUnit, self).__init__(**kwargs)
mid_channels = out_channels // 6
with self.name_scope():
self.conv1x1_prev = nas_conv1x1(
in_channels=prev_in_channels,
out_channels=mid_channels)
self.conv1x1 = nas_conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.comb0_left = dws_branch_k5_s1_p2(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb0_right = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb1_left = dws_branch_k5_s1_p2(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb1_right = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels)
self.comb2_left = nasnet_avgpool3x3_s1()
self.comb3_left = nasnet_avgpool3x3_s1()
self.comb3_right = nasnet_avgpool3x3_s1()
self.comb4_left = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels)
def hybrid_forward(self, F, x, x_prev):
x_left = self.conv1x1(x)
x_right = self.conv1x1_prev(x_prev)
x0 = self.comb0_left(x_left) + self.comb0_right(x_right)
x1 = self.comb1_left(x_right) + self.comb1_right(x_right)
x2 = self.comb2_left(x_left) + x_right
x3 = self.comb3_left(x_right) + self.comb3_right(x_right)
x4 = self.comb4_left(x_left) + x_left
x_out = F.concat(x_right, x0, x1, x2, x3, x4, dim=1)
return x_out
class ReductionBaseUnit(HybridBlock):
"""
NASNet Reduction base unit.
Parameters:
----------
in_channels : int
Number of input channels.
prev_in_channels : int
Number of input channels in previous input.
out_channels : int
Number of output channels.
extra_padding : bool, default True
Whether to use extra padding.
"""
def __init__(self,
in_channels,
prev_in_channels,
out_channels,
extra_padding=True,
**kwargs):
super(ReductionBaseUnit, self).__init__(**kwargs)
self.skip_input = True
mid_channels = out_channels // 4
with self.name_scope():
self.conv1x1_prev = nas_conv1x1(
in_channels=prev_in_channels,
out_channels=mid_channels)
self.conv1x1 = nas_conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.comb0_left = dws_branch_k5_s2_p2(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb0_right = dws_branch_k7_s2_p3(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb1_left = NasMaxPoolBlock(extra_padding=extra_padding)
self.comb1_right = dws_branch_k7_s2_p3(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb2_left = NasAvgPoolBlock(extra_padding=extra_padding)
self.comb2_right = dws_branch_k5_s2_p2(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb3_right = nasnet_avgpool3x3_s1()
self.comb4_left = dws_branch_k3_s1_p1(
in_channels=mid_channels,
out_channels=mid_channels,
extra_padding=extra_padding)
self.comb4_right = NasMaxPoolBlock(extra_padding=extra_padding)
def hybrid_forward(self, F, x, x_prev):
x_left = self.conv1x1(x)
x_right = self.conv1x1_prev(x_prev)
x0 = self.comb0_left(x_left) + self.comb0_right(x_right)
x1 = self.comb1_left(x_left) + self.comb1_right(x_right)
x2 = self.comb2_left(x_left) + self.comb2_right(x_right)
x3 = x1 + self.comb3_right(x0)
x4 = self.comb4_left(x0) + self.comb4_right(x_left)
x_out = F.concat(x1, x2, x3, x4, dim=1)
return x_out
class Reduction1Unit(ReductionBaseUnit):
"""
NASNet Reduction1 unit.
Parameters:
----------
in_channels : int
Number of input channels.
prev_in_channels : int
Number of input channels in previous input.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
prev_in_channels,
out_channels):
super(Reduction1Unit, self).__init__(
in_channels=in_channels,
prev_in_channels=prev_in_channels,
out_channels=out_channels,
extra_padding=True)
class Reduction2Unit(ReductionBaseUnit):
"""
NASNet Reduction2 unit.
Parameters:
----------
in_channels : int
Number of input channels.
prev_in_channels : int
Number of input channels in previous input.
out_channels : int
Number of output channels.
extra_padding : bool
Whether to use extra padding.
"""
def __init__(self,
in_channels,
prev_in_channels,
out_channels,
extra_padding):
super(Reduction2Unit, self).__init__(
in_channels=in_channels,
prev_in_channels=prev_in_channels,
out_channels=out_channels,
extra_padding=extra_padding)
class NASNetInitBlock(HybridBlock):
"""
NASNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels,
**kwargs):
super(NASNetInitBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv = nn.Conv2D(
channels=out_channels,
kernel_size=3,
strides=2,
padding=0,
use_bias=False,
in_channels=in_channels)
self.bn = nasnet_batch_norm(channels=out_channels)
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.bn(x)
return x
class NASNet(HybridBlock):
"""
NASNet-A model from 'Learning Transferable Architectures for Scalable Image Recognition,'
https://arxiv.org/abs/1707.07012.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
stem_blocks_channels : list of 2 int
Number of output channels for the Stem units.
final_pool_size : int
Size of the pooling windows for final pool.
extra_padding : bool
Whether to use extra padding.
skip_reduction_layer_input : bool
Whether to skip the reduction layers when calculating the previous layer to connect to.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
stem_blocks_channels,
final_pool_size,
extra_padding,
skip_reduction_layer_input,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(NASNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
reduction_units = [Reduction1Unit, Reduction2Unit]
with self.name_scope():
self.features = nasnet_dual_path_sequential(
return_two=False,
first_ordinals=1,
last_ordinals=2,
prefix="")
self.features.add(NASNetInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
out_channels = stem_blocks_channels[0]
self.features.add(Stem1Unit(
in_channels=in_channels,
out_channels=out_channels))
prev_in_channels = in_channels
in_channels = out_channels
out_channels = stem_blocks_channels[1]
self.features.add(Stem2Unit(
in_channels=in_channels,
prev_in_channels=prev_in_channels,
out_channels=out_channels,
extra_padding=extra_padding))
prev_in_channels = in_channels
in_channels = out_channels
for i, channels_per_stage in enumerate(channels):
stage = nasnet_dual_path_sequential(
can_skip_input=skip_reduction_layer_input,
prefix='stage{}_'.format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
if (j == 0) and (i != 0):
unit = reduction_units[i - 1]
elif ((i == 0) and (j == 0)) or ((i != 0) and (j == 1)):
unit = FirstUnit
else:
unit = NormalUnit
if unit == Reduction2Unit:
stage.add(Reduction2Unit(
in_channels=in_channels,
prev_in_channels=prev_in_channels,
out_channels=out_channels,
extra_padding=extra_padding))
else:
stage.add(unit(
in_channels=in_channels,
prev_in_channels=prev_in_channels,
out_channels=out_channels))
prev_in_channels = in_channels
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.Activation("relu"))
self.features.add(nn.AvgPool2D(
pool_size=final_pool_size,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dropout(rate=0.5))
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_nasnet(repeat,
penultimate_filters,
init_block_channels,
final_pool_size,
extra_padding,
skip_reduction_layer_input,
in_size,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create NASNet-A model with specific parameters.
Parameters:
----------
repeat : int
NNumber of cell repeats.
penultimate_filters : int
Number of filters in the penultimate layer of the network.
init_block_channels : int
Number of output channels for the initial unit.
final_pool_size : int
Size of the pooling windows for final pool.
extra_padding : bool
Whether to use extra padding.
skip_reduction_layer_input : bool
Whether to skip the reduction layers when calculating the previous layer to connect to.
in_size : tuple of two ints
Spatial size of the expected input image.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
stem_blocks_channels = [1, 2]
reduct_channels = [[], [8], [16]]
norm_channels = [6, 12, 24]
channels = [rci + [nci] * repeat for rci, nci in zip(reduct_channels, norm_channels)]
base_channel_chunk = penultimate_filters // channels[-1][-1]
stem_blocks_channels = [(ci * base_channel_chunk) for ci in stem_blocks_channels]
channels = [[(cij * base_channel_chunk) for cij in ci] for ci in channels]
net = NASNet(
channels=channels,
init_block_channels=init_block_channels,
stem_blocks_channels=stem_blocks_channels,
final_pool_size=final_pool_size,
extra_padding=extra_padding,
skip_reduction_layer_input=skip_reduction_layer_input,
in_size=in_size,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def nasnet_4a1056(**kwargs):
"""
NASNet-A 4@1056 (NASNet-A-Mobile) model from 'Learning Transferable Architectures for Scalable Image Recognition,'
https://arxiv.org/abs/1707.07012.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_nasnet(
repeat=4,
penultimate_filters=1056,
init_block_channels=32,
final_pool_size=7,
extra_padding=True,
skip_reduction_layer_input=False,
in_size=(224, 224),
model_name="nasnet_4a1056",
**kwargs)
def nasnet_6a4032(**kwargs):
"""
NASNet-A 6@4032 (NASNet-A-Large) model from 'Learning Transferable Architectures for Scalable Image Recognition,'
https://arxiv.org/abs/1707.07012.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_nasnet(
repeat=6,
penultimate_filters=4032,
init_block_channels=96,
final_pool_size=11,
extra_padding=False,
skip_reduction_layer_input=True,
in_size=(331, 331),
model_name="nasnet_6a4032",
**kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
nasnet_4a1056,
nasnet_6a4032,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != nasnet_4a1056 or weight_count == 5289978)
assert (model != nasnet_6a4032 or weight_count == 88753150)
x = mx.nd.zeros((1, 3, net.in_size[0], net.in_size[1]), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 41,341 | 29.443299 | 118 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/resnext_cifar.py | """
ResNeXt for CIFAR/SVHN, implemented in Gluon.
Original paper: 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431.
"""
__all__ = ['CIFARResNeXt', 'resnext20_1x64d_cifar10', 'resnext20_1x64d_cifar100', 'resnext20_1x64d_svhn',
'resnext20_2x32d_cifar10', 'resnext20_2x32d_cifar100', 'resnext20_2x32d_svhn',
'resnext20_2x64d_cifar10', 'resnext20_2x64d_cifar100', 'resnext20_2x64d_svhn',
'resnext20_4x16d_cifar10', 'resnext20_4x16d_cifar100', 'resnext20_4x16d_svhn',
'resnext20_4x32d_cifar10', 'resnext20_4x32d_cifar100', 'resnext20_4x32d_svhn',
'resnext20_8x8d_cifar10', 'resnext20_8x8d_cifar100', 'resnext20_8x8d_svhn',
'resnext20_8x16d_cifar10', 'resnext20_8x16d_cifar100', 'resnext20_8x16d_svhn',
'resnext20_16x4d_cifar10', 'resnext20_16x4d_cifar100', 'resnext20_16x4d_svhn',
'resnext20_16x8d_cifar10', 'resnext20_16x8d_cifar100', 'resnext20_16x8d_svhn',
'resnext20_32x2d_cifar10', 'resnext20_32x2d_cifar100', 'resnext20_32x2d_svhn',
'resnext20_32x4d_cifar10', 'resnext20_32x4d_cifar100', 'resnext20_32x4d_svhn',
'resnext20_64x1d_cifar10', 'resnext20_64x1d_cifar100', 'resnext20_64x1d_svhn',
'resnext20_64x2d_cifar10', 'resnext20_64x2d_cifar100', 'resnext20_64x2d_svhn',
'resnext29_32x4d_cifar10', 'resnext29_32x4d_cifar100', 'resnext29_32x4d_svhn',
'resnext29_16x64d_cifar10', 'resnext29_16x64d_cifar100', 'resnext29_16x64d_svhn',
'resnext56_1x64d_cifar10', 'resnext56_1x64d_cifar100', 'resnext56_1x64d_svhn',
'resnext56_2x32d_cifar10', 'resnext56_2x32d_cifar100', 'resnext56_2x32d_svhn',
'resnext56_4x16d_cifar10', 'resnext56_4x16d_cifar100', 'resnext56_4x16d_svhn',
'resnext56_8x8d_cifar10', 'resnext56_8x8d_cifar100', 'resnext56_8x8d_svhn',
'resnext56_16x4d_cifar10', 'resnext56_16x4d_cifar100', 'resnext56_16x4d_svhn',
'resnext56_32x2d_cifar10', 'resnext56_32x2d_cifar100', 'resnext56_32x2d_svhn',
'resnext56_64x1d_cifar10', 'resnext56_64x1d_cifar100', 'resnext56_64x1d_svhn',
'resnext272_1x64d_cifar10', 'resnext272_1x64d_cifar100', 'resnext272_1x64d_svhn',
'resnext272_2x32d_cifar10', 'resnext272_2x32d_cifar100', 'resnext272_2x32d_svhn']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv3x3_block
from .resnext import ResNeXtUnit
class CIFARResNeXt(HybridBlock):
"""
ResNeXt model for CIFAR from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
cardinality,
bottleneck_width,
bn_use_global_stats=False,
in_channels=3,
in_size=(32, 32),
classes=10,
**kwargs):
super(CIFARResNeXt, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
stage.add(ResNeXtUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=8,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_resnext_cifar(classes,
blocks,
cardinality,
bottleneck_width,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
ResNeXt model for CIFAR with specific parameters.
Parameters:
----------
classes : int
Number of classification classes.
blocks : int
Number of blocks.
cardinality: int
Number of groups.
bottleneck_width: int
Width of bottleneck block.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
assert (blocks - 2) % 9 == 0
layers = [(blocks - 2) // 9] * 3
channels_per_layers = [256, 512, 1024]
init_block_channels = 64
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = CIFARResNeXt(
channels=channels,
init_block_channels=init_block_channels,
cardinality=cardinality,
bottleneck_width=bottleneck_width,
classes=classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def resnext20_1x64d_cifar10(classes=10, **kwargs):
"""
ResNeXt-20 (1x64d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=1, bottleneck_width=64,
model_name="resnext20_1x64d_cifar10", **kwargs)
def resnext20_1x64d_cifar100(classes=100, **kwargs):
"""
ResNeXt-20 (1x64d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=1, bottleneck_width=64,
model_name="resnext20_1x64d_cifar100", **kwargs)
def resnext20_1x64d_svhn(classes=10, **kwargs):
"""
ResNeXt-20 (1x64d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=1, bottleneck_width=64,
model_name="resnext20_1x64d_svhn", **kwargs)
def resnext20_2x32d_cifar10(classes=10, **kwargs):
"""
ResNeXt-20 (2x32d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=2, bottleneck_width=32,
model_name="resnext20_2x32d_cifar10", **kwargs)
def resnext20_2x32d_cifar100(classes=100, **kwargs):
"""
ResNeXt-20 (2x32d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=2, bottleneck_width=32,
model_name="resnext20_2x32d_cifar100", **kwargs)
def resnext20_2x32d_svhn(classes=10, **kwargs):
"""
ResNeXt-20 (2x32d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=2, bottleneck_width=32,
model_name="resnext20_2x32d_svhn", **kwargs)
def resnext20_2x64d_cifar10(classes=10, **kwargs):
"""
ResNeXt-20 (2x64d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=2, bottleneck_width=64,
model_name="resnext20_2x64d_cifar10", **kwargs)
def resnext20_2x64d_cifar100(classes=100, **kwargs):
"""
ResNeXt-20 (2x64d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=2, bottleneck_width=64,
model_name="resnext20_2x64d_cifar100", **kwargs)
def resnext20_2x64d_svhn(classes=10, **kwargs):
"""
ResNeXt-20 (2x64d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=2, bottleneck_width=64,
model_name="resnext20_2x64d_svhn", **kwargs)
def resnext20_4x16d_cifar10(classes=10, **kwargs):
"""
ResNeXt-20 (4x16d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=4, bottleneck_width=16,
model_name="resnext20_4x16d_cifar10", **kwargs)
def resnext20_4x16d_cifar100(classes=100, **kwargs):
"""
ResNeXt-20 (4x16d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=4, bottleneck_width=16,
model_name="resnext20_4x16d_cifar100", **kwargs)
def resnext20_4x16d_svhn(classes=10, **kwargs):
"""
ResNeXt-20 (4x16d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=4, bottleneck_width=16,
model_name="resnext20_4x16d_svhn", **kwargs)
def resnext20_4x32d_cifar10(classes=10, **kwargs):
"""
ResNeXt-20 (4x32d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=4, bottleneck_width=32,
model_name="resnext20_4x32d_cifar10", **kwargs)
def resnext20_4x32d_cifar100(classes=100, **kwargs):
"""
ResNeXt-20 (4x32d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=4, bottleneck_width=32,
model_name="resnext20_4x32d_cifar100", **kwargs)
def resnext20_4x32d_svhn(classes=10, **kwargs):
"""
ResNeXt-20 (4x32d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=4, bottleneck_width=32,
model_name="resnext20_4x32d_svhn", **kwargs)
def resnext20_8x8d_cifar10(classes=10, **kwargs):
"""
ResNeXt-20 (8x8d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=8, bottleneck_width=8,
model_name="resnext20_8x8d_cifar10", **kwargs)
def resnext20_8x8d_cifar100(classes=100, **kwargs):
"""
ResNeXt-20 (8x8d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=8, bottleneck_width=8,
model_name="resnext20_8x8d_cifar100", **kwargs)
def resnext20_8x8d_svhn(classes=10, **kwargs):
"""
ResNeXt-20 (8x8d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=8, bottleneck_width=8,
model_name="resnext20_8x8d_svhn", **kwargs)
def resnext20_8x16d_cifar10(classes=10, **kwargs):
"""
ResNeXt-20 (8x16d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=8, bottleneck_width=16,
model_name="resnext20_8x16d_cifar10", **kwargs)
def resnext20_8x16d_cifar100(classes=100, **kwargs):
"""
ResNeXt-20 (8x16d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=8, bottleneck_width=16,
model_name="resnext20_8x16d_cifar100", **kwargs)
def resnext20_8x16d_svhn(classes=10, **kwargs):
"""
ResNeXt-20 (8x16d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=8, bottleneck_width=16,
model_name="resnext20_8x16d_svhn", **kwargs)
def resnext20_16x4d_cifar10(classes=10, **kwargs):
"""
ResNeXt-20 (16x4d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=16, bottleneck_width=4,
model_name="resnext20_16x4d_cifar10", **kwargs)
def resnext20_16x4d_cifar100(classes=100, **kwargs):
"""
ResNeXt-20 (16x4d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=16, bottleneck_width=4,
model_name="resnext20_16x4d_cifar100", **kwargs)
def resnext20_16x4d_svhn(classes=10, **kwargs):
"""
ResNeXt-20 (16x4d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=16, bottleneck_width=4,
model_name="resnext20_16x4d_svhn", **kwargs)
def resnext20_16x8d_cifar10(classes=10, **kwargs):
"""
ResNeXt-20 (16x8d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=16, bottleneck_width=8,
model_name="resnext20_16x8d_cifar10", **kwargs)
def resnext20_16x8d_cifar100(classes=100, **kwargs):
"""
ResNeXt-20 (16x8d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=16, bottleneck_width=8,
model_name="resnext20_16x8d_cifar100", **kwargs)
def resnext20_16x8d_svhn(classes=10, **kwargs):
"""
ResNeXt-20 (16x8d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=16, bottleneck_width=8,
model_name="resnext20_16x8d_svhn", **kwargs)
def resnext20_32x2d_cifar10(classes=10, **kwargs):
"""
ResNeXt-20 (32x2d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=32, bottleneck_width=2,
model_name="resnext20_32x2d_cifar10", **kwargs)
def resnext20_32x2d_cifar100(classes=100, **kwargs):
"""
ResNeXt-20 (32x2d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=32, bottleneck_width=2,
model_name="resnext20_32x2d_cifar100", **kwargs)
def resnext20_32x2d_svhn(classes=10, **kwargs):
"""
ResNeXt-20 (32x2d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=32, bottleneck_width=2,
model_name="resnext20_32x2d_svhn", **kwargs)
def resnext20_32x4d_cifar10(classes=10, **kwargs):
"""
ResNeXt-20 (32x4d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=32, bottleneck_width=4,
model_name="resnext20_32x4d_cifar10", **kwargs)
def resnext20_32x4d_cifar100(classes=100, **kwargs):
"""
ResNeXt-20 (32x4d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=32, bottleneck_width=4,
model_name="resnext20_32x4d_cifar100", **kwargs)
def resnext20_32x4d_svhn(classes=10, **kwargs):
"""
ResNeXt-20 (32x4d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=32, bottleneck_width=4,
model_name="resnext20_32x4d_svhn", **kwargs)
def resnext20_64x1d_cifar10(classes=10, **kwargs):
"""
ResNeXt-20 (64x1d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=64, bottleneck_width=1,
model_name="resnext20_64x1d_cifar10", **kwargs)
def resnext20_64x1d_cifar100(classes=100, **kwargs):
"""
ResNeXt-20 (64x1d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=64, bottleneck_width=1,
model_name="resnext20_64x1d_cifar100", **kwargs)
def resnext20_64x1d_svhn(classes=10, **kwargs):
"""
ResNeXt-20 (64x1d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=64, bottleneck_width=1,
model_name="resnext20_64x1d_svhn", **kwargs)
def resnext20_64x2d_cifar10(classes=10, **kwargs):
"""
ResNeXt-20 (64x2d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=64, bottleneck_width=2,
model_name="resnext20_64x2d_cifar10", **kwargs)
def resnext20_64x2d_cifar100(classes=100, **kwargs):
"""
ResNeXt-20 (64x2d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=64, bottleneck_width=2,
model_name="resnext20_64x2d_cifar100", **kwargs)
def resnext20_64x2d_svhn(classes=10, **kwargs):
"""
ResNeXt-20 (64x1d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=20, cardinality=64, bottleneck_width=2,
model_name="resnext20_64x2d_svhn", **kwargs)
def resnext29_32x4d_cifar10(classes=10, **kwargs):
"""
ResNeXt-29 (32x4d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=29, cardinality=32, bottleneck_width=4,
model_name="resnext29_32x4d_cifar10", **kwargs)
def resnext29_32x4d_cifar100(classes=100, **kwargs):
"""
ResNeXt-29 (32x4d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=29, cardinality=32, bottleneck_width=4,
model_name="resnext29_32x4d_cifar100", **kwargs)
def resnext29_32x4d_svhn(classes=10, **kwargs):
"""
ResNeXt-29 (32x4d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=29, cardinality=32, bottleneck_width=4,
model_name="resnext29_32x4d_svhn", **kwargs)
def resnext29_16x64d_cifar10(classes=10, **kwargs):
"""
ResNeXt-29 (16x64d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=29, cardinality=16, bottleneck_width=64,
model_name="resnext29_16x64d_cifar10", **kwargs)
def resnext29_16x64d_cifar100(classes=100, **kwargs):
"""
ResNeXt-29 (16x64d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=29, cardinality=16, bottleneck_width=64,
model_name="resnext29_16x64d_cifar100", **kwargs)
def resnext29_16x64d_svhn(classes=10, **kwargs):
"""
ResNeXt-29 (16x64d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=29, cardinality=16, bottleneck_width=64,
model_name="resnext29_16x64d_svhn", **kwargs)
def resnext56_1x64d_cifar10(classes=10, **kwargs):
"""
ResNeXt-56 (1x64d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=1, bottleneck_width=64,
model_name="resnext56_1x64d_cifar10", **kwargs)
def resnext56_1x64d_cifar100(classes=100, **kwargs):
"""
ResNeXt-56 (1x64d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=1, bottleneck_width=64,
model_name="resnext56_1x64d_cifar100", **kwargs)
def resnext56_1x64d_svhn(classes=10, **kwargs):
"""
ResNeXt-56 (1x64d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=1, bottleneck_width=64,
model_name="resnext56_1x64d_svhn", **kwargs)
def resnext56_2x32d_cifar10(classes=10, **kwargs):
"""
ResNeXt-56 (2x32d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=2, bottleneck_width=32,
model_name="resnext56_2x32d_cifar10", **kwargs)
def resnext56_2x32d_cifar100(classes=100, **kwargs):
"""
ResNeXt-56 (2x32d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=2, bottleneck_width=32,
model_name="resnext56_2x32d_cifar100", **kwargs)
def resnext56_2x32d_svhn(classes=10, **kwargs):
"""
ResNeXt-56 (2x32d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=2, bottleneck_width=32,
model_name="resnext56_2x32d_svhn", **kwargs)
def resnext56_4x16d_cifar10(classes=10, **kwargs):
"""
ResNeXt-56 (4x16d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=4, bottleneck_width=16,
model_name="resnext56_4x16d_cifar10", **kwargs)
def resnext56_4x16d_cifar100(classes=100, **kwargs):
"""
ResNeXt-56 (4x16d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=4, bottleneck_width=16,
model_name="resnext56_4x16d_cifar100", **kwargs)
def resnext56_4x16d_svhn(classes=10, **kwargs):
"""
ResNeXt-56 (4x16d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=4, bottleneck_width=16,
model_name="resnext56_4x16d_svhn", **kwargs)
def resnext56_8x8d_cifar10(classes=10, **kwargs):
"""
ResNeXt-56 (8x8d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=8, bottleneck_width=8,
model_name="resnext56_8x8d_cifar10", **kwargs)
def resnext56_8x8d_cifar100(classes=100, **kwargs):
"""
ResNeXt-56 (8x8d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=8, bottleneck_width=8,
model_name="resnext56_8x8d_cifar100", **kwargs)
def resnext56_8x8d_svhn(classes=10, **kwargs):
"""
ResNeXt-56 (8x8d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=8, bottleneck_width=8,
model_name="resnext56_8x8d_svhn", **kwargs)
def resnext56_16x4d_cifar10(classes=10, **kwargs):
"""
ResNeXt-56 (16x4d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=16, bottleneck_width=4,
model_name="resnext56_16x4d_cifar10", **kwargs)
def resnext56_16x4d_cifar100(classes=100, **kwargs):
"""
ResNeXt-56 (16x4d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=16, bottleneck_width=4,
model_name="resnext56_16x4d_cifar100", **kwargs)
def resnext56_16x4d_svhn(classes=10, **kwargs):
"""
ResNeXt-56 (16x4d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=16, bottleneck_width=4,
model_name="resnext56_16x4d_svhn", **kwargs)
def resnext56_32x2d_cifar10(classes=10, **kwargs):
"""
ResNeXt-56 (32x2d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=32, bottleneck_width=2,
model_name="resnext56_32x2d_cifar10", **kwargs)
def resnext56_32x2d_cifar100(classes=100, **kwargs):
"""
ResNeXt-56 (32x2d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=32, bottleneck_width=2,
model_name="resnext56_32x2d_cifar100", **kwargs)
def resnext56_32x2d_svhn(classes=10, **kwargs):
"""
ResNeXt-56 (32x2d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=32, bottleneck_width=2,
model_name="resnext56_32x2d_svhn", **kwargs)
def resnext56_64x1d_cifar10(classes=10, **kwargs):
"""
ResNeXt-56 (64x1d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=64, bottleneck_width=1,
model_name="resnext56_64x1d_cifar10", **kwargs)
def resnext56_64x1d_cifar100(classes=100, **kwargs):
"""
ResNeXt-56 (64x1d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=64, bottleneck_width=1,
model_name="resnext56_64x1d_cifar100", **kwargs)
def resnext56_64x1d_svhn(classes=10, **kwargs):
"""
ResNeXt-56 (64x1d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=56, cardinality=64, bottleneck_width=1,
model_name="resnext56_64x1d_svhn", **kwargs)
def resnext272_1x64d_cifar10(classes=10, **kwargs):
"""
ResNeXt-272 (1x64d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=272, cardinality=1, bottleneck_width=64,
model_name="resnext272_1x64d_cifar10", **kwargs)
def resnext272_1x64d_cifar100(classes=100, **kwargs):
"""
ResNeXt-272 (1x64d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=272, cardinality=1, bottleneck_width=64,
model_name="resnext272_1x64d_cifar100", **kwargs)
def resnext272_1x64d_svhn(classes=10, **kwargs):
"""
ResNeXt-272 (1x64d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=272, cardinality=1, bottleneck_width=64,
model_name="resnext272_1x64d_svhn", **kwargs)
def resnext272_2x32d_cifar10(classes=10, **kwargs):
"""
ResNeXt-272 (2x32d) model for CIFAR-10 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=272, cardinality=2, bottleneck_width=32,
model_name="resnext272_2x32d_cifar10", **kwargs)
def resnext272_2x32d_cifar100(classes=100, **kwargs):
"""
ResNeXt-272 (2x32d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=272, cardinality=2, bottleneck_width=32,
model_name="resnext272_2x32d_cifar100", **kwargs)
def resnext272_2x32d_svhn(classes=10, **kwargs):
"""
ResNeXt-272 (2x32d) model for SVHN from 'Aggregated Residual Transformations for Deep Neural Networks,'
http://arxiv.org/abs/1611.05431.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_resnext_cifar(classes=classes, blocks=272, cardinality=2, bottleneck_width=32,
model_name="resnext272_2x32d_svhn", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
(resnext20_1x64d_cifar10, 10),
(resnext20_1x64d_cifar100, 100),
(resnext20_1x64d_svhn, 10),
(resnext20_2x32d_cifar10, 10),
(resnext20_2x32d_cifar100, 100),
(resnext20_2x32d_svhn, 10),
(resnext20_2x64d_cifar10, 10),
(resnext20_2x64d_cifar100, 100),
(resnext20_2x64d_svhn, 10),
(resnext20_4x16d_cifar10, 10),
(resnext20_4x16d_cifar100, 100),
(resnext20_4x16d_svhn, 10),
(resnext20_4x32d_cifar10, 10),
(resnext20_4x32d_cifar100, 100),
(resnext20_4x32d_svhn, 10),
(resnext20_8x8d_cifar10, 10),
(resnext20_8x8d_cifar100, 100),
(resnext20_8x8d_svhn, 10),
(resnext20_8x16d_cifar10, 10),
(resnext20_8x16d_cifar100, 100),
(resnext20_8x16d_svhn, 10),
(resnext20_16x4d_cifar10, 10),
(resnext20_16x4d_cifar100, 100),
(resnext20_16x4d_svhn, 10),
(resnext20_16x8d_cifar10, 10),
(resnext20_16x8d_cifar100, 100),
(resnext20_16x8d_svhn, 10),
(resnext20_32x2d_cifar10, 10),
(resnext20_32x2d_cifar100, 100),
(resnext20_32x2d_svhn, 10),
(resnext20_32x4d_cifar10, 10),
(resnext20_32x4d_cifar100, 100),
(resnext20_32x4d_svhn, 10),
(resnext20_64x1d_cifar10, 10),
(resnext20_64x1d_cifar100, 100),
(resnext20_64x1d_svhn, 10),
(resnext20_64x2d_cifar10, 10),
(resnext20_64x2d_cifar100, 100),
(resnext20_64x2d_svhn, 10),
(resnext29_32x4d_cifar10, 10),
(resnext29_32x4d_cifar100, 100),
(resnext29_32x4d_svhn, 10),
(resnext29_16x64d_cifar10, 10),
(resnext29_16x64d_cifar100, 100),
(resnext29_16x64d_svhn, 10),
(resnext56_1x64d_cifar10, 10),
(resnext56_1x64d_cifar100, 100),
(resnext56_1x64d_svhn, 10),
(resnext56_2x32d_cifar10, 10),
(resnext56_2x32d_cifar100, 100),
(resnext56_2x32d_svhn, 10),
(resnext56_4x16d_cifar10, 10),
(resnext56_4x16d_cifar100, 100),
(resnext56_4x16d_svhn, 10),
(resnext56_8x8d_cifar10, 10),
(resnext56_8x8d_cifar100, 100),
(resnext56_8x8d_svhn, 10),
(resnext56_16x4d_cifar10, 10),
(resnext56_16x4d_cifar100, 100),
(resnext56_16x4d_svhn, 10),
(resnext56_32x2d_cifar10, 10),
(resnext56_32x2d_cifar100, 100),
(resnext56_32x2d_svhn, 10),
(resnext56_64x1d_cifar10, 10),
(resnext56_64x1d_cifar100, 100),
(resnext56_64x1d_svhn, 10),
(resnext272_1x64d_cifar10, 10),
(resnext272_1x64d_cifar100, 100),
(resnext272_1x64d_svhn, 10),
(resnext272_2x32d_cifar10, 10),
(resnext272_2x32d_cifar100, 100),
(resnext272_2x32d_svhn, 10),
]
for model, classes in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != resnext20_1x64d_cifar10 or weight_count == 3446602)
assert (model != resnext20_1x64d_cifar100 or weight_count == 3538852)
assert (model != resnext20_1x64d_svhn or weight_count == 3446602)
assert (model != resnext20_2x32d_cifar10 or weight_count == 2672458)
assert (model != resnext20_2x32d_cifar100 or weight_count == 2764708)
assert (model != resnext20_2x32d_svhn or weight_count == 2672458)
assert (model != resnext20_2x64d_cifar10 or weight_count == 6198602)
assert (model != resnext20_2x64d_cifar100 or weight_count == 6290852)
assert (model != resnext20_2x64d_svhn or weight_count == 6198602)
assert (model != resnext20_4x16d_cifar10 or weight_count == 2285386)
assert (model != resnext20_4x16d_cifar100 or weight_count == 2377636)
assert (model != resnext20_4x16d_svhn or weight_count == 2285386)
assert (model != resnext20_4x32d_cifar10 or weight_count == 4650314)
assert (model != resnext20_4x32d_cifar100 or weight_count == 4742564)
assert (model != resnext20_4x32d_svhn or weight_count == 4650314)
assert (model != resnext20_8x8d_cifar10 or weight_count == 2091850)
assert (model != resnext20_8x8d_cifar100 or weight_count == 2184100)
assert (model != resnext20_8x8d_svhn or weight_count == 2091850)
assert (model != resnext20_8x16d_cifar10 or weight_count == 3876170)
assert (model != resnext20_8x16d_cifar100 or weight_count == 3968420)
assert (model != resnext20_8x16d_svhn or weight_count == 3876170)
assert (model != resnext20_16x4d_cifar10 or weight_count == 1995082)
assert (model != resnext20_16x4d_cifar100 or weight_count == 2087332)
assert (model != resnext20_16x4d_svhn or weight_count == 1995082)
assert (model != resnext20_16x8d_cifar10 or weight_count == 3489098)
assert (model != resnext20_16x8d_cifar100 or weight_count == 3581348)
assert (model != resnext20_16x8d_svhn or weight_count == 3489098)
assert (model != resnext20_32x2d_cifar10 or weight_count == 1946698)
assert (model != resnext20_32x2d_cifar100 or weight_count == 2038948)
assert (model != resnext20_32x2d_svhn or weight_count == 1946698)
assert (model != resnext20_32x4d_cifar10 or weight_count == 3295562)
assert (model != resnext20_32x4d_cifar100 or weight_count == 3387812)
assert (model != resnext20_32x4d_svhn or weight_count == 3295562)
assert (model != resnext20_64x1d_cifar10 or weight_count == 1922506)
assert (model != resnext20_64x1d_cifar100 or weight_count == 2014756)
assert (model != resnext20_64x1d_svhn or weight_count == 1922506)
assert (model != resnext20_64x2d_cifar10 or weight_count == 3198794)
assert (model != resnext20_64x2d_cifar100 or weight_count == 3291044)
assert (model != resnext20_64x2d_svhn or weight_count == 3198794)
assert (model != resnext29_32x4d_cifar10 or weight_count == 4775754)
assert (model != resnext29_32x4d_cifar100 or weight_count == 4868004)
assert (model != resnext29_32x4d_svhn or weight_count == 4775754)
assert (model != resnext29_16x64d_cifar10 or weight_count == 68155210)
assert (model != resnext29_16x64d_cifar100 or weight_count == 68247460)
assert (model != resnext29_16x64d_svhn or weight_count == 68155210)
assert (model != resnext56_1x64d_cifar10 or weight_count == 9317194)
assert (model != resnext56_1x64d_cifar100 or weight_count == 9409444)
assert (model != resnext56_1x64d_svhn or weight_count == 9317194)
assert (model != resnext56_2x32d_cifar10 or weight_count == 6994762)
assert (model != resnext56_2x32d_cifar100 or weight_count == 7087012)
assert (model != resnext56_2x32d_svhn or weight_count == 6994762)
assert (model != resnext56_4x16d_cifar10 or weight_count == 5833546)
assert (model != resnext56_4x16d_cifar100 or weight_count == 5925796)
assert (model != resnext56_4x16d_svhn or weight_count == 5833546)
assert (model != resnext56_8x8d_cifar10 or weight_count == 5252938)
assert (model != resnext56_8x8d_cifar100 or weight_count == 5345188)
assert (model != resnext56_8x8d_svhn or weight_count == 5252938)
assert (model != resnext56_16x4d_cifar10 or weight_count == 4962634)
assert (model != resnext56_16x4d_cifar100 or weight_count == 5054884)
assert (model != resnext56_16x4d_svhn or weight_count == 4962634)
assert (model != resnext56_32x2d_cifar10 or weight_count == 4817482)
assert (model != resnext56_32x2d_cifar100 or weight_count == 4909732)
assert (model != resnext56_32x2d_svhn or weight_count == 4817482)
assert (model != resnext56_64x1d_cifar10 or weight_count == 4744906)
assert (model != resnext56_64x1d_cifar100 or weight_count == 4837156)
assert (model != resnext56_64x1d_svhn or weight_count == 4744906)
assert (model != resnext272_1x64d_cifar10 or weight_count == 44540746)
assert (model != resnext272_1x64d_cifar100 or weight_count == 44632996)
assert (model != resnext272_1x64d_svhn or weight_count == 44540746)
assert (model != resnext272_2x32d_cifar10 or weight_count == 32928586)
assert (model != resnext272_2x32d_cifar100 or weight_count == 33020836)
assert (model != resnext272_2x32d_svhn or weight_count == 32928586)
x = mx.nd.zeros((1, 3, 32, 32), ctx=ctx)
y = net(x)
assert (y.shape == (1, classes))
if __name__ == "__main__":
_test()
| 71,735 | 39.075978 | 116 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/densenet_cifar.py | """
DenseNet for CIFAR/SVHN, implemented in Gluon.
Original paper: 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993.
"""
__all__ = ['CIFARDenseNet', 'densenet40_k12_cifar10', 'densenet40_k12_cifar100', 'densenet40_k12_svhn',
'densenet40_k12_bc_cifar10', 'densenet40_k12_bc_cifar100', 'densenet40_k12_bc_svhn',
'densenet40_k24_bc_cifar10', 'densenet40_k24_bc_cifar100', 'densenet40_k24_bc_svhn',
'densenet40_k36_bc_cifar10', 'densenet40_k36_bc_cifar100', 'densenet40_k36_bc_svhn',
'densenet100_k12_cifar10', 'densenet100_k12_cifar100', 'densenet100_k12_svhn',
'densenet100_k24_cifar10', 'densenet100_k24_cifar100', 'densenet100_k24_svhn',
'densenet100_k12_bc_cifar10', 'densenet100_k12_bc_cifar100', 'densenet100_k12_bc_svhn',
'densenet190_k40_bc_cifar10', 'densenet190_k40_bc_cifar100', 'densenet190_k40_bc_svhn',
'densenet250_k24_bc_cifar10', 'densenet250_k24_bc_cifar100', 'densenet250_k24_bc_svhn']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv3x3, pre_conv3x3_block
from .preresnet import PreResActivation
from .densenet import DenseUnit, TransitionBlock
class DenseSimpleUnit(HybridBlock):
"""
DenseNet simple unit for CIFAR.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats,
dropout_rate,
**kwargs):
super(DenseSimpleUnit, self).__init__(**kwargs)
self.use_dropout = (dropout_rate != 0.0)
inc_channels = out_channels - in_channels
with self.name_scope():
self.conv = pre_conv3x3_block(
in_channels=in_channels,
out_channels=inc_channels,
bn_use_global_stats=bn_use_global_stats)
if self.use_dropout:
self.dropout = nn.Dropout(rate=dropout_rate)
def hybrid_forward(self, F, x):
identity = x
x = self.conv(x)
if self.use_dropout:
x = self.dropout(x)
x = F.concat(identity, x, dim=1)
return x
class CIFARDenseNet(HybridBlock):
"""
DenseNet model for CIFAR from 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
dropout_rate : float, default 0.0
Parameter of Dropout layer. Faction of the input units to drop.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
bn_use_global_stats=False,
dropout_rate=0.0,
in_channels=3,
in_size=(32, 32),
classes=10,
**kwargs):
super(CIFARDenseNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
unit_class = DenseUnit if bottleneck else DenseSimpleUnit
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(conv3x3(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
if i != 0:
stage.add(TransitionBlock(
in_channels=in_channels,
out_channels=(in_channels // 2),
bn_use_global_stats=bn_use_global_stats))
in_channels = in_channels // 2
for j, out_channels in enumerate(channels_per_stage):
stage.add(unit_class(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
dropout_rate=dropout_rate))
in_channels = out_channels
self.features.add(stage)
self.features.add(PreResActivation(
in_channels=in_channels,
bn_use_global_stats=bn_use_global_stats))
self.features.add(nn.AvgPool2D(
pool_size=8,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_densenet_cifar(classes,
blocks,
growth_rate,
bottleneck,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create DenseNet model for CIFAR with specific parameters.
Parameters:
----------
classes : int
Number of classification classes.
blocks : int
Number of blocks.
growth_rate : int
Growth rate.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
assert (classes in [10, 100])
if bottleneck:
assert ((blocks - 4) % 6 == 0)
layers = [(blocks - 4) // 6] * 3
else:
assert ((blocks - 4) % 3 == 0)
layers = [(blocks - 4) // 3] * 3
init_block_channels = 2 * growth_rate
from functools import reduce
channels = reduce(
lambda xi, yi: xi + [reduce(
lambda xj, yj: xj + [xj[-1] + yj],
[growth_rate] * yi,
[xi[-1][-1] // 2])[1:]],
layers,
[[init_block_channels * 2]])[1:]
net = CIFARDenseNet(
channels=channels,
init_block_channels=init_block_channels,
classes=classes,
bottleneck=bottleneck,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def densenet40_k12_cifar10(classes=10, **kwargs):
"""
DenseNet-40 (k=12) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=40, growth_rate=12, bottleneck=False,
model_name="densenet40_k12_cifar10", **kwargs)
def densenet40_k12_cifar100(classes=100, **kwargs):
"""
DenseNet-40 (k=12) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=40, growth_rate=12, bottleneck=False,
model_name="densenet40_k12_cifar100", **kwargs)
def densenet40_k12_svhn(classes=10, **kwargs):
"""
DenseNet-40 (k=12) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=40, growth_rate=12, bottleneck=False,
model_name="densenet40_k12_svhn", **kwargs)
def densenet40_k12_bc_cifar10(classes=10, **kwargs):
"""
DenseNet-BC-40 (k=12) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=40, growth_rate=12, bottleneck=True,
model_name="densenet40_k12_bc_cifar10", **kwargs)
def densenet40_k12_bc_cifar100(classes=100, **kwargs):
"""
DenseNet-BC-40 (k=12) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=40, growth_rate=12, bottleneck=True,
model_name="densenet40_k12_bc_cifar100", **kwargs)
def densenet40_k12_bc_svhn(classes=10, **kwargs):
"""
DenseNet-BC-40 (k=12) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=40, growth_rate=12, bottleneck=True,
model_name="densenet40_k12_bc_svhn", **kwargs)
def densenet40_k24_bc_cifar10(classes=10, **kwargs):
"""
DenseNet-BC-40 (k=24) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=40, growth_rate=24, bottleneck=True,
model_name="densenet40_k24_bc_cifar10", **kwargs)
def densenet40_k24_bc_cifar100(classes=100, **kwargs):
"""
DenseNet-BC-40 (k=24) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=40, growth_rate=24, bottleneck=True,
model_name="densenet40_k24_bc_cifar100", **kwargs)
def densenet40_k24_bc_svhn(classes=10, **kwargs):
"""
DenseNet-BC-40 (k=24) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=40, growth_rate=24, bottleneck=True,
model_name="densenet40_k24_bc_svhn", **kwargs)
def densenet40_k36_bc_cifar10(classes=10, **kwargs):
"""
DenseNet-BC-40 (k=36) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=40, growth_rate=36, bottleneck=True,
model_name="densenet40_k36_bc_cifar10", **kwargs)
def densenet40_k36_bc_cifar100(classes=100, **kwargs):
"""
DenseNet-BC-40 (k=36) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=40, growth_rate=36, bottleneck=True,
model_name="densenet40_k36_bc_cifar100", **kwargs)
def densenet40_k36_bc_svhn(classes=10, **kwargs):
"""
DenseNet-BC-40 (k=36) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=40, growth_rate=36, bottleneck=True,
model_name="densenet40_k36_bc_svhn", **kwargs)
def densenet100_k12_cifar10(classes=10, **kwargs):
"""
DenseNet-100 (k=12) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=100, growth_rate=12, bottleneck=False,
model_name="densenet100_k12_cifar10", **kwargs)
def densenet100_k12_cifar100(classes=100, **kwargs):
"""
DenseNet-100 (k=12) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=100, growth_rate=12, bottleneck=False,
model_name="densenet100_k12_cifar100", **kwargs)
def densenet100_k12_svhn(classes=10, **kwargs):
"""
DenseNet-100 (k=12) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=100, growth_rate=12, bottleneck=False,
model_name="densenet100_k12_svhn", **kwargs)
def densenet100_k24_cifar10(classes=10, **kwargs):
"""
DenseNet-100 (k=24) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=100, growth_rate=24, bottleneck=False,
model_name="densenet100_k24_cifar10", **kwargs)
def densenet100_k24_cifar100(classes=100, **kwargs):
"""
DenseNet-100 (k=24) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=100, growth_rate=24, bottleneck=False,
model_name="densenet100_k24_cifar100", **kwargs)
def densenet100_k24_svhn(classes=10, **kwargs):
"""
DenseNet-100 (k=24) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=100, growth_rate=24, bottleneck=False,
model_name="densenet100_k24_svhn", **kwargs)
def densenet100_k12_bc_cifar10(classes=10, **kwargs):
"""
DenseNet-BC-100 (k=12) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=100, growth_rate=12, bottleneck=True,
model_name="densenet100_k12_bc_cifar10", **kwargs)
def densenet100_k12_bc_cifar100(classes=100, **kwargs):
"""
DenseNet-BC-100 (k=12) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=100, growth_rate=12, bottleneck=True,
model_name="densenet100_k12_bc_cifar100", **kwargs)
def densenet100_k12_bc_svhn(classes=10, **kwargs):
"""
DenseNet-BC-100 (k=12) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=100, growth_rate=12, bottleneck=True,
model_name="densenet100_k12_bc_svhn", **kwargs)
def densenet190_k40_bc_cifar10(classes=10, **kwargs):
"""
DenseNet-BC-190 (k=40) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=190, growth_rate=40, bottleneck=True,
model_name="densenet190_k40_bc_cifar10", **kwargs)
def densenet190_k40_bc_cifar100(classes=100, **kwargs):
"""
DenseNet-BC-190 (k=40) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=190, growth_rate=40, bottleneck=True,
model_name="densenet190_k40_bc_cifar100", **kwargs)
def densenet190_k40_bc_svhn(classes=10, **kwargs):
"""
DenseNet-BC-190 (k=40) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=190, growth_rate=40, bottleneck=True,
model_name="densenet190_k40_bc_svhn", **kwargs)
def densenet250_k24_bc_cifar10(classes=10, **kwargs):
"""
DenseNet-BC-250 (k=24) model for CIFAR-10 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=250, growth_rate=24, bottleneck=True,
model_name="densenet250_k24_bc_cifar10", **kwargs)
def densenet250_k24_bc_cifar100(classes=100, **kwargs):
"""
DenseNet-BC-250 (k=24) model for CIFAR-100 from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=250, growth_rate=24, bottleneck=True,
model_name="densenet250_k24_bc_cifar100", **kwargs)
def densenet250_k24_bc_svhn(classes=10, **kwargs):
"""
DenseNet-BC-250 (k=24) model for SVHN from 'Densely Connected Convolutional Networks,'
https://arxiv.org/abs/1608.06993.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_densenet_cifar(classes=classes, blocks=250, growth_rate=24, bottleneck=True,
model_name="densenet250_k24_bc_svhn", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
(densenet40_k12_cifar10, 10),
(densenet40_k12_cifar100, 100),
(densenet40_k12_svhn, 10),
(densenet40_k12_bc_cifar10, 10),
(densenet40_k12_bc_cifar100, 100),
(densenet40_k12_bc_svhn, 10),
(densenet40_k24_bc_cifar10, 10),
(densenet40_k24_bc_cifar100, 100),
(densenet40_k24_bc_svhn, 10),
(densenet40_k36_bc_cifar10, 10),
(densenet40_k36_bc_cifar100, 100),
(densenet40_k36_bc_svhn, 10),
(densenet100_k12_cifar10, 10),
(densenet100_k12_cifar100, 100),
(densenet100_k12_svhn, 10),
(densenet100_k24_cifar10, 10),
(densenet100_k24_cifar100, 100),
(densenet100_k24_svhn, 10),
(densenet100_k12_bc_cifar10, 10),
(densenet100_k12_bc_cifar100, 100),
(densenet100_k12_bc_svhn, 10),
(densenet190_k40_bc_cifar10, 10),
(densenet190_k40_bc_cifar100, 100),
(densenet190_k40_bc_svhn, 10),
(densenet250_k24_bc_cifar10, 10),
(densenet250_k24_bc_cifar100, 100),
(densenet250_k24_bc_svhn, 10),
]
for model, classes in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != densenet40_k12_cifar10 or weight_count == 599050)
assert (model != densenet40_k12_cifar100 or weight_count == 622360)
assert (model != densenet40_k12_svhn or weight_count == 599050)
assert (model != densenet40_k12_bc_cifar10 or weight_count == 176122)
assert (model != densenet40_k12_bc_cifar100 or weight_count == 188092)
assert (model != densenet40_k12_bc_svhn or weight_count == 176122)
assert (model != densenet40_k24_bc_cifar10 or weight_count == 690346)
assert (model != densenet40_k24_bc_cifar100 or weight_count == 714196)
assert (model != densenet40_k24_bc_svhn or weight_count == 690346)
assert (model != densenet40_k36_bc_cifar10 or weight_count == 1542682)
assert (model != densenet40_k36_bc_cifar100 or weight_count == 1578412)
assert (model != densenet40_k36_bc_svhn or weight_count == 1542682)
assert (model != densenet100_k12_cifar10 or weight_count == 4068490)
assert (model != densenet100_k12_cifar100 or weight_count == 4129600)
assert (model != densenet100_k12_svhn or weight_count == 4068490)
assert (model != densenet100_k24_cifar10 or weight_count == 16114138)
assert (model != densenet100_k24_cifar100 or weight_count == 16236268)
assert (model != densenet100_k24_svhn or weight_count == 16114138)
assert (model != densenet100_k12_bc_cifar10 or weight_count == 769162)
assert (model != densenet100_k12_bc_cifar100 or weight_count == 800032)
assert (model != densenet100_k12_bc_svhn or weight_count == 769162)
assert (model != densenet190_k40_bc_cifar10 or weight_count == 25624430)
assert (model != densenet190_k40_bc_cifar100 or weight_count == 25821620)
assert (model != densenet190_k40_bc_svhn or weight_count == 25624430)
assert (model != densenet250_k24_bc_cifar10 or weight_count == 15324406)
assert (model != densenet250_k24_bc_cifar100 or weight_count == 15480556)
assert (model != densenet250_k24_bc_svhn or weight_count == 15324406)
x = mx.nd.zeros((1, 3, 32, 32), ctx=ctx)
y = net(x)
assert (y.shape == (1, classes))
if __name__ == "__main__":
_test()
| 32,370 | 37.354265 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/bninception.py | """
BN-Inception for ImageNet-1K, implemented in Gluon.
Original paper: 'Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift,'
https://arxiv.org/abs/1502.03167.
"""
__all__ = ['BNInception', 'bninception']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from mxnet.gluon.contrib.nn import HybridConcurrent
from .common import conv1x1_block, conv3x3_block, conv7x7_block
class Inception3x3Branch(HybridBlock):
"""
BN-Inception 3x3 branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of intermediate channels.
strides : int or tuple/list of 2 int, default 1
Strides of the second convolution.
use_bias : bool, default True
Whether the convolution layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layers.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels,
strides=1,
use_bias=True,
use_bn=True,
bn_use_global_stats=False,
**kwargs):
super(Inception3x3Branch, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
strides=strides,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class InceptionDouble3x3Branch(HybridBlock):
"""
BN-Inception double 3x3 branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of intermediate channels.
strides : int or tuple/list of 2 int, default 1
Strides of the second convolution.
use_bias : bool, default True
Whether the convolution layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layers.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels,
strides=1,
use_bias=True,
use_bn=True,
bn_use_global_stats=False,
**kwargs):
super(InceptionDouble3x3Branch, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats)
self.conv3 = conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
strides=strides,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class InceptionPoolBranch(HybridBlock):
"""
BN-Inception avg-pool branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
avg_pool : bool
Whether use average pooling or max pooling.
use_bias : bool
Whether the convolution layer uses a bias vector.
use_bn : bool
Whether to use BatchNorm layers.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
avg_pool,
use_bias,
use_bn,
bn_use_global_stats,
**kwargs):
super(InceptionPoolBranch, self).__init__(**kwargs)
with self.name_scope():
if avg_pool:
self.pool = nn.AvgPool2D(
pool_size=3,
strides=1,
padding=1,
ceil_mode=True,
count_include_pad=True)
else:
self.pool = nn.MaxPool2D(
pool_size=3,
strides=1,
padding=1,
ceil_mode=True)
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.pool(x)
x = self.conv(x)
return x
class StemBlock(HybridBlock):
"""
BN-Inception stem block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of intermediate channels.
use_bias : bool
Whether the convolution layer uses a bias vector.
use_bn : bool
Whether to use BatchNorm layers.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels,
use_bias,
use_bn,
bn_use_global_stats,
**kwargs):
super(StemBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv7x7_block(
in_channels=in_channels,
out_channels=mid_channels,
strides=2,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats)
self.pool1 = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=0,
ceil_mode=True)
self.conv2 = Inception3x3Branch(
in_channels=mid_channels,
out_channels=out_channels,
mid_channels=mid_channels,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats)
self.pool2 = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=0,
ceil_mode=True)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.pool1(x)
x = self.conv2(x)
x = self.pool2(x)
return x
class InceptionBlock(HybridBlock):
"""
BN-Inception unit.
Parameters:
----------
in_channels : int
Number of input channels.
mid1_channels_list : list of int
Number of pre-middle channels for branches.
mid2_channels_list : list of int
Number of middle channels for branches.
avg_pool : bool
Whether use average pooling or max pooling.
use_bias : bool
Whether the convolution layer uses a bias vector.
use_bn : bool
Whether to use BatchNorm layers.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
mid1_channels_list,
mid2_channels_list,
avg_pool,
use_bias,
use_bn,
bn_use_global_stats,
**kwargs):
super(InceptionBlock, self).__init__(**kwargs)
assert (len(mid1_channels_list) == 2)
assert (len(mid2_channels_list) == 4)
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(conv1x1_block(
in_channels=in_channels,
out_channels=mid2_channels_list[0],
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(Inception3x3Branch(
in_channels=in_channels,
out_channels=mid2_channels_list[1],
mid_channels=mid1_channels_list[0],
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(InceptionDouble3x3Branch(
in_channels=in_channels,
out_channels=mid2_channels_list[2],
mid_channels=mid1_channels_list[1],
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(InceptionPoolBranch(
in_channels=in_channels,
out_channels=mid2_channels_list[3],
avg_pool=avg_pool,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats))
def hybrid_forward(self, F, x):
x = self.branches(x)
return x
class ReductionBlock(HybridBlock):
"""
BN-Inception reduction block.
Parameters:
----------
in_channels : int
Number of input channels.
mid1_channels_list : list of int
Number of pre-middle channels for branches.
mid2_channels_list : list of int
Number of middle channels for branches.
use_bias : bool
Whether the convolution layer uses a bias vector.
use_bn : bool
Whether to use BatchNorm layers.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
mid1_channels_list,
mid2_channels_list,
use_bias,
use_bn,
bn_use_global_stats,
**kwargs):
super(ReductionBlock, self).__init__(**kwargs)
assert (len(mid1_channels_list) == 2)
assert (len(mid2_channels_list) == 4)
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(Inception3x3Branch(
in_channels=in_channels,
out_channels=mid2_channels_list[1],
mid_channels=mid1_channels_list[0],
strides=2,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(InceptionDouble3x3Branch(
in_channels=in_channels,
out_channels=mid2_channels_list[2],
mid_channels=mid1_channels_list[1],
strides=2,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(nn.MaxPool2D(
pool_size=3,
strides=2,
padding=0,
ceil_mode=True))
def hybrid_forward(self, F, x):
x = self.branches(x)
return x
class BNInception(HybridBlock):
"""
BN-Inception model from 'Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate
Shift,' https://arxiv.org/abs/1502.03167.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels_list : list of int
Number of output channels for the initial unit.
mid1_channels_list : list of list of list of int
Number of pre-middle channels for each unit.
mid2_channels_list : list of list of list of int
Number of middle channels for each unit.
use_bias : bool, default True
Whether the convolution layer uses a bias vector.
use_bn : bool, default True
Whether to use BatchNorm layers.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels_list,
mid1_channels_list,
mid2_channels_list,
use_bias=True,
use_bn=True,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(BNInception, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(StemBlock(
in_channels=in_channels,
out_channels=init_block_channels_list[1],
mid_channels=init_block_channels_list[0],
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels_list[-1]
for i, channels_per_stage in enumerate(channels):
mid1_channels_list_i = mid1_channels_list[i]
mid2_channels_list_i = mid2_channels_list[i]
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
if (j == 0) and (i != 0):
stage.add(ReductionBlock(
in_channels=in_channels,
mid1_channels_list=mid1_channels_list_i[j],
mid2_channels_list=mid2_channels_list_i[j],
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats))
else:
avg_pool = (i != len(channels) - 1) or (j != len(channels_per_stage) - 1)
stage.add(InceptionBlock(
in_channels=in_channels,
mid1_channels_list=mid1_channels_list_i[j],
mid2_channels_list=mid2_channels_list_i[j],
avg_pool=avg_pool,
use_bias=use_bias,
use_bn=use_bn,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_bninception(model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create BN-Inception model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
init_block_channels_list = [64, 192]
channels = [[256, 320], [576, 576, 576, 608, 608], [1056, 1024, 1024]]
mid1_channels_list = [
[[64, 64],
[64, 64]],
[[128, 64], # 3c
[64, 96], # 4a
[96, 96], # 4a
[128, 128], # 4c
[128, 160]], # 4d
[[128, 192], # 4e
[192, 160], # 5a
[192, 192]],
]
mid2_channels_list = [
[[64, 64, 96, 32],
[64, 96, 96, 64]],
[[0, 160, 96, 0], # 3c
[224, 96, 128, 128], # 4a
[192, 128, 128, 128], # 4b
[160, 160, 160, 128], # 4c
[96, 192, 192, 128]], # 4d
[[0, 192, 256, 0], # 4e
[352, 320, 224, 128], # 5a
[352, 320, 224, 128]],
]
net = BNInception(
channels=channels,
init_block_channels_list=init_block_channels_list,
mid1_channels_list=mid1_channels_list,
mid2_channels_list=mid2_channels_list,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def bninception(**kwargs):
"""
BN-Inception model from 'Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate
Shift,' https://arxiv.org/abs/1502.03167.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_bninception(model_name="bninception", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
bninception,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != bninception or weight_count == 11295240)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 19,996 | 33.008503 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/msdnet.py | """
MSDNet for ImageNet-1K, implemented in Gluon.
Original paper: 'Multi-Scale Dense Networks for Resource Efficient Image Classification,'
https://arxiv.org/abs/1703.09844.
"""
__all__ = ['MSDNet', 'msdnet22', 'MultiOutputSequential', 'MSDFeatureBlock']
import os
import math
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block, conv3x3_block, DualPathSequential
from .resnet import ResInitBlock
class MultiOutputSequential(nn.HybridSequential):
"""
A sequential container for blocks. Blocks will be executed in the order they are added. Output value contains
results from all blocks.
"""
def __init__(self, **kwargs):
super(MultiOutputSequential, self).__init__(**kwargs)
def hybrid_forward(self, F, x):
outs = []
for block in self._children.values():
x = block(x)
outs.append(x)
return outs
class MultiBlockSequential(nn.HybridSequential):
"""
A sequential container for blocks. Blocks will be executed in the order they are added. Input is a list with
length equal to number of blocks.
"""
def __init__(self, **kwargs):
super(MultiBlockSequential, self).__init__(**kwargs)
def hybrid_forward(self, F, x0, x_rest):
outs = []
for block, x_i in zip(self._children.values(), [x0] + x_rest):
y = block(x_i)
outs.append(y)
return outs
class MSDBaseBlock(HybridBlock):
"""
MSDNet base block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
use_bottleneck : bool
Whether to use a bottleneck.
bottleneck_factor : int
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
strides,
use_bottleneck,
bottleneck_factor,
**kwargs):
super(MSDBaseBlock, self).__init__(**kwargs)
self.use_bottleneck = use_bottleneck
mid_channels = min(in_channels, bottleneck_factor * out_channels) if use_bottleneck else in_channels
with self.name_scope():
if self.use_bottleneck:
self.bn_conv = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels)
self.conv = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
strides=strides)
def hybrid_forward(self, F, x):
if self.use_bottleneck:
x = self.bn_conv(x)
x = self.conv(x)
return x
class MSDFirstScaleBlock(HybridBlock):
"""
MSDNet first scale dense block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
use_bottleneck : bool
Whether to use a bottleneck.
bottleneck_factor : int
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
use_bottleneck,
bottleneck_factor,
**kwargs):
super(MSDFirstScaleBlock, self).__init__(**kwargs)
assert (out_channels > in_channels)
inc_channels = out_channels - in_channels
with self.name_scope():
self.block = MSDBaseBlock(
in_channels=in_channels,
out_channels=inc_channels,
strides=1,
use_bottleneck=use_bottleneck,
bottleneck_factor=bottleneck_factor)
def hybrid_forward(self, F, x):
y = self.block(x)
y = F.concat(x, y, dim=1)
return y
class MSDScaleBlock(HybridBlock):
"""
MSDNet ordinary scale dense block.
Parameters:
----------
in_channels_prev : int
Number of input channels for the previous scale.
in_channels : int
Number of input channels for the current scale.
out_channels : int
Number of output channels.
use_bottleneck : bool
Whether to use a bottleneck.
bottleneck_factor_prev : int
Bottleneck factor for the previous scale.
bottleneck_factor : int
Bottleneck factor for the current scale.
"""
def __init__(self,
in_channels_prev,
in_channels,
out_channels,
use_bottleneck,
bottleneck_factor_prev,
bottleneck_factor,
**kwargs):
super(MSDScaleBlock, self).__init__(**kwargs)
assert (out_channels > in_channels)
assert (out_channels % 2 == 0)
inc_channels = out_channels - in_channels
mid_channels = inc_channels // 2
with self.name_scope():
self.down_block = MSDBaseBlock(
in_channels=in_channels_prev,
out_channels=mid_channels,
strides=2,
use_bottleneck=use_bottleneck,
bottleneck_factor=bottleneck_factor_prev)
self.curr_block = MSDBaseBlock(
in_channels=in_channels,
out_channels=mid_channels,
strides=1,
use_bottleneck=use_bottleneck,
bottleneck_factor=bottleneck_factor)
def hybrid_forward(self, F, x_prev, x):
y_prev = self.down_block(x_prev)
y = self.curr_block(x)
x = F.concat(x, y_prev, y, dim=1)
return x
class MSDInitLayer(HybridBlock):
"""
MSDNet initial (so-called first) layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : list/tuple of int
Number of output channels for each scale.
"""
def __init__(self,
in_channels,
out_channels,
**kwargs):
super(MSDInitLayer, self).__init__(**kwargs)
with self.name_scope():
self.scale_blocks = MultiOutputSequential()
for i, out_channels_per_scale in enumerate(out_channels):
if i == 0:
self.scale_blocks.add(ResInitBlock(
in_channels=in_channels,
out_channels=out_channels_per_scale))
else:
self.scale_blocks.add(conv3x3_block(
in_channels=in_channels,
out_channels=out_channels_per_scale,
strides=2))
in_channels = out_channels_per_scale
def hybrid_forward(self, F, x):
y = self.scale_blocks(x)
return y
class MSDLayer(HybridBlock):
"""
MSDNet ordinary layer.
Parameters:
----------
in_channels : list/tuple of int
Number of input channels for each input scale.
out_channels : list/tuple of int
Number of output channels for each output scale.
use_bottleneck : bool
Whether to use a bottleneck.
bottleneck_factors : list/tuple of int
Bottleneck factor for each input scale.
"""
def __init__(self,
in_channels,
out_channels,
use_bottleneck,
bottleneck_factors,
**kwargs):
super(MSDLayer, self).__init__(**kwargs)
in_scales = len(in_channels)
out_scales = len(out_channels)
self.dec_scales = in_scales - out_scales
assert (self.dec_scales >= 0)
with self.name_scope():
self.scale_blocks = nn.HybridSequential(prefix="")
for i in range(out_scales):
if (i == 0) and (self.dec_scales == 0):
self.scale_blocks.add(MSDFirstScaleBlock(
in_channels=in_channels[self.dec_scales + i],
out_channels=out_channels[i],
use_bottleneck=use_bottleneck,
bottleneck_factor=bottleneck_factors[self.dec_scales + i]))
else:
self.scale_blocks.add(MSDScaleBlock(
in_channels_prev=in_channels[self.dec_scales + i - 1],
in_channels=in_channels[self.dec_scales + i],
out_channels=out_channels[i],
use_bottleneck=use_bottleneck,
bottleneck_factor_prev=bottleneck_factors[self.dec_scales + i - 1],
bottleneck_factor=bottleneck_factors[self.dec_scales + i]))
def hybrid_forward(self, F, x0, x_rest):
x = [x0] + x_rest
outs = []
for i in range(len(self.scale_blocks)):
if (i == 0) and (self.dec_scales == 0):
y = self.scale_blocks[i](x[i])
else:
y = self.scale_blocks[i](
x[self.dec_scales + i - 1],
x[self.dec_scales + i])
outs.append(y)
return outs[0], outs[1:]
class MSDTransitionLayer(HybridBlock):
"""
MSDNet transition layer.
Parameters:
----------
in_channels : list/tuple of int
Number of input channels for each scale.
out_channels : list/tuple of int
Number of output channels for each scale.
"""
def __init__(self,
in_channels,
out_channels,
**kwargs):
super(MSDTransitionLayer, self).__init__(**kwargs)
assert (len(in_channels) == len(out_channels))
with self.name_scope():
self.scale_blocks = MultiBlockSequential()
for i in range(len(out_channels)):
self.scale_blocks.add(conv1x1_block(
in_channels=in_channels[i],
out_channels=out_channels[i]))
def hybrid_forward(self, F, x0, x_rest):
y = self.scale_blocks(x0, x_rest)
return y[0], y[1:]
class MSDFeatureBlock(HybridBlock):
"""
MSDNet feature block (stage of cascade, so-called block).
Parameters:
----------
in_channels : list of list of int
Number of input channels for each layer and for each input scale.
out_channels : list of list of int
Number of output channels for each layer and for each output scale.
use_bottleneck : bool
Whether to use a bottleneck.
bottleneck_factors : list of list of int
Bottleneck factor for each layer and for each input scale.
"""
def __init__(self,
in_channels,
out_channels,
use_bottleneck,
bottleneck_factors,
**kwargs):
super(MSDFeatureBlock, self).__init__(**kwargs)
with self.name_scope():
self.blocks = DualPathSequential(prefix="")
for i, out_channels_per_layer in enumerate(out_channels):
if len(bottleneck_factors[i]) == 0:
self.blocks.add(MSDTransitionLayer(
in_channels=in_channels,
out_channels=out_channels_per_layer))
else:
self.blocks.add(MSDLayer(
in_channels=in_channels,
out_channels=out_channels_per_layer,
use_bottleneck=use_bottleneck,
bottleneck_factors=bottleneck_factors[i]))
in_channels = out_channels_per_layer
def hybrid_forward(self, F, x0, x_rest):
x0, x_rest = self.blocks(x0, x_rest)
return [x0] + x_rest
class MSDClassifier(HybridBlock):
"""
MSDNet classifier.
Parameters:
----------
in_channels : int
Number of input channels.
classes : int
Number of classification classes.
"""
def __init__(self,
in_channels,
classes,
**kwargs):
super(MSDClassifier, self).__init__(**kwargs)
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(conv3x3_block(
in_channels=in_channels,
out_channels=in_channels,
strides=2))
self.features.add(conv3x3_block(
in_channels=in_channels,
out_channels=in_channels,
strides=2))
self.features.add(nn.AvgPool2D(
pool_size=2,
strides=2))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
class MSDNet(HybridBlock):
"""
MSDNet model from 'Multi-Scale Dense Networks for Resource Efficient Image Classification,'
https://arxiv.org/abs/1703.09844.
Parameters:
----------
channels : list of list of list of int
Number of output channels for each unit.
init_layer_channels : list of int
Number of output channels for the initial layer.
num_feature_blocks : int
Number of subnets.
use_bottleneck : bool
Whether to use a bottleneck.
bottleneck_factors : list of list of int
Bottleneck factor for each layers and for each input scale.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_layer_channels,
num_feature_blocks,
use_bottleneck,
bottleneck_factors,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(MSDNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.init_layer = MSDInitLayer(
in_channels=in_channels,
out_channels=init_layer_channels)
in_channels = init_layer_channels
self.feature_blocks = nn.HybridSequential(prefix="")
self.classifiers = nn.HybridSequential(prefix="")
for i in range(num_feature_blocks):
self.feature_blocks.add(MSDFeatureBlock(
in_channels=in_channels,
out_channels=channels[i],
use_bottleneck=use_bottleneck,
bottleneck_factors=bottleneck_factors[i]))
in_channels = channels[i][-1]
self.classifiers.add(MSDClassifier(
in_channels=in_channels[-1],
classes=classes))
def hybrid_forward(self, F, x, only_last=True):
x = self.init_layer(x)
outs = []
for feature_block, classifier in zip(self.feature_blocks, self.classifiers):
x = feature_block(x[0], x[1:])
y = classifier(x[-1])
outs.append(y)
if only_last:
return outs[-1]
else:
return outs
def get_msdnet(blocks,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create MSDNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
assert (blocks == 22)
num_scales = 4
num_feature_blocks = 10
base = 4
step = 2
reduction_rate = 0.5
growth = 6
growth_factor = [1, 2, 4, 4]
use_bottleneck = True
bottleneck_factor_per_scales = [1, 2, 4, 4]
assert (reduction_rate > 0.0)
init_layer_channels = [64 * c for c in growth_factor[:num_scales]]
step_mode = "even"
layers_per_subnets = [base]
for i in range(num_feature_blocks - 1):
layers_per_subnets.append(step if step_mode == 'even' else step * i + 1)
total_layers = sum(layers_per_subnets)
interval = math.ceil(total_layers / num_scales)
global_layer_ind = 0
channels = []
bottleneck_factors = []
in_channels_tmp = init_layer_channels
in_scales = num_scales
for i in range(num_feature_blocks):
layers_per_subnet = layers_per_subnets[i]
scales_i = []
channels_i = []
bottleneck_factors_i = []
for j in range(layers_per_subnet):
out_scales = int(num_scales - math.floor(global_layer_ind / interval))
global_layer_ind += 1
scales_i += [out_scales]
scale_offset = num_scales - out_scales
in_dec_scales = num_scales - len(in_channels_tmp)
out_channels = [in_channels_tmp[scale_offset - in_dec_scales + k] + growth * growth_factor[scale_offset + k]
for k in range(out_scales)]
in_dec_scales = num_scales - len(in_channels_tmp)
bottleneck_factors_ij = bottleneck_factor_per_scales[in_dec_scales:][:len(in_channels_tmp)]
in_channels_tmp = out_channels
channels_i += [out_channels]
bottleneck_factors_i += [bottleneck_factors_ij]
if in_scales > out_scales:
assert (in_channels_tmp[0] % growth_factor[scale_offset] == 0)
out_channels1 = int(math.floor(in_channels_tmp[0] / growth_factor[scale_offset] * reduction_rate))
out_channels = [out_channels1 * growth_factor[scale_offset + k] for k in range(out_scales)]
in_channels_tmp = out_channels
channels_i += [out_channels]
bottleneck_factors_i += [[]]
in_scales = out_scales
in_scales = scales_i[-1]
channels += [channels_i]
bottleneck_factors += [bottleneck_factors_i]
net = MSDNet(
channels=channels,
init_layer_channels=init_layer_channels,
num_feature_blocks=num_feature_blocks,
use_bottleneck=use_bottleneck,
bottleneck_factors=bottleneck_factors,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def msdnet22(**kwargs):
"""
MSDNet-22 model from 'Multi-Scale Dense Networks for Resource Efficient Image Classification,'
https://arxiv.org/abs/1703.09844.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_msdnet(blocks=22, model_name="msdnet22", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
msdnet22,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != msdnet22 or weight_count == 20106676)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 20,581 | 31.566456 | 120 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/zfnet.py | """
ZFNet for ImageNet-1K, implemented in Gluon.
Original paper: 'Visualizing and Understanding Convolutional Networks,' https://arxiv.org/abs/1311.2901.
"""
__all__ = ['zfnet', 'zfnetb']
import os
from mxnet import cpu
from .alexnet import AlexNet
def get_zfnet(version="a",
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create ZFNet model with specific parameters.
Parameters:
----------
version : str, default 'a'
Version of ZFNet ('a' or 'b').
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if version == "a":
channels = [[96], [256], [384, 384, 256]]
kernel_sizes = [[7], [5], [3, 3, 3]]
strides = [[2], [2], [1, 1, 1]]
paddings = [[1], [0], [1, 1, 1]]
use_lrn = True
elif version == "b":
channels = [[96], [256], [512, 1024, 512]]
kernel_sizes = [[7], [5], [3, 3, 3]]
strides = [[2], [2], [1, 1, 1]]
paddings = [[1], [0], [1, 1, 1]]
use_lrn = True
else:
raise ValueError("Unsupported ZFNet version {}".format(version))
net = AlexNet(
channels=channels,
kernel_sizes=kernel_sizes,
strides=strides,
paddings=paddings,
use_lrn=use_lrn,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def zfnet(**kwargs):
"""
ZFNet model from 'Visualizing and Understanding Convolutional Networks,' https://arxiv.org/abs/1311.2901.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_zfnet(model_name="zfnet", **kwargs)
def zfnetb(**kwargs):
"""
ZFNet-b model from 'Visualizing and Understanding Convolutional Networks,' https://arxiv.org/abs/1311.2901.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_zfnet(version="b", model_name="zfnetb", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
zfnet,
zfnetb,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != zfnet or weight_count == 62357608)
assert (model != zfnetb or weight_count == 107627624)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 4,058 | 28.201439 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/peleenet.py | """
PeleeNet for ImageNet-1K, implemented in Gluon.
Original paper: 'Pelee: A Real-Time Object Detection System on Mobile Devices,' https://arxiv.org/abs/1804.06882.
"""
__all__ = ['PeleeNet', 'peleenet']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from mxnet.gluon.contrib.nn import HybridConcurrent
from .common import conv1x1_block, conv3x3_block
class PeleeBranch1(HybridBlock):
"""
PeleeNet branch type 1 block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of intermediate channels.
strides : int or tuple/list of 2 int, default 1
Strides of the second convolution.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels,
strides=1,
bn_use_global_stats=False,
**kwargs):
super(PeleeBranch1, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class PeleeBranch2(HybridBlock):
"""
PeleeNet branch type 2 block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of intermediate channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels,
bn_use_global_stats,
**kwargs):
super(PeleeBranch2, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
self.conv3 = conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class StemBlock(HybridBlock):
"""
PeleeNet stem block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats,
**kwargs):
super(StemBlock, self).__init__(**kwargs)
mid1_channels = out_channels // 2
mid2_channels = out_channels * 2
with self.name_scope():
self.first_conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
strides=2)
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(PeleeBranch1(
in_channels=out_channels,
out_channels=out_channels,
mid_channels=mid1_channels,
strides=2,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(nn.MaxPool2D(
pool_size=2,
strides=2,
padding=0))
self.last_conv = conv1x1_block(
in_channels=mid2_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.first_conv(x)
x = self.branches(x)
x = self.last_conv(x)
return x
class DenseBlock(HybridBlock):
"""
PeleeNet dense block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bottleneck_size : int
Bottleneck width.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bottleneck_size,
bn_use_global_stats,
**kwargs):
super(DenseBlock, self).__init__(**kwargs)
inc_channels = (out_channels - in_channels) // 2
mid_channels = inc_channels * bottleneck_size
with self.name_scope():
self.branch1 = PeleeBranch1(
in_channels=in_channels,
out_channels=inc_channels,
mid_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats)
self.branch2 = PeleeBranch2(
in_channels=in_channels,
out_channels=inc_channels,
mid_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x1 = self.branch1(x)
x2 = self.branch2(x)
x = F.concat(x, x1, x2, dim=1)
return x
class TransitionBlock(HybridBlock):
"""
PeleeNet's transition block, like in DensNet, but with ordinary convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats,
**kwargs):
super(TransitionBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
self.pool = nn.AvgPool2D(
pool_size=2,
strides=2,
padding=0)
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.pool(x)
return x
class PeleeNet(HybridBlock):
"""
PeleeNet model from 'Pelee: A Real-Time Object Detection System on Mobile Devices,'
https://arxiv.org/abs/1804.06882.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck_sizes : list of int
Bottleneck sizes for each stage.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
dropout_rate : float, default 0.5
Parameter of Dropout layer. Faction of the input units to drop.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck_sizes,
bn_use_global_stats=False,
dropout_rate=0.5,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(PeleeNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(StemBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
bottleneck_size = bottleneck_sizes[i]
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
if i != 0:
stage.add(TransitionBlock(
in_channels=in_channels,
out_channels=in_channels,
bn_use_global_stats=bn_use_global_stats))
for j, out_channels in enumerate(channels_per_stage):
stage.add(DenseBlock(
in_channels=in_channels,
out_channels=out_channels,
bottleneck_size=bottleneck_size,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(conv1x1_block(
in_channels=in_channels,
out_channels=in_channels,
bn_use_global_stats=bn_use_global_stats))
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dropout(rate=dropout_rate))
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_peleenet(model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create PeleeNet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
init_block_channels = 32
growth_rate = 32
layers = [3, 4, 8, 6]
bottleneck_sizes = [1, 2, 4, 4]
from functools import reduce
channels = reduce(
lambda xi, yi: xi + [reduce(
lambda xj, yj: xj + [xj[-1] + yj],
[growth_rate] * yi,
[xi[-1][-1]])[1:]],
layers,
[[init_block_channels]])[1:]
net = PeleeNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck_sizes=bottleneck_sizes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def peleenet(**kwargs):
"""
PeleeNet model from 'Pelee: A Real-Time Object Detection System on Mobile Devices,'
https://arxiv.org/abs/1804.06882.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_peleenet(model_name="peleenet", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
peleenet,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != peleenet or weight_count == 2802248)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 13,545 | 31.252381 | 117 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/regnetv.py | """
RegNetV for ImageNet-1K, implemented in Gluon.
Original paper: 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
"""
__all__ = ['RegNetV', 'regnetv002', 'regnetv004', 'regnetv006', 'regnetv008', 'regnetv016', 'regnetv032', 'regnetv040',
'regnetv064', 'regnetv080', 'regnetv120', 'regnetv160', 'regnetv320']
import os
import numpy as np
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block, conv3x3_block, dwsconv3x3_block
class DownBlock(HybridBlock):
"""
ResNet(A)-like downsample block for the identity branch of a residual unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(DownBlock, self).__init__(**kwargs)
with self.name_scope():
self.pool = nn.AvgPool2D(
pool_size=strides,
strides=strides,
ceil_mode=True,
count_include_pad=False)
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=None)
def hybrid_forward(self, F, x):
x = self.pool(x)
x = self.conv(x)
return x
class RegNetVUnit(HybridBlock):
"""
RegNetV unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
downscale : bool
Whether to downscale tensor.
dw_use_bn : bool
Whether to use BatchNorm layer (depthwise convolution block).
dw_activation : function or str or None
Activation function after the depthwise convolution block.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
downscale,
dw_use_bn,
dw_activation,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(RegNetVUnit, self).__init__(**kwargs)
self.downscale = downscale
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
if self.downscale:
self.pool = nn.AvgPool2D(
pool_size=3,
strides=2,
padding=1)
self.conv2 = dwsconv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
dw_use_bn=dw_use_bn,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
dw_activation=dw_activation,
pw_activation=None)
if self.downscale:
self.identity_block = DownBlock(
in_channels=in_channels,
out_channels=out_channels,
strides=2,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
if self.downscale:
identity = self.identity_block(x)
else:
identity = x
x = self.conv1(x)
if self.downscale:
x = self.pool(x)
x = self.conv2(x)
x = x + identity
x = self.activ(x)
return x
class RegNetVInitBlock(HybridBlock):
"""
RegNetV specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(RegNetVInitBlock, self).__init__(**kwargs)
mid_channels = out_channels // 2
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.pool = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=1)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.pool(x)
x = self.conv2(x)
return x
class RegNetV(HybridBlock):
"""
RegNet model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
dw_use_bn : bool, default True
Whether to use BatchNorm layer (depthwise convolution block).
dw_activation : function or str or None, default nn.Activation('relu')
Activation function after the depthwise convolution block.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
dw_use_bn=True,
dw_activation=(lambda: nn.Activation("relu")),
bn_use_global_stats=False,
bn_cudnn_off=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(RegNetV, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(RegNetVInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
downscale = (j == 0)
stage.add(RegNetVUnit(
in_channels=in_channels,
out_channels=out_channels,
downscale=downscale,
dw_use_bn=dw_use_bn,
dw_activation=dw_activation,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_regnet(channels_init,
channels_slope,
channels_mult,
depth,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create RegNet model with specific parameters.
Parameters:
----------
channels_init : float
Initial value for channels/widths.
channels_slope : float
Slope value for channels/widths.
width_mult : float
Width multiplier value.
depth : int
Depth value.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
divisor = 8
assert (channels_slope >= 0) and (channels_init > 0) and (channels_mult > 1) and (channels_init % divisor == 0)
# Generate continuous per-block channels/widths:
channels_cont = np.arange(depth) * channels_slope + channels_init
# Generate quantized per-block channels/widths:
channels_exps = np.round(np.log(channels_cont / channels_init) / np.log(channels_mult))
channels = channels_init * np.power(channels_mult, channels_exps)
channels = (np.round(channels / divisor) * divisor).astype(np.int)
# Generate per stage channels/widths and layers/depths:
channels_per_stage, layers = np.unique(channels, return_counts=True)
channels = [[ci] * li for (ci, li) in zip(channels_per_stage, layers)]
init_block_channels = 32
dws_simplified = True
if dws_simplified:
dw_use_bn = False
dw_activation = None
else:
dw_use_bn = True
dw_activation = (lambda: nn.Activation("relu"))
net = RegNetV(
channels=channels,
init_block_channels=init_block_channels,
dw_use_bn=dw_use_bn,
dw_activation=dw_activation,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def regnetv002(**kwargs):
"""
RegNetV-200MF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_regnet(channels_init=24, channels_slope=36.44, channels_mult=2.49, depth=13,
model_name="regnetv002", **kwargs)
def regnetv004(**kwargs):
"""
RegNetV-400MF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_regnet(channels_init=24, channels_slope=24.48, channels_mult=2.54, depth=22,
model_name="regnetv004", **kwargs)
def regnetv006(**kwargs):
"""
RegNetV-600MF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_regnet(channels_init=48, channels_slope=36.97, channels_mult=2.24, depth=16,
model_name="regnetv006", **kwargs)
def regnetv008(**kwargs):
"""
RegNetV-800MF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_regnet(channels_init=56, channels_slope=35.73, channels_mult=2.28, depth=16,
model_name="regnetv008", **kwargs)
def regnetv016(**kwargs):
"""
RegNetV-1.6GF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_regnet(channels_init=80, channels_slope=34.01, channels_mult=2.25, depth=18,
model_name="regnetv016", **kwargs)
def regnetv032(**kwargs):
"""
RegNetV-3.2GF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_regnet(channels_init=88, channels_slope=26.31, channels_mult=2.25, depth=25,
model_name="regnetv032", **kwargs)
def regnetv040(**kwargs):
"""
RegNetV-4.0GF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_regnet(channels_init=96, channels_slope=38.65, channels_mult=2.43, depth=23,
model_name="regnetv040", **kwargs)
def regnetv064(**kwargs):
"""
RegNetV-6.4GF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_regnet(channels_init=184, channels_slope=60.83, channels_mult=2.07, depth=17,
model_name="regnetv064", **kwargs)
def regnetv080(**kwargs):
"""
RegNetV-8.0GF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_regnet(channels_init=80, channels_slope=49.56, channels_mult=2.88, depth=23,
model_name="regnetv080", **kwargs)
def regnetv120(**kwargs):
"""
RegNetV-12GF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_regnet(channels_init=168, channels_slope=73.36, channels_mult=2.37, depth=19,
model_name="regnetv120", **kwargs)
def regnetv160(**kwargs):
"""
RegNetV-16GF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_regnet(channels_init=216, channels_slope=55.59, channels_mult=2.1, depth=22,
model_name="regnetv160", **kwargs)
def regnetv320(**kwargs):
"""
RegNetV-32GF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_regnet(channels_init=320, channels_slope=69.86, channels_mult=2.0, depth=23,
model_name="regnetv320", **kwargs)
def _test():
import numpy as np
import mxnet as mx
dws_simplified = True
pretrained = False
models = [
regnetv002,
regnetv004,
regnetv006,
regnetv008,
regnetv016,
regnetv032,
regnetv040,
regnetv064,
regnetv080,
regnetv120,
regnetv160,
regnetv320,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
if dws_simplified:
assert (model != regnetv002 or weight_count == 2476840)
assert (model != regnetv004 or weight_count == 4467080)
assert (model != regnetv006 or weight_count == 5242936)
assert (model != regnetv008 or weight_count == 6353000)
assert (model != regnetv016 or weight_count == 7824440)
assert (model != regnetv032 or weight_count == 11540536)
assert (model != regnetv040 or weight_count == 18323824)
assert (model != regnetv064 or weight_count == 20854680)
assert (model != regnetv080 or weight_count == 21930224)
assert (model != regnetv120 or weight_count == 32833720)
assert (model != regnetv160 or weight_count == 36213360)
assert (model != regnetv320 or weight_count == 64659576)
else:
assert (model != regnetv002 or weight_count == 2479160)
assert (model != regnetv004 or weight_count == 4474712)
assert (model != regnetv006 or weight_count == 5249352)
assert (model != regnetv008 or weight_count == 6360344)
assert (model != regnetv016 or weight_count == 7833768)
assert (model != regnetv032 or weight_count == 11556520)
assert (model != regnetv040 or weight_count == 18343728)
assert (model != regnetv064 or weight_count == 20873384)
assert (model != regnetv080 or weight_count == 21952400)
assert (model != regnetv120 or weight_count == 32859432)
assert (model != regnetv160 or weight_count == 36244240)
assert (model != regnetv320 or weight_count == 64704008)
batch = 14
size = 224
x = mx.nd.zeros((batch, 3, size, size), ctx=ctx)
y = net(x)
assert (y.shape == (batch, 1000))
if __name__ == "__main__":
_test()
| 21,904 | 34.444984 | 119 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/sharesnet.py | """
ShaResNet for ImageNet-1K, implemented in Gluon.
Original paper: 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
"""
__all__ = ['ShaResNet', 'sharesnet18', 'sharesnet34', 'sharesnet50', 'sharesnet50b', 'sharesnet101', 'sharesnet101b',
'sharesnet152', 'sharesnet152b']
import os
from inspect import isfunction
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import ReLU6, conv1x1_block, conv3x3_block
from .resnet import ResInitBlock
class ShaConvBlock(HybridBlock):
"""
Shared convolution block with Batch normalization and ReLU/ReLU6 activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
activation : function or str or None, default nn.Activation("relu")
Activation function or name of activation function.
activate : bool, default True
Whether activate the convolution block.
shared_conv : HybridBlock, default None
Shared convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
dilation=1,
groups=1,
use_bias=False,
bn_use_global_stats=False,
activation=(lambda: nn.Activation("relu")),
activate=True,
shared_conv=None,
**kwargs):
super(ShaConvBlock, self).__init__(**kwargs)
self.activate = activate
with self.name_scope():
if shared_conv is None:
self.conv = nn.Conv2D(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
in_channels=in_channels)
else:
self.conv = shared_conv
self.bn = nn.BatchNorm(
in_channels=out_channels,
use_global_stats=bn_use_global_stats)
if self.activate:
assert (activation is not None)
if isfunction(activation):
self.activ = activation()
elif isinstance(activation, str):
if activation == "relu6":
self.activ = ReLU6()
else:
self.activ = nn.Activation(activation)
else:
self.activ = activation
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.bn(x)
if self.activate:
x = self.activ(x)
return x
def sha_conv3x3_block(in_channels,
out_channels,
strides=1,
padding=1,
dilation=1,
groups=1,
use_bias=False,
bn_use_global_stats=False,
activation=(lambda: nn.Activation("relu")),
activate=True,
shared_conv=None,
**kwargs):
"""
3x3 version of the shared convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
activation : function or str or None, default nn.Activation("relu")
Activation function or name of activation function.
activate : bool, default True
Whether activate the convolution block.
shared_conv : HybridBlock, default None
Shared convolution layer.
"""
return ShaConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
bn_use_global_stats=bn_use_global_stats,
activation=activation,
activate=activate,
shared_conv=shared_conv,
**kwargs)
class ShaResBlock(HybridBlock):
"""
Simple ShaResNet block for residual path in ShaResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
shared_conv : HybridBlock, default None
Shared convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats,
shared_conv=None,
**kwargs):
super(ShaResBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = sha_conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation=None,
activate=False,
shared_conv=shared_conv)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class ShaResBottleneck(HybridBlock):
"""
ShaResNet bottleneck block for residual path in ShaResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bottleneck_factor : int, default 4
Bottleneck factor.
conv1_stride : bool, default False
Whether to use stride in the first or the second convolution layer of the block.
shared_conv : HybridBlock, default None
Shared convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats=False,
conv1_stride=False,
bottleneck_factor=4,
shared_conv=None,
**kwargs):
super(ShaResBottleneck, self).__init__(**kwargs)
assert (conv1_stride or not ((strides > 1) and (shared_conv is not None)))
mid_channels = out_channels // bottleneck_factor
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
strides=(strides if conv1_stride else 1),
bn_use_global_stats=bn_use_global_stats)
self.conv2 = sha_conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
strides=(1 if conv1_stride else strides),
bn_use_global_stats=bn_use_global_stats,
shared_conv=shared_conv)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation=None)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class ShaResUnit(HybridBlock):
"""
ShaResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer of the block.
shared_conv : HybridBlock, default None
Shared convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats,
bottleneck,
conv1_stride,
shared_conv=None,
**kwargs):
super(ShaResUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
if bottleneck:
self.body = ShaResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
conv1_stride=conv1_stride,
shared_conv=shared_conv)
else:
self.body = ShaResBlock(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
shared_conv=shared_conv)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
activation=None)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class ShaResNet(HybridBlock):
"""
ShaResNet model from 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(ShaResNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
shared_conv = None
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
unit = ShaResUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
shared_conv=shared_conv)
if (shared_conv is None) and not (bottleneck and not conv1_stride and strides > 1):
shared_conv = unit.body.conv2.conv
stage.add(unit)
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_sharesnet(blocks,
conv1_stride=True,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create ShaResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if blocks == 18:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
else:
raise ValueError("Unsupported ShaResNet with number of blocks: {}".format(blocks))
init_block_channels = 64
if blocks < 50:
channels_per_layers = [64, 128, 256, 512]
bottleneck = False
else:
channels_per_layers = [256, 512, 1024, 2048]
bottleneck = True
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = ShaResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def sharesnet18(**kwargs):
"""
ShaResNet-18 model from 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=18, model_name="sharesnet18", **kwargs)
def sharesnet34(**kwargs):
"""
ShaResNet-34 model from 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=34, model_name="sharesnet34", **kwargs)
def sharesnet50(**kwargs):
"""
ShaResNet-50 model from 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=50, model_name="sharesnet50", **kwargs)
def sharesnet50b(**kwargs):
"""
ShaResNet-50b model with stride at the second convolution in bottleneck block from 'ShaResNet: reducing residual
network parameter number by sharing weights,' https://arxiv.org/abs/1702.08782.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=50, conv1_stride=False, model_name="sharesnet50b", **kwargs)
def sharesnet101(**kwargs):
"""
ShaResNet-101 model from 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=101, model_name="sharesnet101", **kwargs)
def sharesnet101b(**kwargs):
"""
ShaResNet-101b model with stride at the second convolution in bottleneck block from 'ShaResNet: reducing residual
network parameter number by sharing weights,' https://arxiv.org/abs/1702.08782.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=101, conv1_stride=False, model_name="sharesnet101b", **kwargs)
def sharesnet152(**kwargs):
"""
ShaResNet-152 model from 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=152, model_name="sharesnet152", **kwargs)
def sharesnet152b(**kwargs):
"""
ShaResNet-152b model with stride at the second convolution in bottleneck block from 'ShaResNet: reducing residual
network parameter number by sharing weights,' https://arxiv.org/abs/1702.08782.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sharesnet(blocks=152, conv1_stride=False, model_name="sharesnet152b", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
sharesnet18,
sharesnet34,
sharesnet50,
sharesnet50b,
sharesnet101,
sharesnet101b,
sharesnet152,
sharesnet152b,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != sharesnet18 or weight_count == 8556072)
assert (model != sharesnet34 or weight_count == 13613864)
assert (model != sharesnet50 or weight_count == 17373224)
assert (model != sharesnet50b or weight_count == 20469800)
assert (model != sharesnet101 or weight_count == 26338344)
assert (model != sharesnet101b or weight_count == 29434920)
assert (model != sharesnet152 or weight_count == 33724456)
assert (model != sharesnet152b or weight_count == 36821032)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 23,240 | 33.73991 | 117 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/ibppose_coco.py | """
IBPPose for COCO Keypoint, implemented in Gluon.
Original paper: 'Simple Pose: Rethinking and Improving a Bottom-up Approach for Multi-Person Pose Estimation,'
https://arxiv.org/abs/1911.10529.
"""
__all__ = ['IbpPose', 'ibppose_coco']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import get_activation_layer, conv1x1_block, conv3x3_block, conv7x7_block, SEBlock, Hourglass,\
InterpolationBlock
class IbpResBottleneck(HybridBlock):
"""
Bottleneck block for residual path in the residual unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
use_bias : bool, default False
Whether the layer uses a bias vector.
bottleneck_factor : int, default 2
Bottleneck factor.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
out_channels,
strides,
use_bias=False,
bottleneck_factor=2,
activation=(lambda: nn.Activation("relu")),
**kwargs):
super(IbpResBottleneck, self).__init__(**kwargs)
mid_channels = out_channels // bottleneck_factor
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
use_bias=use_bias,
activation=activation)
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
strides=strides,
use_bias=use_bias,
activation=activation)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
use_bias=use_bias,
activation=None)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class IbpResUnit(HybridBlock):
"""
ResNet-like residual unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
use_bias : bool, default False
Whether the layer uses a bias vector.
bottleneck_factor : int, default 2
Bottleneck factor.
activation : function or str or None, default nn.Activation('relu')
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
out_channels,
strides=1,
use_bias=False,
bottleneck_factor=2,
activation=(lambda: nn.Activation("relu")),
**kwargs):
super(IbpResUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
self.body = IbpResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
use_bias=use_bias,
bottleneck_factor=bottleneck_factor,
activation=activation)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
use_bias=use_bias,
activation=None)
self.activ = get_activation_layer(activation)
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class IbpBackbone(HybridBlock):
"""
IBPPose backbone.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
activation : function or str or None
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
out_channels,
activation,
**kwargs):
super(IbpBackbone, self).__init__(**kwargs)
dilations = (3, 3, 4, 4, 5, 5)
mid1_channels = out_channels // 4
mid2_channels = out_channels // 2
with self.name_scope():
self.conv1 = conv7x7_block(
in_channels=in_channels,
out_channels=mid1_channels,
strides=2,
activation=activation)
self.res1 = IbpResUnit(
in_channels=mid1_channels,
out_channels=mid2_channels,
activation=activation)
self.pool = nn.MaxPool2D(
pool_size=2,
strides=2)
self.res2 = IbpResUnit(
in_channels=mid2_channels,
out_channels=mid2_channels,
activation=activation)
self.dilation_branch = nn.HybridSequential(prefix="")
for dilation in dilations:
self.dilation_branch.add(conv3x3_block(
in_channels=mid2_channels,
out_channels=mid2_channels,
padding=dilation,
dilation=dilation,
activation=activation))
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.res1(x)
x = self.pool(x)
x = self.res2(x)
y = self.dilation_branch(x)
x = F.concat(x, y, dim=1)
return x
class IbpDownBlock(HybridBlock):
"""
IBPPose down block for the hourglass.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
activation : function or str or None
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
out_channels,
activation,
**kwargs):
super(IbpDownBlock, self).__init__(**kwargs)
with self.name_scope():
self.down = nn.MaxPool2D(
pool_size=2,
strides=2)
self.res = IbpResUnit(
in_channels=in_channels,
out_channels=out_channels,
activation=activation)
def hybrid_forward(self, F, x):
x = self.down(x)
x = self.res(x)
return x
class IbpUpBlock(HybridBlock):
"""
IBPPose up block for the hourglass.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
use_bn : bool
Whether to use BatchNorm layer.
activation : function or str or None
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
out_channels,
use_bn,
activation,
**kwargs):
super(IbpUpBlock, self).__init__(**kwargs)
with self.name_scope():
self.res = IbpResUnit(
in_channels=in_channels,
out_channels=out_channels,
activation=activation)
self.up = InterpolationBlock(
scale_factor=2,
bilinear=False)
self.conv = conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
use_bias=(not use_bn),
use_bn=use_bn,
activation=activation)
def hybrid_forward(self, F, x):
x = self.res(x)
x = self.up(x)
x = self.conv(x)
return x
class MergeBlock(HybridBlock):
"""
IBPPose merge block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
use_bn : bool
Whether to use BatchNorm layer.
"""
def __init__(self,
in_channels,
out_channels,
use_bn,
**kwargs):
super(MergeBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
use_bias=(not use_bn),
use_bn=use_bn,
activation=None)
def hybrid_forward(self, F, x):
return self.conv(x)
class IbpPreBlock(HybridBlock):
"""
IBPPose preliminary decoder block.
Parameters:
----------
out_channels : int
Number of output channels.
use_bn : bool
Whether to use BatchNorm layer.
activation : function or str or None
Activation function or name of activation function.
"""
def __init__(self,
out_channels,
use_bn,
activation,
**kwargs):
super(IbpPreBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
use_bias=(not use_bn),
use_bn=use_bn,
activation=activation)
self.conv2 = conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
use_bias=(not use_bn),
use_bn=use_bn,
activation=activation)
self.se = SEBlock(
channels=out_channels,
use_conv=False,
mid_activation=activation)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.se(x)
return x
class IbpPass(HybridBlock):
"""
IBPPose single pass decoder block.
Parameters:
----------
channels : int
Number of input/output channels.
mid_channels : int
Number of middle channels.
depth : int
Depth of hourglass.
growth_rate : int
Addition for number of channel for each level.
use_bn : bool
Whether to use BatchNorm layer.
activation : function or str or None
Activation function or name of activation function.
"""
def __init__(self,
channels,
mid_channels,
depth,
growth_rate,
merge,
use_bn,
activation,
**kwargs):
super(IbpPass, self).__init__(**kwargs)
self.merge = merge
with self.name_scope():
down_seq = nn.HybridSequential(prefix="")
up_seq = nn.HybridSequential(prefix="")
skip_seq = nn.HybridSequential(prefix="")
top_channels = channels
bottom_channels = channels
for i in range(depth + 1):
skip_seq.add(IbpResUnit(
in_channels=top_channels,
out_channels=top_channels,
activation=activation))
bottom_channels += growth_rate
if i < depth:
down_seq.add(IbpDownBlock(
in_channels=top_channels,
out_channels=bottom_channels,
activation=activation))
up_seq.add(IbpUpBlock(
in_channels=bottom_channels,
out_channels=top_channels,
use_bn=use_bn,
activation=activation))
top_channels = bottom_channels
self.hg = Hourglass(
down_seq=down_seq,
up_seq=up_seq,
skip_seq=skip_seq)
self.pre_block = IbpPreBlock(
out_channels=channels,
use_bn=use_bn,
activation=activation)
self.post_block = conv1x1_block(
in_channels=channels,
out_channels=mid_channels,
use_bias=True,
use_bn=False,
activation=None)
if self.merge:
self.pre_merge_block = MergeBlock(
in_channels=channels,
out_channels=channels,
use_bn=use_bn)
self.post_merge_block = MergeBlock(
in_channels=mid_channels,
out_channels=channels,
use_bn=use_bn)
def hybrid_forward(self, F, x, x_prev):
x = self.hg(x)
if x_prev is not None:
x = x + x_prev
y = self.pre_block(x)
z = self.post_block(y)
if self.merge:
z = self.post_merge_block(z) + self.pre_merge_block(y)
return z
class IbpPose(HybridBlock):
"""
IBPPose model from 'Simple Pose: Rethinking and Improving a Bottom-up Approach for Multi-Person Pose Estimation,'
https://arxiv.org/abs/1911.10529.
Parameters:
----------
passes : int
Number of passes.
backbone_out_channels : int
Number of output channels for the backbone.
outs_channels : int
Number of output channels for the backbone.
depth : int
Depth of hourglass.
growth_rate : int
Addition for number of channel for each level.
use_bn : bool
Whether to use BatchNorm layer.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (256, 256)
Spatial size of the expected input image.
"""
def __init__(self,
passes,
backbone_out_channels,
outs_channels,
depth,
growth_rate,
use_bn,
in_channels=3,
in_size=(256, 256),
**kwargs):
super(IbpPose, self).__init__(**kwargs)
self.in_size = in_size
activation = (lambda: nn.LeakyReLU(alpha=0.01))
with self.name_scope():
self.backbone = IbpBackbone(
in_channels=in_channels,
out_channels=backbone_out_channels,
activation=activation)
self.decoder = nn.HybridSequential(prefix="")
for i in range(passes):
merge = (i != passes - 1)
self.decoder.add(IbpPass(
channels=backbone_out_channels,
mid_channels=outs_channels,
depth=depth,
growth_rate=growth_rate,
merge=merge,
use_bn=use_bn,
activation=activation))
def hybrid_forward(self, F, x):
x = self.backbone(x)
x_prev = None
for block in self.decoder._children.values():
if x_prev is not None:
x = x + x_prev
x_prev = block(x, x_prev)
return x_prev
def get_ibppose(model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create IBPPose model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
passes = 4
backbone_out_channels = 256
outs_channels = 50
depth = 4
growth_rate = 128
use_bn = True
net = IbpPose(
passes=passes,
backbone_out_channels=backbone_out_channels,
outs_channels=outs_channels,
depth=depth,
growth_rate=growth_rate,
use_bn=use_bn,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def ibppose_coco(**kwargs):
"""
IBPPose model for COCO Keypoint from 'Simple Pose: Rethinking and Improving a Bottom-up Approach for Multi-Person
Pose Estimation,' https://arxiv.org/abs/1911.10529.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ibppose(model_name="ibppose_coco", **kwargs)
def _test():
import numpy as np
import mxnet as mx
in_size = (256, 256)
pretrained = False
models = [
ibppose_coco,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != ibppose_coco or weight_count == 95827784)
batch = 14
x = mx.nd.random.normal(shape=(batch, 3, in_size[0], in_size[1]), ctx=ctx)
y = net(x)
assert (y.shape == (batch, 50, in_size[0] // 4, in_size[0] // 4))
if __name__ == "__main__":
_test()
| 18,529 | 29.883333 | 117 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/xception.py | """
Xception for ImageNet-1K, implemented in Gluon.
Original paper: 'Xception: Deep Learning with Depthwise Separable Convolutions,' https://arxiv.org/abs/1610.02357.
"""
__all__ = ['Xception', 'xception']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block, conv3x3_block
class DwsConv(HybridBlock):
"""
Depthwise separable convolution layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 0
Padding value for convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides=1,
padding=0,
**kwargs):
super(DwsConv, self).__init__(**kwargs)
with self.name_scope():
self.dw_conv = nn.Conv2D(
channels=in_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
groups=in_channels,
use_bias=False,
in_channels=in_channels)
self.pw_conv = nn.Conv2D(
channels=out_channels,
kernel_size=1,
use_bias=False,
in_channels=in_channels)
def hybrid_forward(self, F, x):
x = self.dw_conv(x)
x = self.pw_conv(x)
return x
class DwsConvBlock(HybridBlock):
"""
Depthwise separable convolution block with batchnorm and ReLU pre-activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
activate : bool
Whether activate the convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
bn_use_global_stats,
activate,
**kwargs):
super(DwsConvBlock, self).__init__(**kwargs)
self.activate = activate
with self.name_scope():
if self.activate:
self.activ = nn.Activation("relu")
self.conv = DwsConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding)
self.bn = nn.BatchNorm(
in_channels=out_channels,
use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
if self.activate:
x = self.activ(x)
x = self.conv(x)
x = self.bn(x)
return x
def dws_conv3x3_block(in_channels,
out_channels,
bn_use_global_stats,
activate):
"""
3x3 version of the depthwise separable convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
activate : bool
Whether activate the convolution block.
"""
return DwsConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
strides=1,
padding=1,
bn_use_global_stats=bn_use_global_stats,
activate=activate)
class XceptionUnit(HybridBlock):
"""
Xception unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the downsample polling.
reps : int
Number of repetitions.
start_with_relu : bool, default True
Whether start with ReLU activation.
grow_first : bool, default True
Whether start from growing.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
reps,
start_with_relu=True,
grow_first=True,
bn_use_global_stats=False,
**kwargs):
super(XceptionUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
activation=None)
self.body = nn.HybridSequential(prefix="")
for i in range(reps):
if (grow_first and (i == 0)) or ((not grow_first) and (i == reps - 1)):
in_channels_i = in_channels
out_channels_i = out_channels
else:
if grow_first:
in_channels_i = out_channels
out_channels_i = out_channels
else:
in_channels_i = in_channels
out_channels_i = in_channels
activate = start_with_relu if (i == 0) else True
self.body.add(dws_conv3x3_block(
in_channels=in_channels_i,
out_channels=out_channels_i,
bn_use_global_stats=bn_use_global_stats,
activate=activate))
if strides != 1:
self.body.add(nn.MaxPool2D(
pool_size=3,
strides=strides,
padding=1))
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = F.identity(x)
x = self.body(x)
x = x + identity
return x
class XceptionInitBlock(HybridBlock):
"""
Xception specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
bn_use_global_stats,
**kwargs):
super(XceptionInitBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=32,
strides=2,
padding=0,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = conv3x3_block(
in_channels=32,
out_channels=64,
strides=1,
padding=0,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class XceptionFinalBlock(HybridBlock):
"""
Xception specific final block.
Parameters:
----------
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
bn_use_global_stats,
**kwargs):
super(XceptionFinalBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = dws_conv3x3_block(
in_channels=1024,
out_channels=1536,
bn_use_global_stats=bn_use_global_stats,
activate=False)
self.conv2 = dws_conv3x3_block(
in_channels=1536,
out_channels=2048,
bn_use_global_stats=bn_use_global_stats,
activate=True)
self.activ = nn.Activation("relu")
self.pool = nn.AvgPool2D(
pool_size=10,
strides=1)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.activ(x)
x = self.pool(x)
return x
class Xception(HybridBlock):
"""
Xception model from 'Xception: Deep Learning with Depthwise Separable Convolutions,'
https://arxiv.org/abs/1610.02357.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
bn_use_global_stats=False,
in_channels=3,
in_size=(299, 299),
classes=1000,
**kwargs):
super(Xception, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(XceptionInitBlock(
in_channels=in_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = 64
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
stage.add(XceptionUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=(2 if (j == 0) else 1),
reps=(2 if (j == 0) else 3),
start_with_relu=((i != 0) or (j != 0)),
grow_first=((i != len(channels) - 1) or (j != len(channels_per_stage) - 1)),
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(XceptionFinalBlock(bn_use_global_stats=bn_use_global_stats))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=2048))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_xception(model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create Xception model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
channels = [[128], [256], [728] * 9, [1024]]
net = Xception(
channels=channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def xception(**kwargs):
"""
Xception model from 'Xception: Deep Learning with Depthwise Separable Convolutions,'
https://arxiv.org/abs/1610.02357.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_xception(model_name="xception", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
xception,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != xception or weight_count == 22855952)
x = mx.nd.zeros((1, 3, 299, 299), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 14,182 | 30.87191 | 118 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/darknet53.py | """
DarkNet-53 for ImageNet-1K, implemented in Gluon.
Original source: 'YOLOv3: An Incremental Improvement,' https://arxiv.org/abs/1804.02767.
"""
__all__ = ['DarkNet53', 'darknet53']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block, conv3x3_block
class DarkUnit(HybridBlock):
"""
DarkNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
alpha : float
Slope coefficient for Leaky ReLU activation.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats,
alpha,
**kwargs):
super(DarkUnit, self).__init__(**kwargs)
assert (out_channels % 2 == 0)
mid_channels = out_channels // 2
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats,
activation=nn.LeakyReLU(alpha=alpha))
self.conv2 = conv3x3_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation=nn.LeakyReLU(alpha=alpha))
def hybrid_forward(self, F, x):
identity = x
x = self.conv1(x)
x = self.conv2(x)
return x + identity
class DarkNet53(HybridBlock):
"""
DarkNet-53 model from 'YOLOv3: An Incremental Improvement,' https://arxiv.org/abs/1804.02767.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
alpha : float, default 0.1
Slope coefficient for Leaky ReLU activation.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
alpha=0.1,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(DarkNet53, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats,
activation=nn.LeakyReLU(alpha=alpha)))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
if j == 0:
stage.add(conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
strides=2,
bn_use_global_stats=bn_use_global_stats,
activation=nn.LeakyReLU(alpha=alpha)))
else:
stage.add(DarkUnit(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
alpha=alpha))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_darknet53(model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create DarkNet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
init_block_channels = 32
layers = [2, 3, 9, 9, 5]
channels_per_layers = [64, 128, 256, 512, 1024]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = DarkNet53(
channels=channels,
init_block_channels=init_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def darknet53(**kwargs):
"""
DarkNet-53 'Reference' model from 'YOLOv3: An Incremental Improvement,' https://arxiv.org/abs/1804.02767.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_darknet53(model_name="darknet53", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
darknet53,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != darknet53 or weight_count == 41609928)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 7,537 | 31.917031 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/mobilenet.py | """
MobileNet for ImageNet-1K, implemented in Gluon.
Original paper: 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
"""
__all__ = ['MobileNet', 'mobilenet_w1', 'mobilenet_w3d4', 'mobilenet_wd2', 'mobilenet_wd4', 'get_mobilenet']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv3x3_block, dwsconv3x3_block
class MobileNet(HybridBlock):
"""
MobileNet model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
first_stage_stride : bool
Whether stride is used at the first stage.
dw_use_bn : bool, default True
Whether to use BatchNorm layer (depthwise convolution block).
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
dw_activation : function or str or None, default nn.Activation('relu')
Activation function after the depthwise convolution block.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
first_stage_stride,
dw_use_bn=True,
bn_use_global_stats=False,
bn_cudnn_off=False,
dw_activation=(lambda: nn.Activation("relu")),
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(MobileNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
init_block_channels = channels[0][0]
self.features.add(conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
strides=2,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels[1:]):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and ((i != 0) or first_stage_stride) else 1
stage.add(dwsconv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
dw_use_bn=dw_use_bn,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
dw_activation=dw_activation))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_mobilenet(width_scale,
dws_simplified=False,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create MobileNet model with specific parameters.
Parameters:
----------
width_scale : float
Scale factor for width of layers.
dws_simplified : bool, default False
Whether to use simplified depthwise separable convolution block.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
channels = [[32], [64], [128, 128], [256, 256], [512, 512, 512, 512, 512, 512], [1024, 1024]]
first_stage_stride = False
if width_scale != 1.0:
channels = [[int(cij * width_scale) for cij in ci] for ci in channels]
if dws_simplified:
dw_use_bn = False
dw_activation = None
else:
dw_use_bn = True
dw_activation = (lambda: nn.Activation("relu"))
net = MobileNet(
channels=channels,
first_stage_stride=first_stage_stride,
dw_use_bn=dw_use_bn,
dw_activation=dw_activation,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def mobilenet_w1(**kwargs):
"""
1.0 MobileNet-224 model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenet(width_scale=1.0, model_name="mobilenet_w1", **kwargs)
def mobilenet_w3d4(**kwargs):
"""
0.75 MobileNet-224 model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenet(width_scale=0.75, model_name="mobilenet_w3d4", **kwargs)
def mobilenet_wd2(**kwargs):
"""
0.5 MobileNet-224 model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenet(width_scale=0.5, model_name="mobilenet_wd2", **kwargs)
def mobilenet_wd4(**kwargs):
"""
0.25 MobileNet-224 model from 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenet(width_scale=0.25, model_name="mobilenet_wd4", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
mobilenet_w1,
mobilenet_w3d4,
mobilenet_wd2,
mobilenet_wd4,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != mobilenet_w1 or weight_count == 4231976)
assert (model != mobilenet_w3d4 or weight_count == 2585560)
assert (model != mobilenet_wd2 or weight_count == 1331592)
assert (model != mobilenet_wd4 or weight_count == 470072)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 9,265 | 34.098485 | 119 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/dpn.py | """
DPN for ImageNet-1K, implemented in Gluon.
Original paper: 'Dual Path Networks,' https://arxiv.org/abs/1707.01629.
"""
__all__ = ['DPN', 'dpn68', 'dpn68b', 'dpn98', 'dpn107', 'dpn131']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1, DualPathSequential
class GlobalAvgMaxPool2D(HybridBlock):
"""
Global average+max pooling operation for spatial data.
"""
def __init__(self,
**kwargs):
super(GlobalAvgMaxPool2D, self).__init__(**kwargs)
with self.name_scope():
self.avg_pool = nn.GlobalAvgPool2D()
self.max_pool = nn.GlobalMaxPool2D()
def hybrid_forward(self, F, x):
x_avg = self.avg_pool(x)
x_max = self.max_pool(x)
x = 0.5 * (x_avg + x_max)
return x
def dpn_batch_norm(channels):
"""
DPN specific Batch normalization layer.
Parameters:
----------
channels : int
Number of channels in input data.
"""
return nn.BatchNorm(
epsilon=0.001,
in_channels=channels)
class PreActivation(HybridBlock):
"""
DPN specific block, which performs the preactivation like in RreResNet.
Parameters:
----------
channels : int
Number of channels.
"""
def __init__(self,
channels,
**kwargs):
super(PreActivation, self).__init__(**kwargs)
with self.name_scope():
self.bn = dpn_batch_norm(channels=channels)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
x = self.bn(x)
x = self.activ(x)
return x
class DPNConv(HybridBlock):
"""
DPN specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
groups : int
Number of groups.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
groups,
**kwargs):
super(DPNConv, self).__init__(**kwargs)
with self.name_scope():
self.bn = dpn_batch_norm(channels=in_channels)
self.activ = nn.Activation("relu")
self.conv = nn.Conv2D(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
groups=groups,
use_bias=False,
in_channels=in_channels)
def hybrid_forward(self, F, x):
x = self.bn(x)
x = self.activ(x)
x = self.conv(x)
return x
def dpn_conv1x1(in_channels,
out_channels,
strides=1):
"""
1x1 version of the DPN specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
"""
return DPNConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
strides=strides,
padding=0,
groups=1)
def dpn_conv3x3(in_channels,
out_channels,
strides,
groups):
"""
3x3 version of the DPN specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
groups : int
Number of groups.
"""
return DPNConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
strides=strides,
padding=1,
groups=groups)
class DPNUnit(HybridBlock):
"""
DPN unit.
Parameters:
----------
in_channels : int
Number of input channels.
mid_channels : int
Number of intermediate channels.
bw : int
Number of residual channels.
inc : int
Incrementing step for channels.
groups : int
Number of groups in the units.
has_proj : bool
Whether to use projection.
key_strides : int
Key strides of the convolutions.
b_case : bool, default False
Whether to use B-case model.
"""
def __init__(self,
in_channels,
mid_channels,
bw,
inc,
groups,
has_proj,
key_strides,
b_case=False,
**kwargs):
super(DPNUnit, self).__init__(**kwargs)
self.bw = bw
self.has_proj = has_proj
self.b_case = b_case
with self.name_scope():
if self.has_proj:
self.conv_proj = dpn_conv1x1(
in_channels=in_channels,
out_channels=bw + 2 * inc,
strides=key_strides)
self.conv1 = dpn_conv1x1(
in_channels=in_channels,
out_channels=mid_channels)
self.conv2 = dpn_conv3x3(
in_channels=mid_channels,
out_channels=mid_channels,
strides=key_strides,
groups=groups)
if b_case:
self.preactiv = PreActivation(channels=mid_channels)
self.conv3a = conv1x1(
in_channels=mid_channels,
out_channels=bw)
self.conv3b = conv1x1(
in_channels=mid_channels,
out_channels=inc)
else:
self.conv3 = dpn_conv1x1(
in_channels=mid_channels,
out_channels=bw + inc)
def hybrid_forward(self, F, x1, x2=None):
x_in = F.concat(x1, x2, dim=1) if x2 is not None else x1
if self.has_proj:
x_s = self.conv_proj(x_in)
x_s1 = F.slice_axis(x_s, axis=1, begin=0, end=self.bw)
x_s2 = F.slice_axis(x_s, axis=1, begin=self.bw, end=None)
else:
assert (x2 is not None)
x_s1 = x1
x_s2 = x2
x_in = self.conv1(x_in)
x_in = self.conv2(x_in)
if self.b_case:
x_in = self.preactiv(x_in)
y1 = self.conv3a(x_in)
y2 = self.conv3b(x_in)
else:
x_in = self.conv3(x_in)
y1 = F.slice_axis(x_in, axis=1, begin=0, end=self.bw)
y2 = F.slice_axis(x_in, axis=1, begin=self.bw, end=None)
residual = x_s1 + y1
dense = F.concat(x_s2, y2, dim=1)
return residual, dense
class DPNInitBlock(HybridBlock):
"""
DPN specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
padding,
**kwargs):
super(DPNInitBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv = nn.Conv2D(
channels=out_channels,
kernel_size=kernel_size,
strides=2,
padding=padding,
use_bias=False,
in_channels=in_channels)
self.bn = dpn_batch_norm(channels=out_channels)
self.activ = nn.Activation("relu")
self.pool = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=1)
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.bn(x)
x = self.activ(x)
x = self.pool(x)
return x
class DPNFinalBlock(HybridBlock):
"""
DPN final block, which performs the preactivation with cutting.
Parameters:
----------
channels : int
Number of channels.
"""
def __init__(self,
channels,
**kwargs):
super(DPNFinalBlock, self).__init__(**kwargs)
with self.name_scope():
self.activ = PreActivation(channels=channels)
def hybrid_forward(self, F, x1, x2):
assert (x2 is not None)
x = F.concat(x1, x2, dim=1)
x = self.activ(x)
return x, None
class DPN(HybridBlock):
"""
DPN model from 'Dual Path Networks,' https://arxiv.org/abs/1707.01629.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
init_block_kernel_size : int or tuple/list of 2 int
Convolution window size for the initial unit.
init_block_padding : int or tuple/list of 2 int
Padding value for convolution layer in the initial unit.
rs : list f int
Number of intermediate channels for each unit.
bws : list f int
Number of residual channels for each unit.
incs : list f int
Incrementing step for channels for each unit.
groups : int
Number of groups in the units.
b_case : bool
Whether to use B-case model.
for_training : bool
Whether to use model for training.
test_time_pool : bool
Whether to use the avg-max pooling in the inference mode.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
init_block_kernel_size,
init_block_padding,
rs,
bws,
incs,
groups,
b_case,
for_training,
test_time_pool,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(DPN, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = DualPathSequential(
return_two=False,
first_ordinals=1,
last_ordinals=0,
prefix="")
self.features.add(DPNInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
kernel_size=init_block_kernel_size,
padding=init_block_padding))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = DualPathSequential(prefix="stage{}_".format(i + 1))
r = rs[i]
bw = bws[i]
inc = incs[i]
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
has_proj = (j == 0)
key_strides = 2 if (j == 0) and (i != 0) else 1
stage.add(DPNUnit(
in_channels=in_channels,
mid_channels=r,
bw=bw,
inc=inc,
groups=groups,
has_proj=has_proj,
key_strides=key_strides,
b_case=b_case))
in_channels = out_channels
self.features.add(stage)
self.features.add(DPNFinalBlock(channels=in_channels))
self.output = nn.HybridSequential(prefix="")
if for_training or not test_time_pool:
self.output.add(nn.GlobalAvgPool2D())
self.output.add(conv1x1(
in_channels=in_channels,
out_channels=classes,
use_bias=True))
self.output.add(nn.Flatten())
else:
self.output.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output.add(conv1x1(
in_channels=in_channels,
out_channels=classes,
use_bias=True))
self.output.add(GlobalAvgMaxPool2D())
self.output.add(nn.Flatten())
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_dpn(num_layers,
b_case=False,
for_training=False,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create DPN model with specific parameters.
Parameters:
----------
num_layers : int
Number of layers.
b_case : bool, default False
Whether to use B-case model.
for_training : bool
Whether to use model for training.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if num_layers == 68:
init_block_channels = 10
init_block_kernel_size = 3
init_block_padding = 1
bw_factor = 1
k_r = 128
groups = 32
k_sec = (3, 4, 12, 3)
incs = (16, 32, 32, 64)
test_time_pool = True
elif num_layers == 98:
init_block_channels = 96
init_block_kernel_size = 7
init_block_padding = 3
bw_factor = 4
k_r = 160
groups = 40
k_sec = (3, 6, 20, 3)
incs = (16, 32, 32, 128)
test_time_pool = True
elif num_layers == 107:
init_block_channels = 128
init_block_kernel_size = 7
init_block_padding = 3
bw_factor = 4
k_r = 200
groups = 50
k_sec = (4, 8, 20, 3)
incs = (20, 64, 64, 128)
test_time_pool = True
elif num_layers == 131:
init_block_channels = 128
init_block_kernel_size = 7
init_block_padding = 3
bw_factor = 4
k_r = 160
groups = 40
k_sec = (4, 8, 28, 3)
incs = (16, 32, 32, 128)
test_time_pool = True
else:
raise ValueError("Unsupported DPN version with number of layers {}".format(num_layers))
channels = [[0] * li for li in k_sec]
rs = [0 * li for li in k_sec]
bws = [0 * li for li in k_sec]
for i in range(len(k_sec)):
rs[i] = (2 ** i) * k_r
bws[i] = (2 ** i) * 64 * bw_factor
inc = incs[i]
channels[i][0] = bws[i] + 3 * inc
for j in range(1, k_sec[i]):
channels[i][j] = channels[i][j - 1] + inc
net = DPN(
channels=channels,
init_block_channels=init_block_channels,
init_block_kernel_size=init_block_kernel_size,
init_block_padding=init_block_padding,
rs=rs,
bws=bws,
incs=incs,
groups=groups,
b_case=b_case,
for_training=for_training,
test_time_pool=test_time_pool,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def dpn68(**kwargs):
"""
DPN-68 model from 'Dual Path Networks,' https://arxiv.org/abs/1707.01629.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_dpn(num_layers=68, b_case=False, model_name="dpn68", **kwargs)
def dpn68b(**kwargs):
"""
DPN-68b model from 'Dual Path Networks,' https://arxiv.org/abs/1707.01629.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_dpn(num_layers=68, b_case=True, model_name="dpn68b", **kwargs)
def dpn98(**kwargs):
"""
DPN-98 model from 'Dual Path Networks,' https://arxiv.org/abs/1707.01629.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_dpn(num_layers=98, b_case=False, model_name="dpn98", **kwargs)
def dpn107(**kwargs):
"""
DPN-107 model from 'Dual Path Networks,' https://arxiv.org/abs/1707.01629.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_dpn(num_layers=107, b_case=False, model_name="dpn107", **kwargs)
def dpn131(**kwargs):
"""
DPN-131 model from 'Dual Path Networks,' https://arxiv.org/abs/1707.01629.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_dpn(num_layers=131, b_case=False, model_name="dpn131", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
for_training = False
models = [
dpn68,
# dpn68b,
dpn98,
# dpn107,
dpn131,
]
for model in models:
net = model(pretrained=pretrained, for_training=for_training)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != dpn68 or weight_count == 12611602)
assert (model != dpn68b or weight_count == 12611602)
assert (model != dpn98 or weight_count == 61570728)
assert (model != dpn107 or weight_count == 86917800)
assert (model != dpn131 or weight_count == 79254504)
# net.hybridize()
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 20,220 | 28.957037 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/sknet.py | """
SKNet for ImageNet-1K, implemented in Gluon.
Original paper: 'Selective Kernel Networks,' https://arxiv.org/abs/1903.06586.
"""
__all__ = ['SKNet', 'sknet50', 'sknet101', 'sknet152']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1, conv1x1_block, conv3x3_block, Concurrent
from .resnet import ResInitBlock
class SKConvBlock(HybridBlock):
"""
SKNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
groups : int, default 32
Number of groups in branches.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
num_branches : int, default 2
Number of branches (`M` parameter in the paper).
reduction : int, default 16
Reduction value for intermediate channels (`r` parameter in the paper).
min_channels : int, default 32
Minimal number of intermediate channels (`L` parameter in the paper).
"""
def __init__(self,
in_channels,
out_channels,
strides,
groups=32,
bn_use_global_stats=False,
num_branches=2,
reduction=16,
min_channels=32,
**kwargs):
super(SKConvBlock, self).__init__(**kwargs)
self.num_branches = num_branches
self.out_channels = out_channels
mid_channels = max(in_channels // reduction, min_channels)
with self.name_scope():
self.branches = Concurrent(stack=True, prefix="")
for i in range(num_branches):
dilation = 1 + i
self.branches.add(conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
padding=dilation,
dilation=dilation,
groups=groups,
bn_use_global_stats=bn_use_global_stats))
self.fc1 = conv1x1_block(
in_channels=out_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats)
self.fc2 = conv1x1(
in_channels=mid_channels,
out_channels=(out_channels * num_branches))
def hybrid_forward(self, F, x):
y = self.branches(x)
u = y.sum(axis=1)
s = F.contrib.AdaptiveAvgPooling2D(u, output_size=1)
z = self.fc1(s)
w = self.fc2(z)
w = w.reshape((0, self.num_branches, self.out_channels))
w = F.softmax(w, axis=1)
w = w.expand_dims(3).expand_dims(4)
y = F.broadcast_mul(y, w)
y = y.sum(axis=1)
return y
class SKNetBottleneck(HybridBlock):
"""
SKNet bottleneck block for residual path in SKNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bottleneck_factor : int, default 2
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats=False,
bottleneck_factor=2,
**kwargs):
super(SKNetBottleneck, self).__init__(**kwargs)
mid_channels = out_channels // bottleneck_factor
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = SKConvBlock(
in_channels=mid_channels,
out_channels=mid_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation=None)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class SKNetUnit(HybridBlock):
"""
SKNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats=False,
**kwargs):
super(SKNetUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
self.body = SKNetBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
activation=None)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class SKNet(HybridBlock):
"""
SKNet model from 'Selective Kernel Networks,' https://arxiv.org/abs/1903.06586.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(SKNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
stage.add(SKNetUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_sknet(blocks,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create SKNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
else:
raise ValueError("Unsupported SKNet with number of blocks: {}".format(blocks))
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = SKNet(
channels=channels,
init_block_channels=init_block_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def sknet50(**kwargs):
"""
SKNet-50 model from 'Selective Kernel Networks,' https://arxiv.org/abs/1903.06586.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sknet(blocks=50, model_name="sknet50", **kwargs)
def sknet101(**kwargs):
"""
SKNet-101 model from 'Selective Kernel Networks,' https://arxiv.org/abs/1903.06586.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sknet(blocks=101, model_name="sknet101", **kwargs)
def sknet152(**kwargs):
"""
SKNet-152 model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_sknet(blocks=152, model_name="sknet152", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
sknet50,
sknet101,
sknet152,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != sknet50 or weight_count == 27479784)
assert (model != sknet101 or weight_count == 48736040)
assert (model != sknet152 or weight_count == 66295656)
x = mx.nd.zeros((14, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (14, 1000))
if __name__ == "__main__":
_test()
| 12,972 | 31.595477 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/spnasnet.py | """
Single-Path NASNet for ImageNet-1K, implemented in Gluon.
Original paper: 'Single-Path NAS: Designing Hardware-Efficient ConvNets in less than 4 Hours,'
https://arxiv.org/abs/1904.02877.
"""
__all__ = ['SPNASNet', 'spnasnet']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv5x5_block
class SPNASUnit(HybridBlock):
"""
Single-Path NASNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the second convolution layer.
use_kernel3 : bool
Whether to use 3x3 (instead of 5x5) kernel.
exp_factor : int
Expansion factor for each unit.
use_skip : bool, default True
Whether to use skip connection.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
activation : str, default 'relu'
Activation function or name of activation function.
"""
def __init__(self,
in_channels,
out_channels,
strides,
use_kernel3,
exp_factor,
use_skip=True,
bn_use_global_stats=False,
activation="relu",
**kwargs):
super(SPNASUnit, self).__init__(**kwargs)
assert (exp_factor >= 1)
self.residual = (in_channels == out_channels) and (strides == 1) and use_skip
self.use_exp_conv = exp_factor > 1
mid_channels = exp_factor * in_channels
with self.name_scope():
if self.use_exp_conv:
self.exp_conv = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats,
activation=activation)
if use_kernel3:
self.conv1 = dwconv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
activation=activation)
else:
self.conv1 = dwconv5x5_block(
in_channels=mid_channels,
out_channels=mid_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
activation=activation)
self.conv2 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation=None)
def hybrid_forward(self, F, x):
if self.residual:
identity = x
if self.use_exp_conv:
x = self.exp_conv(x)
x = self.conv1(x)
x = self.conv2(x)
if self.residual:
x = x + identity
return x
class SPNASInitBlock(HybridBlock):
"""
Single-Path NASNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of middle channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels,
bn_use_global_stats=False,
**kwargs):
super(SPNASInitBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels,
strides=2,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = SPNASUnit(
in_channels=mid_channels,
out_channels=out_channels,
strides=1,
use_kernel3=True,
exp_factor=1,
use_skip=False,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class SPNASFinalBlock(HybridBlock):
"""
Single-Path NASNet specific final block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of middle channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels,
bn_use_global_stats=False,
**kwargs):
super(SPNASFinalBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = SPNASUnit(
in_channels=in_channels,
out_channels=mid_channels,
strides=1,
use_kernel3=True,
exp_factor=6,
use_skip=False,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class SPNASNet(HybridBlock):
"""
Single-Path NASNet model from 'Single-Path NAS: Designing Hardware-Efficient ConvNets in less than 4 Hours,'
https://arxiv.org/abs/1904.02877.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : list of 2 int
Number of output channels for the initial unit.
final_block_channels : list of 2 int
Number of output channels for the final block of the feature extractor.
kernels3 : list of list of int/bool
Using 3x3 (instead of 5x5) kernel for each unit.
exp_factors : list of list of int
Expansion factor for each unit.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
kernels3,
exp_factors,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(SPNASNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(SPNASInitBlock(
in_channels=in_channels,
out_channels=init_block_channels[1],
mid_channels=init_block_channels[0],
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels[1]
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if ((j == 0) and (i != 3)) or\
((j == len(channels_per_stage) // 2) and (i == 3)) else 1
use_kernel3 = kernels3[i][j] == 1
exp_factor = exp_factors[i][j]
stage.add(SPNASUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
use_kernel3=use_kernel3,
exp_factor=exp_factor,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(SPNASFinalBlock(
in_channels=in_channels,
out_channels=final_block_channels[1],
mid_channels=final_block_channels[0],
bn_use_global_stats=bn_use_global_stats))
in_channels = final_block_channels[1]
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_spnasnet(model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create Single-Path NASNet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
init_block_channels = [32, 16]
final_block_channels = [320, 1280]
channels = [[24, 24, 24], [40, 40, 40, 40], [80, 80, 80, 80], [96, 96, 96, 96, 192, 192, 192, 192]]
kernels3 = [[1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0]]
exp_factors = [[3, 3, 3], [6, 3, 3, 3], [6, 3, 3, 3], [6, 3, 3, 3, 6, 6, 6, 6]]
net = SPNASNet(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
kernels3=kernels3,
exp_factors=exp_factors,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def spnasnet(**kwargs):
"""
Single-Path NASNet model from 'Single-Path NAS: Designing Hardware-Efficient ConvNets in less than 4 Hours,'
https://arxiv.org/abs/1904.02877.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_spnasnet(model_name="spnasnet", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
spnasnet,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != spnasnet or weight_count == 4421616)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 12,626 | 33.405995 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/fastscnn.py | """
Fast-SCNN for image segmentation, implemented in Gluon.
Original paper: 'Fast-SCNN: Fast Semantic Segmentation Network,' https://arxiv.org/abs/1902.04502.
"""
__all__ = ['FastSCNN', 'fastscnn_cityscapes']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from mxnet.gluon.contrib.nn import Identity
from .common import conv1x1, conv1x1_block, conv3x3_block, dwconv3x3_block, dwsconv3x3_block, Concurrent,\
InterpolationBlock
class Stem(HybridBlock):
"""
Fast-SCNN specific stem block.
Parameters:
----------
in_channels : int
Number of input channels.
channels : tuple/list of 3 int
Number of output channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
channels,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(Stem, self).__init__(**kwargs)
assert (len(channels) == 3)
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=channels[0],
strides=2,
padding=0,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.conv2 = dwsconv3x3_block(
in_channels=channels[0],
out_channels=channels[1],
strides=2,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.conv3 = dwsconv3x3_block(
in_channels=channels[1],
out_channels=channels[2],
strides=2,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class LinearBottleneck(HybridBlock):
"""
Fast-SCNN specific Linear Bottleneck layer from MobileNetV2.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the second convolution layer.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
strides,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(LinearBottleneck, self).__init__(**kwargs)
self.residual = (in_channels == out_channels) and (strides == 1)
mid_channels = in_channels * 6
with self.name_scope():
self.conv1 = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.conv2 = dwconv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.conv3 = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=None)
def hybrid_forward(self, F, x):
if self.residual:
identity = x
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
if self.residual:
x = x + identity
return x
class FeatureExtractor(HybridBlock):
"""
Fast-SCNN specific feature extractor/encoder.
Parameters:
----------
in_channels : int
Number of input channels.
channels : list of list of int
Number of output channels for each unit.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
channels,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(FeatureExtractor, self).__init__(**kwargs)
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != len(channels) - 1) else 1
stage.add(LinearBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
in_channels = out_channels
self.features.add(stage)
def hybrid_forward(self, F, x):
x = self.features(x)
return x
class PoolingBranch(HybridBlock):
"""
Fast-SCNN specific pooling branch.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
in_size : tuple of 2 int or None
Spatial size of input image.
down_size : int
Spatial size of downscaled image.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
in_size,
down_size,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(PoolingBranch, self).__init__(**kwargs)
self.in_size = in_size
self.down_size = down_size
with self.name_scope():
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.up = InterpolationBlock(
scale_factor=None,
out_size=in_size)
def hybrid_forward(self, F, x):
in_size = self.in_size if self.in_size is not None else x.shape[2:]
x = F.contrib.AdaptiveAvgPooling2D(x, output_size=self.down_size)
x = self.conv(x)
x = self.up(x, in_size)
return x
class FastPyramidPooling(HybridBlock):
"""
Fast-SCNN specific fast pyramid pooling block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
in_size : tuple of 2 int or None
Spatial size of input image.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
in_size,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(FastPyramidPooling, self).__init__(**kwargs)
down_sizes = [1, 2, 3, 6]
mid_channels = in_channels // 4
with self.name_scope():
self.branches = Concurrent()
self.branches.add(Identity())
for down_size in down_sizes:
self.branches.add(PoolingBranch(
in_channels=in_channels,
out_channels=mid_channels,
in_size=in_size,
down_size=down_size,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
self.conv = conv1x1_block(
in_channels=(in_channels * 2),
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
def hybrid_forward(self, F, x):
x = self.branches(x)
x = self.conv(x)
return x
class FeatureFusion(HybridBlock):
"""
Fast-SCNN specific feature fusion block.
Parameters:
----------
x_in_channels : int
Number of high resolution (x) input channels.
y_in_channels : int
Number of low resolution (y) input channels.
out_channels : int
Number of output channels.
x_in_size : tuple of 2 int or None
Spatial size of high resolution (x) input image.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
x_in_channels,
y_in_channels,
out_channels,
x_in_size,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(FeatureFusion, self).__init__(**kwargs)
self.x_in_size = x_in_size
with self.name_scope():
self.up = InterpolationBlock(
scale_factor=None,
out_size=x_in_size)
self.low_dw_conv = dwconv3x3_block(
in_channels=y_in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.low_pw_conv = conv1x1_block(
in_channels=out_channels,
out_channels=out_channels,
use_bias=True,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=None)
self.high_conv = conv1x1_block(
in_channels=x_in_channels,
out_channels=out_channels,
use_bias=True,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=None)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x, y):
x_in_size = self.x_in_size if self.x_in_size is not None else x.shape[2:]
y = self.up(y, x_in_size)
y = self.low_dw_conv(y)
y = self.low_pw_conv(y)
x = self.high_conv(x)
out = x + y
return self.activ(out)
class Head(HybridBlock):
"""
Fast-SCNN head (classifier) block.
Parameters:
----------
in_channels : int
Number of input channels.
classes : int
Number of classification classes.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
classes,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(Head, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = dwsconv3x3_block(
in_channels=in_channels,
out_channels=in_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.conv2 = dwsconv3x3_block(
in_channels=in_channels,
out_channels=in_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.dropout = nn.Dropout(rate=0.1)
self.conv3 = conv1x1(
in_channels=in_channels,
out_channels=classes,
use_bias=True)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.dropout(x)
x = self.conv3(x)
return x
class AuxHead(HybridBlock):
"""
Fast-SCNN auxiliary (after stem) head (classifier) block.
Parameters:
----------
in_channels : int
Number of input channels.
mid_channels : int
Number of middle channels.
classes : int
Number of classification classes.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
mid_channels,
classes,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(AuxHead, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.dropout = nn.Dropout(rate=0.1)
self.conv2 = conv1x1(
in_channels=mid_channels,
out_channels=classes,
use_bias=True)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.dropout(x)
x = self.conv2(x)
return x
class FastSCNN(HybridBlock):
"""
Fast-SCNN from 'Fast-SCNN: Fast Semantic Segmentation Network,' https://arxiv.org/abs/1902.04502.
Parameters:
----------
aux : bool, default False
Whether to output an auxiliary result.
fixed_size : bool, default True
Whether to expect fixed spatial size of input image.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (1024, 1024)
Spatial size of the expected input image.
classes : int, default 19
Number of segmentation classes.
"""
def __init__(self,
aux=False,
fixed_size=True,
bn_use_global_stats=False,
bn_cudnn_off=False,
in_channels=3,
in_size=(1024, 1024),
classes=19,
**kwargs):
super(FastSCNN, self).__init__(**kwargs)
assert (in_channels > 0)
assert ((in_size[0] % 32 == 0) and (in_size[1] % 32 == 0))
self.in_size = in_size
self.classes = classes
self.aux = aux
self.fixed_size = fixed_size
with self.name_scope():
steam_channels = [32, 48, 64]
self.stem = Stem(
in_channels=in_channels,
channels=steam_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
in_channels = steam_channels[-1]
feature_channels = [[64, 64, 64], [96, 96, 96], [128, 128, 128]]
self.features = FeatureExtractor(
in_channels=in_channels,
channels=feature_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
pool_out_size = (in_size[0] // 32, in_size[1] // 32) if fixed_size else None
self.pool = FastPyramidPooling(
in_channels=feature_channels[-1][-1],
out_channels=feature_channels[-1][-1],
in_size=pool_out_size,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
fusion_out_size = (in_size[0] // 8, in_size[1] // 8) if fixed_size else None
fusion_out_channels = 128
self.fusion = FeatureFusion(
x_in_channels=steam_channels[-1],
y_in_channels=feature_channels[-1][-1],
out_channels=fusion_out_channels,
x_in_size=fusion_out_size,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.head = Head(
in_channels=fusion_out_channels,
classes=classes,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.up = InterpolationBlock(
scale_factor=None,
out_size=in_size)
if self.aux:
self.aux_head = AuxHead(
in_channels=64,
mid_channels=64,
classes=classes,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
def hybrid_forward(self, F, x):
in_size = self.in_size if self.fixed_size else x.shape[2:]
x = self.stem(x)
y = self.features(x)
y = self.pool(y)
y = self.fusion(x, y)
y = self.head(y)
y = self.up(y, in_size)
if self.aux:
x = self.aux_head(x)
x = self.up(x, in_size)
return y, x
return y
def get_fastscnn(model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create Fast-SCNN model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
net = FastSCNN(
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx,
ignore_extra=True)
return net
def fastscnn_cityscapes(classes=19, aux=True, **kwargs):
"""
Fast-SCNN model for Cityscapes from 'Fast-SCNN: Fast Semantic Segmentation Network,'
https://arxiv.org/abs/1902.04502.
Parameters:
----------
classes : int, default 19
Number of segmentation classes.
aux : bool, default True
Whether to output an auxiliary result.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_fastscnn(classes=classes, aux=aux, model_name="fastscnn_cityscapes", **kwargs)
def _test():
import numpy as np
import mxnet as mx
# in_size = (1024, 1024)
in_size = (1024, 2048)
aux = True
pretrained = False
fixed_size = False
models = [
(fastscnn_cityscapes, 19),
]
for model, classes in models:
net = model(pretrained=pretrained, in_size=in_size, fixed_size=fixed_size, aux=aux)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
if aux:
assert (model != fastscnn_cityscapes or weight_count == 1176278)
else:
assert (model != fastscnn_cityscapes or weight_count == 1138051)
x = mx.nd.zeros((1, 3, in_size[0], in_size[1]), ctx=ctx)
ys = net(x)
y = ys[0] if aux else ys
assert ((y.shape[0] == x.shape[0]) and (y.shape[1] == classes) and (y.shape[2] == x.shape[2]) and
(y.shape[3] == x.shape[3]))
if __name__ == "__main__":
_test()
| 21,678 | 33.520701 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/res2net.py | """
Res2Net for ImageNet-1K, implemented in Gluon.
Original paper: 'Res2Net: A New Multi-scale Backbone Architecture,' https://arxiv.org/abs/1904.01169.
"""
__all__ = ['Res2Net', 'res2net50_w14_s8', 'res2net50_w26_s8']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from mxnet.gluon.contrib.nn import Identity
from .common import conv1x1, conv3x3, conv1x1_block
from .resnet import ResInitBlock
from .preresnet import PreResActivation
class HierarchicalConcurrent(nn.HybridSequential):
"""
A container for hierarchical concatenation of blocks with parameters.
Parameters:
----------
axis : int, default 1
The axis on which to concatenate the outputs.
multi_input : bool, default False
Whether input is multiple.
"""
def __init__(self,
axis=1,
multi_input=False,
**kwargs):
super(HierarchicalConcurrent, self).__init__(**kwargs)
self.axis = axis
self.multi_input = multi_input
def hybrid_forward(self, F, x):
out = []
y_prev = None
if self.multi_input:
xs = F.split(x, axis=self.axis, num_outputs=len(self._children.values()))
for i, block in enumerate(self._children.values()):
if self.multi_input:
y = block(xs[i])
else:
y = block(x)
if y_prev is not None:
y = y + y_prev
out.append(y)
y_prev = y
out = F.concat(*out, dim=self.axis)
return out
class Res2NetUnit(HybridBlock):
"""
Res2Net unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the branch convolution layers.
width : int
Width of filters.
scale : int
Number of scale.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
width,
scale,
bn_use_global_stats,
**kwargs):
super(Res2NetUnit, self).__init__(**kwargs)
self.scale = scale
downsample = (strides != 1)
self.resize_identity = (in_channels != out_channels) or downsample
mid_channels = width * scale
brn_channels = width
with self.name_scope():
self.reduce_conv = conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats)
self.branches = HierarchicalConcurrent(axis=1, multi_input=True, prefix="")
if downsample:
self.branches.add(conv1x1(
in_channels=brn_channels,
out_channels=brn_channels,
strides=strides))
else:
self.branches.add(Identity())
for i in range(scale - 1):
self.branches.add(conv3x3(
in_channels=brn_channels,
out_channels=brn_channels,
strides=strides))
self.preactiv = PreResActivation(in_channels=mid_channels)
self.merge_conv = conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation=None)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
bn_use_global_stats=bn_use_global_stats,
activation=None)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
y = self.reduce_conv(x)
y = self.branches(y)
y = self.preactiv(y)
y = self.merge_conv(y)
y = y + identity
y = self.activ(y)
return y
class Res2Net(HybridBlock):
"""
Res2Net model from 'Res2Net: A New Multi-scale Backbone Architecture,' https://arxiv.org/abs/1904.01169.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
width : int
Width of filters.
scale : int
Number of scale.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
width,
scale,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(Res2Net, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
stage.add(Res2NetUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
width=width,
scale=scale,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_res2net(blocks,
width,
scale,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create Res2Net model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
width : int
Width of filters.
scale : int
Number of scale.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
bottleneck = True
if blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
else:
raise ValueError("Unsupported Res2Net with number of blocks: {}".format(blocks))
assert (sum(layers) * 3 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [64, 128, 256, 512]
if bottleneck:
bottleneck_factor = 4
channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = Res2Net(
channels=channels,
init_block_channels=init_block_channels,
width=width,
scale=scale,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def res2net50_w14_s8(**kwargs):
"""
Res2Net-50 (14wx8s) model from 'Res2Net: A New Multi-scale Backbone Architecture,' https://arxiv.org/abs/1904.01169.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_res2net(blocks=50, width=14, scale=8, model_name="res2net50_w14_s8", **kwargs)
def res2net50_w26_s8(**kwargs):
"""
Res2Net-50 (26wx8s) model from 'Res2Net: A New Multi-scale Backbone Architecture,' https://arxiv.org/abs/1904.01169.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_res2net(blocks=50, width=26, scale=8, model_name="res2net50_w14_s8", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
res2net50_w14_s8,
res2net50_w26_s8,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != res2net50_w14_s8 or weight_count == 8231732)
assert (model != res2net50_w26_s8 or weight_count == 11432660)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 11,307 | 31.401146 | 120 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/darknet.py | """
DarkNet for ImageNet-1K, implemented in Gluon.
Original source: 'Darknet: Open source neural networks in c,' https://github.com/pjreddie/darknet.
"""
__all__ = ['DarkNet', 'darknet_ref', 'darknet_tiny', 'darknet19']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block, conv3x3_block
def dark_convYxY(in_channels,
out_channels,
bn_use_global_stats,
alpha,
pointwise):
"""
DarkNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
alpha : float
Slope coefficient for Leaky ReLU activation.
pointwise : bool
Whether use 1x1 (pointwise) convolution or 3x3 convolution.
"""
if pointwise:
return conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation=nn.LeakyReLU(alpha=alpha))
else:
return conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation=nn.LeakyReLU(alpha=alpha))
class DarkNet(HybridBlock):
"""
DarkNet model from 'Darknet: Open source neural networks in c,' https://github.com/pjreddie/darknet.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
odd_pointwise : bool
Whether pointwise convolution layer is used for each odd unit.
avg_pool_size : int
Window size of the final average pooling.
cls_activ : bool
Whether classification convolution layer uses an activation.
alpha : float, default 0.1
Slope coefficient for Leaky ReLU activation.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
odd_pointwise,
avg_pool_size,
cls_activ,
alpha=0.1,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(DarkNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
stage.add(dark_convYxY(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
alpha=alpha,
pointwise=(len(channels_per_stage) > 1) and not(((j + 1) % 2 == 1) ^ odd_pointwise)))
in_channels = out_channels
if i != len(channels) - 1:
stage.add(nn.MaxPool2D(
pool_size=2,
strides=2))
self.features.add(stage)
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Conv2D(
channels=classes,
kernel_size=1,
in_channels=in_channels))
if cls_activ:
self.output.add(nn.LeakyReLU(alpha=alpha))
self.output.add(nn.AvgPool2D(
pool_size=avg_pool_size,
strides=1))
self.output.add(nn.Flatten())
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_darknet(version,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create DarkNet model with specific parameters.
Parameters:
----------
version : str
Version of SqueezeNet ('ref', 'tiny' or '19').
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if version == 'ref':
channels = [[16], [32], [64], [128], [256], [512], [1024]]
odd_pointwise = False
avg_pool_size = 3
cls_activ = True
elif version == 'tiny':
channels = [[16], [32], [16, 128, 16, 128], [32, 256, 32, 256], [64, 512, 64, 512, 128]]
odd_pointwise = True
avg_pool_size = 14
cls_activ = False
elif version == '19':
channels = [[32], [64], [128, 64, 128], [256, 128, 256], [512, 256, 512, 256, 512],
[1024, 512, 1024, 512, 1024]]
odd_pointwise = False
avg_pool_size = 7
cls_activ = False
else:
raise ValueError("Unsupported DarkNet version {}".format(version))
net = DarkNet(
channels=channels,
odd_pointwise=odd_pointwise,
avg_pool_size=avg_pool_size,
cls_activ=cls_activ,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def darknet_ref(**kwargs):
"""
DarkNet 'Reference' model from 'Darknet: Open source neural networks in c,' https://github.com/pjreddie/darknet.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_darknet(version="ref", model_name="darknet_ref", **kwargs)
def darknet_tiny(**kwargs):
"""
DarkNet Tiny model from 'Darknet: Open source neural networks in c,' https://github.com/pjreddie/darknet.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_darknet(version="tiny", model_name="darknet_tiny", **kwargs)
def darknet19(**kwargs):
"""
DarkNet-19 model from 'Darknet: Open source neural networks in c,' https://github.com/pjreddie/darknet.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_darknet(version="19", model_name="darknet19", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
darknet_ref,
darknet_tiny,
darknet19,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != darknet_ref or weight_count == 7319416)
assert (model != darknet_tiny or weight_count == 1042104)
assert (model != darknet19 or weight_count == 20842376)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 9,154 | 32.17029 | 116 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/ror_cifar.py | """
RoR-3 for CIFAR/SVHN, implemented in Gluon.
Original paper: 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
"""
__all__ = ['CIFARRoR', 'ror3_56_cifar10', 'ror3_56_cifar100', 'ror3_56_svhn', 'ror3_110_cifar10', 'ror3_110_cifar100',
'ror3_110_svhn', 'ror3_164_cifar10', 'ror3_164_cifar100', 'ror3_164_svhn']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1_block, conv3x3_block
class RoRBlock(HybridBlock):
"""
RoR-3 block for residual path in residual unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats,
dropout_rate,
**kwargs):
super(RoRBlock, self).__init__(**kwargs)
self.use_dropout = (dropout_rate != 0.0)
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation=None)
if self.use_dropout:
self.dropout = nn.Dropout(rate=dropout_rate)
def hybrid_forward(self, F, x):
x = self.conv1(x)
if self.use_dropout:
x = self.dropout(x)
x = self.conv2(x)
return x
class RoRResUnit(HybridBlock):
"""
RoR-3 residual unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
last_activate : bool, default True
Whether activate output.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats,
dropout_rate,
last_activate=True,
**kwargs):
super(RoRResUnit, self).__init__(**kwargs)
self.last_activate = last_activate
self.resize_identity = (in_channels != out_channels)
with self.name_scope():
self.body = RoRBlock(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
dropout_rate=dropout_rate)
if self.resize_identity:
self.identity_conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
activation=None)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
if self.last_activate:
x = self.activ(x)
return x
class RoRResStage(HybridBlock):
"""
RoR-3 residual stage.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of int
Number of output channels for each unit.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
downsample : bool, default True
Whether downsample output.
"""
def __init__(self,
in_channels,
out_channels_list,
bn_use_global_stats,
dropout_rate,
downsample=True,
**kwargs):
super(RoRResStage, self).__init__(**kwargs)
self.downsample = downsample
with self.name_scope():
self.shortcut = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels_list[-1],
bn_use_global_stats=bn_use_global_stats,
activation=None)
self.units = nn.HybridSequential(prefix="")
with self.units.name_scope():
for i, out_channels in enumerate(out_channels_list):
last_activate = (i != len(out_channels_list) - 1)
self.units.add(RoRResUnit(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
dropout_rate=dropout_rate,
last_activate=last_activate))
in_channels = out_channels
if self.downsample:
self.activ = nn.Activation("relu")
self.pool = nn.MaxPool2D(
pool_size=2,
strides=2,
padding=0)
def hybrid_forward(self, F, x):
identity = self.shortcut(x)
x = self.units(x)
x = x + identity
if self.downsample:
x = self.activ(x)
x = self.pool(x)
return x
class RoRResBody(HybridBlock):
"""
RoR-3 residual body (main feature path).
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_lists : list of list of int
Number of output channels for each stage.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_channels,
out_channels_lists,
bn_use_global_stats,
dropout_rate,
**kwargs):
super(RoRResBody, self).__init__(**kwargs)
with self.name_scope():
self.shortcut = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels_lists[-1][-1],
strides=4,
bn_use_global_stats=bn_use_global_stats,
activation=None)
self.stages = nn.HybridSequential(prefix="")
with self.stages.name_scope():
for i, channels_per_stage in enumerate(out_channels_lists):
downsample = (i != len(out_channels_lists) - 1)
self.stages.add(RoRResStage(
in_channels=in_channels,
out_channels_list=channels_per_stage,
bn_use_global_stats=bn_use_global_stats,
dropout_rate=dropout_rate,
downsample=downsample))
in_channels = channels_per_stage[-1]
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
identity = self.shortcut(x)
x = self.stages(x)
x = x + identity
x = self.activ(x)
return x
class CIFARRoR(HybridBlock):
"""
RoR-3 model for CIFAR from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
dropout_rate : float, default 0.0
Parameter of Dropout layer. Faction of the input units to drop.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (32, 32)
Spatial size of the expected input image.
classes : int, default 10
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bn_use_global_stats=False,
dropout_rate=0.0,
in_channels=3,
in_size=(32, 32),
classes=10,
**kwargs):
super(CIFARRoR, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(conv3x3_block(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
self.features.add(RoRResBody(
in_channels=in_channels,
out_channels_lists=channels,
bn_use_global_stats=bn_use_global_stats,
dropout_rate=dropout_rate))
in_channels = channels[-1][-1]
self.features.add(nn.AvgPool2D(
pool_size=8,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_ror_cifar(classes,
blocks,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create RoR-3 model for CIFAR with specific parameters.
Parameters:
----------
classes : int
Number of classification classes.
blocks : int
Number of blocks.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
assert (classes in [10, 100])
assert ((blocks - 8) % 6 == 0)
layers = [(blocks - 8) // 6] * 3
channels_per_layers = [16, 32, 64]
init_block_channels = 16
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = CIFARRoR(
channels=channels,
init_block_channels=init_block_channels,
classes=classes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def ror3_56_cifar10(classes=10, **kwargs):
"""
RoR-3-56 model for CIFAR-10 from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(classes=classes, blocks=56, model_name="ror3_56_cifar10", **kwargs)
def ror3_56_cifar100(classes=100, **kwargs):
"""
RoR-3-56 model for CIFAR-100 from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(classes=classes, blocks=56, model_name="ror3_56_cifar100", **kwargs)
def ror3_56_svhn(classes=10, **kwargs):
"""
RoR-3-56 model for SVHN from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(classes=classes, blocks=56, model_name="ror3_56_svhn", **kwargs)
def ror3_110_cifar10(classes=10, **kwargs):
"""
RoR-3-110 model for CIFAR-10 from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(classes=classes, blocks=110, model_name="ror3_110_cifar10", **kwargs)
def ror3_110_cifar100(classes=100, **kwargs):
"""
RoR-3-110 model for CIFAR-100 from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(classes=classes, blocks=110, model_name="ror3_110_cifar100", **kwargs)
def ror3_110_svhn(classes=10, **kwargs):
"""
RoR-3-110 model for SVHN from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(classes=classes, blocks=110, model_name="ror3_110_svhn", **kwargs)
def ror3_164_cifar10(classes=10, **kwargs):
"""
RoR-3-164 model for CIFAR-10 from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(classes=classes, blocks=164, model_name="ror3_164_cifar10", **kwargs)
def ror3_164_cifar100(classes=100, **kwargs):
"""
RoR-3-164 model for CIFAR-100 from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
classes : int, default 100
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(classes=classes, blocks=164, model_name="ror3_164_cifar100", **kwargs)
def ror3_164_svhn(classes=10, **kwargs):
"""
RoR-3-164 model for SVHN from 'Residual Networks of Residual Networks: Multilevel Residual Networks,'
https://arxiv.org/abs/1608.02908.
Parameters:
----------
classes : int, default 10
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_ror_cifar(classes=classes, blocks=164, model_name="ror3_164_svhn", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
(ror3_56_cifar10, 10),
(ror3_56_cifar100, 100),
(ror3_56_svhn, 10),
(ror3_110_cifar10, 10),
(ror3_110_cifar100, 100),
(ror3_110_svhn, 10),
(ror3_164_cifar10, 10),
(ror3_164_cifar100, 100),
(ror3_164_svhn, 10),
]
for model, classes in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != ror3_56_cifar10 or weight_count == 762746)
assert (model != ror3_56_cifar100 or weight_count == 768596)
assert (model != ror3_56_svhn or weight_count == 762746)
assert (model != ror3_110_cifar10 or weight_count == 1637690)
assert (model != ror3_110_cifar100 or weight_count == 1643540)
assert (model != ror3_110_svhn or weight_count == 1637690)
assert (model != ror3_164_cifar10 or weight_count == 2512634)
assert (model != ror3_164_cifar100 or weight_count == 2518484)
assert (model != ror3_164_svhn or weight_count == 2512634)
x = mx.nd.zeros((1, 3, 32, 32), ctx=ctx)
y = net(x)
assert (y.shape == (1, classes))
if __name__ == "__main__":
_test()
| 19,573 | 33.522046 | 118 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/dicenet.py | """
DiCENet for ImageNet-1K, implemented in Gluon.
Original paper: 'DiCENet: Dimension-wise Convolutions for Efficient Networks,' https://arxiv.org/abs/1906.03516.
"""
__all__ = ['DiceNet', 'dicenet_wd5', 'dicenet_wd2', 'dicenet_w3d4', 'dicenet_w1', 'dicenet_w5d4', 'dicenet_w3d2',
'dicenet_w7d8', 'dicenet_w2']
import os
import math
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import conv1x1, conv3x3, conv1x1_block, conv3x3_block, NormActivation, ChannelShuffle, Concurrent, PReLU2
class SpatialDiceBranch(HybridBlock):
"""
Spatial element of DiCE block for selected dimension.
Parameters:
----------
sp_size : int
Desired size for selected spatial dimension.
is_height : bool
Is selected dimension height.
fixed_size : bool
Whether to expect fixed spatial size of input image.
"""
def __init__(self,
sp_size,
is_height,
fixed_size,
**kwargs):
super(SpatialDiceBranch, self).__init__(**kwargs)
self.is_height = is_height
self.fixed_size = fixed_size
self.index = 2 if is_height else 3
self.base_sp_size = sp_size
with self.name_scope():
self.conv = conv3x3(
in_channels=self.base_sp_size,
out_channels=self.base_sp_size,
groups=self.base_sp_size)
def hybrid_forward(self, F, x):
if not self.fixed_size:
height, width = x.shape[2:]
if self.is_height:
real_sp_size = height
real_in_size = (real_sp_size, width)
base_in_size = (self.base_sp_size, width)
else:
real_sp_size = width
real_in_size = (height, real_sp_size)
base_in_size = (height, self.base_sp_size)
if real_sp_size != self.base_sp_size:
if real_sp_size < self.base_sp_size:
x = F.contrib.BilinearResize2D(x, height=base_in_size[0], width=base_in_size[1])
else:
x = F.contrib.AdaptiveAvgPooling2D(x, output_size=base_in_size)
x = x.swapaxes(1, self.index)
x = self.conv(x)
x = x.swapaxes(1, self.index)
if not self.fixed_size:
changed_sp_size = x.shape[self.index]
if real_sp_size != changed_sp_size:
if changed_sp_size < real_sp_size:
x = F.contrib.BilinearResize2D(x, height=real_in_size[0], width=real_in_size[1])
else:
x = F.contrib.AdaptiveAvgPooling2D(x, output_size=real_in_size)
return x
class DiceBaseBlock(HybridBlock):
"""
Base part of DiCE block (without attention).
Parameters:
----------
channels : int
Number of input/output channels.
in_size : tuple of two ints
Spatial size of the expected input image.
fixed_size : bool
Whether to expect fixed spatial size of input image.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
channels,
in_size,
fixed_size,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(DiceBaseBlock, self).__init__(**kwargs)
mid_channels = 3 * channels
with self.name_scope():
self.convs = Concurrent()
self.convs.add(conv3x3(
in_channels=channels,
out_channels=channels,
groups=channels))
self.convs.add(SpatialDiceBranch(
sp_size=in_size[0],
is_height=True,
fixed_size=fixed_size))
self.convs.add(SpatialDiceBranch(
sp_size=in_size[1],
is_height=False,
fixed_size=fixed_size))
self.norm_activ = NormActivation(
in_channels=mid_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=(lambda: PReLU2(in_channels=mid_channels)))
self.shuffle = ChannelShuffle(
channels=mid_channels,
groups=3)
self.squeeze_conv = conv1x1_block(
in_channels=mid_channels,
out_channels=channels,
groups=channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=(lambda: PReLU2(in_channels=channels)))
def hybrid_forward(self, F, x):
x = self.convs(x)
x = self.norm_activ(x)
x = self.shuffle(x)
x = self.squeeze_conv(x)
return x
class DiceAttBlock(HybridBlock):
"""
Pure attention part of DiCE block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
reduction : int, default 4
Squeeze reduction value.
"""
def __init__(self,
in_channels,
out_channels,
reduction=4,
**kwargs):
super(DiceAttBlock, self).__init__(**kwargs)
mid_channels = in_channels // reduction
with self.name_scope():
self.pool = nn.GlobalAvgPool2D()
self.conv1 = conv1x1(
in_channels=in_channels,
out_channels=mid_channels,
use_bias=False)
self.activ = nn.Activation("relu")
self.conv2 = conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
use_bias=False)
self.sigmoid = nn.Activation("sigmoid")
def hybrid_forward(self, F, x):
w = self.pool(x)
w = self.conv1(w)
w = self.activ(w)
w = self.conv2(w)
w = self.sigmoid(w)
return w
class DiceBlock(HybridBlock):
"""
DiCE block (volume-wise separable convolutions).
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
in_size : tuple of two ints
Spatial size of the expected input image.
fixed_size : bool
Whether to expect fixed spatial size of input image.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
in_size,
fixed_size,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(DiceBlock, self).__init__(**kwargs)
proj_groups = math.gcd(in_channels, out_channels)
with self.name_scope():
self.base_block = DiceBaseBlock(
channels=in_channels,
in_size=in_size,
fixed_size=fixed_size,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.att = DiceAttBlock(
in_channels=in_channels,
out_channels=out_channels)
# assert (in_channels == out_channels)
self.proj_conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
groups=proj_groups,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=(lambda: PReLU2(in_channels=out_channels)))
def hybrid_forward(self, F, x):
x = self.base_block(x)
w = self.att(x)
x = self.proj_conv(x)
x = F.broadcast_mul(x, w)
return x
class StridedDiceLeftBranch(HybridBlock):
"""
Left branch of the strided DiCE block.
Parameters:
----------
channels : int
Number of input/output channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
channels,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(StridedDiceLeftBranch, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=channels,
out_channels=channels,
strides=2,
groups=channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=(lambda: PReLU2(in_channels=channels)))
self.conv2 = conv1x1_block(
in_channels=channels,
out_channels=channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=(lambda: PReLU2(in_channels=channels)))
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
return x
class StridedDiceRightBranch(HybridBlock):
"""
Right branch of the strided DiCE block.
Parameters:
----------
channels : int
Number of input/output channels.
in_size : tuple of two ints
Spatial size of the expected input image.
fixed_size : bool
Whether to expect fixed spatial size of input image.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
channels,
in_size,
fixed_size,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(StridedDiceRightBranch, self).__init__(**kwargs)
with self.name_scope():
self.pool = nn.AvgPool2D(
pool_size=3,
strides=2,
padding=1)
self.dice = DiceBlock(
in_channels=channels,
out_channels=channels,
in_size=(in_size[0] // 2, in_size[1] // 2),
fixed_size=fixed_size,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.conv = conv1x1_block(
in_channels=channels,
out_channels=channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=(lambda: PReLU2(in_channels=channels)))
def hybrid_forward(self, F, x):
x = self.pool(x)
x = self.dice(x)
x = self.conv(x)
return x
class StridedDiceBlock(HybridBlock):
"""
Strided DiCE block (strided volume-wise separable convolutions).
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
in_size : tuple of two ints
Spatial size of the expected input image.
fixed_size : bool
Whether to expect fixed spatial size of input image.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
in_size,
fixed_size,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(StridedDiceBlock, self).__init__(**kwargs)
assert (out_channels == 2 * in_channels)
with self.name_scope():
self.branches = Concurrent()
self.branches.add(StridedDiceLeftBranch(
channels=in_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
self.branches.add(StridedDiceRightBranch(
channels=in_channels,
in_size=in_size,
fixed_size=fixed_size,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
self.shuffle = ChannelShuffle(
channels=out_channels,
groups=2)
def hybrid_forward(self, F, x):
x = self.branches(x)
x = self.shuffle(x)
return x
class ShuffledDiceRightBranch(HybridBlock):
"""
Right branch of the shuffled DiCE block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
in_size : tuple of two ints
Spatial size of the expected input image.
fixed_size : bool
Whether to expect fixed spatial size of input image.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
in_size,
fixed_size,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(ShuffledDiceRightBranch, self).__init__(**kwargs)
with self.name_scope():
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=(lambda: PReLU2(in_channels=out_channels)))
self.dice = DiceBlock(
in_channels=out_channels,
out_channels=out_channels,
in_size=in_size,
fixed_size=fixed_size,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.dice(x)
return x
class ShuffledDiceBlock(HybridBlock):
"""
Shuffled DiCE block (shuffled volume-wise separable convolutions).
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
in_size : tuple of two ints
Spatial size of the expected input image.
fixed_size : bool
Whether to expect fixed spatial size of input image.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
in_size,
fixed_size,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(ShuffledDiceBlock, self).__init__(**kwargs)
self.left_part = in_channels - in_channels // 2
right_in_channels = in_channels - self.left_part
right_out_channels = out_channels - self.left_part
with self.name_scope():
self.right_branch = ShuffledDiceRightBranch(
in_channels=right_in_channels,
out_channels=right_out_channels,
in_size=in_size,
fixed_size=fixed_size,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off)
self.shuffle = ChannelShuffle(
channels=(2 * right_out_channels),
groups=2)
def hybrid_forward(self, F, x):
x1, x2 = F.split(x, axis=1, num_outputs=2)
x2 = self.right_branch(x2)
x = F.concat(x1, x2, dim=1)
x = self.shuffle(x)
return x
class DiceInitBlock(HybridBlock):
"""
DiceNet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
"""
def __init__(self,
in_channels,
out_channels,
bn_use_global_stats=False,
bn_cudnn_off=False,
**kwargs):
super(DiceInitBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv = conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
strides=2,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off,
activation=(lambda: PReLU2(in_channels=out_channels)))
self.pool = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=1)
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.pool(x)
return x
class DiceClassifier(HybridBlock):
"""
DiceNet specific classifier block.
Parameters:
----------
in_channels : int
Number of input channels.
mid_channels : int
Number of middle channels.
classes : int, default 1000
Number of classification classes.
dropout_rate : float
Parameter of Dropout layer. Faction of the input units to drop.
"""
def __init__(self,
in_channels,
mid_channels,
classes,
dropout_rate,
**kwargs):
super(DiceClassifier, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = conv1x1(
in_channels=in_channels,
out_channels=mid_channels,
groups=4)
self.dropout = nn.Dropout(rate=dropout_rate)
self.conv2 = conv1x1(
in_channels=mid_channels,
out_channels=classes,
use_bias=True)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.dropout(x)
x = self.conv2(x)
return x
class DiceNet(HybridBlock):
"""
DiCENet model from 'DiCENet: Dimension-wise Convolutions for Efficient Networks,' https://arxiv.org/abs/1906.03516.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
classifier_mid_channels : int
Number of middle channels for classifier.
dropout_rate : float
Parameter of Dropout layer in classifier. Faction of the input units to drop.
fixed_size : bool, default True
Whether to expect fixed spatial size of input image.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
bn_cudnn_off : bool, default False
Whether to disable CUDNN batch normalization operator.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
classifier_mid_channels,
dropout_rate,
fixed_size=True,
bn_use_global_stats=False,
bn_cudnn_off=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(DiceNet, self).__init__(**kwargs)
assert ((in_size[0] % 32 == 0) and (in_size[1] % 32 == 0))
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(DiceInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
in_channels = init_block_channels
in_size = (in_size[0] // 4, in_size[1] // 4)
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
unit_class = StridedDiceBlock if j == 0 else ShuffledDiceBlock
stage.add(unit_class(
in_channels=in_channels,
out_channels=out_channels,
in_size=in_size,
fixed_size=fixed_size,
bn_use_global_stats=bn_use_global_stats,
bn_cudnn_off=bn_cudnn_off))
in_channels = out_channels
in_size = (in_size[0] // 2, in_size[1] // 2) if j == 0 else in_size
self.features.add(stage)
self.features.add(nn.GlobalAvgPool2D())
self.output = nn.HybridSequential(prefix="")
self.output.add(DiceClassifier(
in_channels=in_channels,
mid_channels=classifier_mid_channels,
classes=classes,
dropout_rate=dropout_rate))
self.output.add(nn.Flatten())
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_dicenet(width_scale,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create DiCENet model with specific parameters.
Parameters:
----------
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
channels_per_layers_dict = {
0.2: [32, 64, 128],
0.5: [48, 96, 192],
0.75: [86, 172, 344],
1.0: [116, 232, 464],
1.25: [144, 288, 576],
1.5: [176, 352, 704],
1.75: [210, 420, 840],
2.0: [244, 488, 976],
2.4: [278, 556, 1112],
}
if width_scale not in channels_per_layers_dict.keys():
raise ValueError("Unsupported DiceNet with width scale: {}".format(width_scale))
channels_per_layers = channels_per_layers_dict[width_scale]
layers = [3, 7, 3]
if width_scale > 0.2:
init_block_channels = 24
else:
init_block_channels = 16
channels = [[ci] * li for i, (ci, li) in enumerate(zip(channels_per_layers, layers))]
for i in range(len(channels)):
pred_channels = channels[i - 1][-1] if i != 0 else init_block_channels
channels[i] = [pred_channels * 2] + channels[i]
if width_scale > 2.0:
classifier_mid_channels = 1280
else:
classifier_mid_channels = 1024
if width_scale > 1.0:
dropout_rate = 0.2
else:
dropout_rate = 0.1
net = DiceNet(
channels=channels,
init_block_channels=init_block_channels,
classifier_mid_channels=classifier_mid_channels,
dropout_rate=dropout_rate,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def dicenet_wd5(**kwargs):
"""
DiCENet x0.2 model from 'DiCENet: Dimension-wise Convolutions for Efficient Networks,'
https://arxiv.org/abs/1906.03516.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_dicenet(width_scale=0.2, model_name="dicenet_wd5", **kwargs)
def dicenet_wd2(**kwargs):
"""
DiCENet x0.5 model from 'DiCENet: Dimension-wise Convolutions for Efficient Networks,'
https://arxiv.org/abs/1906.03516.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_dicenet(width_scale=0.5, model_name="dicenet_wd2", **kwargs)
def dicenet_w3d4(**kwargs):
"""
DiCENet x0.75 model from 'DiCENet: Dimension-wise Convolutions for Efficient Networks,'
https://arxiv.org/abs/1906.03516.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_dicenet(width_scale=0.75, model_name="dicenet_w3d4", **kwargs)
def dicenet_w1(**kwargs):
"""
DiCENet x1.0 model from 'DiCENet: Dimension-wise Convolutions for Efficient Networks,'
https://arxiv.org/abs/1906.03516.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_dicenet(width_scale=1.0, model_name="dicenet_w1", **kwargs)
def dicenet_w5d4(**kwargs):
"""
DiCENet x1.25 model from 'DiCENet: Dimension-wise Convolutions for Efficient Networks,'
https://arxiv.org/abs/1906.03516.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_dicenet(width_scale=1.25, model_name="dicenet_w5d4", **kwargs)
def dicenet_w3d2(**kwargs):
"""
DiCENet x1.5 model from 'DiCENet: Dimension-wise Convolutions for Efficient Networks,'
https://arxiv.org/abs/1906.03516.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_dicenet(width_scale=1.5, model_name="dicenet_w3d2", **kwargs)
def dicenet_w7d8(**kwargs):
"""
DiCENet x1.75 model from 'DiCENet: Dimension-wise Convolutions for Efficient Networks,'
https://arxiv.org/abs/1906.03516.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_dicenet(width_scale=1.75, model_name="dicenet_w7d8", **kwargs)
def dicenet_w2(**kwargs):
"""
DiCENet x2.0 model from 'DiCENet: Dimension-wise Convolutions for Efficient Networks,'
https://arxiv.org/abs/1906.03516.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_dicenet(width_scale=2.0, model_name="dicenet_w2", **kwargs)
def _calc_width(net):
import numpy as np
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
return weight_count
def _test():
import mxnet as mx
pretrained = False
fixed_size = True
models = [
dicenet_wd5,
dicenet_wd2,
dicenet_w3d4,
dicenet_w1,
dicenet_w5d4,
dicenet_w3d2,
dicenet_w7d8,
dicenet_w2,
]
for model in models:
net = model(pretrained=pretrained, fixed_size=fixed_size)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != dicenet_wd5 or weight_count == 1130704)
assert (model != dicenet_wd2 or weight_count == 1214120)
assert (model != dicenet_w3d4 or weight_count == 1495676)
assert (model != dicenet_w1 or weight_count == 1805604)
assert (model != dicenet_w5d4 or weight_count == 2162888)
assert (model != dicenet_w3d2 or weight_count == 2652200)
assert (model != dicenet_w7d8 or weight_count == 3264932)
assert (model != dicenet_w2 or weight_count == 3979044)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 31,317 | 32.820734 | 119 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/nvpattexp.py | """
Neural Voice Puppetry Audio-to-Expression net for speech-driven facial animation, implemented in Gluon.
Original paper: 'Neural Voice Puppetry: Audio-driven Facial Reenactment,' https://arxiv.org/abs/1912.05566.
"""
__all__ = ['NvpAttExp', 'nvpattexp116bazel76']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import Softmax, DenseBlock, ConvBlock, ConvBlock1d, SelectableDense
class NvpAttExpEncoder(HybridBlock):
"""
Neural Voice Puppetry Audio-to-Expression encoder.
Parameters:
----------
audio_features : int
Number of audio features (characters/sounds).
audio_window_size : int
Size of audio window (for time related audio features).
seq_len : int, default
Size of feature window.
encoder_features : int
Number of encoder features.
"""
def __init__(self,
audio_features,
audio_window_size,
seq_len,
encoder_features,
**kwargs):
super(NvpAttExpEncoder, self).__init__(**kwargs)
self.audio_features = audio_features
self.audio_window_size = audio_window_size
self.seq_len = seq_len
conv_channels = (32, 32, 64, 64)
conv_slopes = (0.02, 0.02, 0.2, 0.2)
fc_channels = (128, 64, encoder_features)
fc_slopes = (0.02, 0.02, None)
att_conv_channels = (16, 8, 4, 2, 1)
att_conv_slopes = 0.02
with self.name_scope():
in_channels = audio_features
self.conv_branch = nn.HybridSequential(prefix="")
with self.conv_branch.name_scope():
for i, (out_channels, slope) in enumerate(zip(conv_channels, conv_slopes)):
self.conv_branch.add(ConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=(3, 1),
strides=(2, 1),
padding=(1, 0),
use_bias=True,
use_bn=False,
activation=nn.LeakyReLU(alpha=slope)))
in_channels = out_channels
self.fc_branch = nn.HybridSequential(prefix="")
with self.fc_branch.name_scope():
for i, (out_channels, slope) in enumerate(zip(fc_channels, fc_slopes)):
activation = nn.LeakyReLU(alpha=slope) if slope is not None else nn.Activation("tanh")
self.fc_branch.add(DenseBlock(
in_channels=in_channels,
out_channels=out_channels,
use_bias=True,
use_bn=False,
activation=activation))
in_channels = out_channels
self.att_conv_branch = nn.HybridSequential(prefix="")
with self.att_conv_branch.name_scope():
for i, out_channels, in enumerate(att_conv_channels):
self.att_conv_branch.add(ConvBlock1d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
strides=1,
padding=1,
use_bias=True,
use_bn=False,
activation=nn.LeakyReLU(alpha=att_conv_slopes)))
in_channels = out_channels
self.att_fc = DenseBlock(
in_channels=seq_len,
out_channels=seq_len,
use_bias=True,
use_bn=False,
activation=Softmax(axis=1))
def hybrid_forward(self, F, x):
x = x.reshape((-3, 1, self.audio_window_size, self.audio_features))
x = x.swapaxes(1, 3)
x = self.conv_branch(x)
x = x.reshape((0, 1, -1))
x = self.fc_branch(x)
x = x.reshape((-4, -1, self.seq_len, 0))
x = x.swapaxes(1, 2)
y = x.slice_axis(axis=-1, begin=(self.seq_len // 2), end=(self.seq_len // 2) + 1).squeeze(axis=-1)
w = self.att_conv_branch(x)
w = w.reshape((0, -1))
w = self.att_fc(w)
w = w.expand_dims(axis=-1)
x = F.batch_dot(x, w)
x = x.squeeze(axis=-1)
return x, y
class NvpAttExp(HybridBlock):
"""
Neural Voice Puppetry Audio-to-Expression model from 'Neural Voice Puppetry: Audio-driven Facial Reenactment,'
https://arxiv.org/abs/1912.05566.
Parameters:
----------
audio_features : int, default 29
Number of audio features (characters/sounds).
audio_window_size : int, default 16
Size of audio window (for time related audio features).
seq_len : int, default 8
Size of feature window.
base_persons : int, default 116
Number of base persons (identities).
blendshapes : int, default 76
Number of 3D model blendshapes.
encoder_features : int, default 32
Number of encoder features.
"""
def __init__(self,
audio_features=29,
audio_window_size=16,
seq_len=8,
base_persons=116,
blendshapes=76,
encoder_features=32,
**kwargs):
super(NvpAttExp, self).__init__(**kwargs)
self.base_persons = base_persons
with self.name_scope():
self.encoder = NvpAttExpEncoder(
audio_features=audio_features,
audio_window_size=audio_window_size,
seq_len=seq_len,
encoder_features=encoder_features)
self.decoder = SelectableDense(
in_channels=encoder_features,
out_channels=blendshapes,
use_bias=False,
num_options=base_persons)
def hybrid_forward(self, F, x, pid):
x, y = self.encoder(x)
x = self.decoder(x, pid)
y = self.decoder(y, pid)
return x, y
def get_nvpattexp(base_persons,
blendshapes,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create Neural Voice Puppetry Audio-to-Expression model with specific parameters.
Parameters:
----------
base_persons : int
Number of base persons (subjects).
blendshapes : int
Number of 3D model blendshapes.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
net = NvpAttExp(
base_persons=base_persons,
blendshapes=blendshapes,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def nvpattexp116bazel76(**kwargs):
"""
Neural Voice Puppetry Audio-to-Expression model for 116 base persons and Bazel topology with 76 blendshapes from
'Neural Voice Puppetry: Audio-driven Facial Reenactment,' https://arxiv.org/abs/1912.05566.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_nvpattexp(base_persons=116, blendshapes=76, model_name="nvpattexp116bazel76", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
nvpattexp116bazel76,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != nvpattexp116bazel76 or weight_count == 327397)
batch = 14
seq_len = 8
audio_window_size = 16
audio_features = 29
blendshapes = 76
x = mx.nd.random.normal(shape=(batch, seq_len, audio_window_size, audio_features), ctx=ctx)
pid = mx.nd.array(np.full(shape=(batch,), fill_value=3), ctx=ctx)
y1, y2 = net(x, pid)
assert (y1.shape == y2.shape == (batch, blendshapes))
if __name__ == "__main__":
_test()
| 9,294 | 33.682836 | 116 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/octresnet.py | """
Oct-ResNet for ImageNet-1K, implemented in Gluon.
Original paper: 'Drop an Octave: Reducing Spatial Redundancy in Convolutional Neural Networks with Octave
Convolution,' https://arxiv.org/abs/1904.05049.
"""
__all__ = ['OctResNet', 'octresnet10_ad2', 'octresnet50b_ad2', 'OctResUnit']
import os
from inspect import isfunction
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import ReLU6, DualPathSequential
from .resnet import ResInitBlock
class OctConv(nn.Conv2D):
"""
Octave convolution layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
oct_alpha : float, default 0.0
Octave alpha coefficient.
oct_mode : str, default 'std'
Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.
oct_value : int, default 2
Octave value.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding=1,
dilation=1,
groups=1,
use_bias=False,
oct_alpha=0.0,
oct_mode="std",
oct_value=2,
**kwargs):
if isinstance(strides, int):
strides = (strides, strides)
self.downsample = (strides[0] > 1) or (strides[1] > 1)
assert (strides[0] in [1, oct_value]) and (strides[1] in [1, oct_value])
strides = (1, 1)
if oct_mode == "first":
in_alpha = 0.0
out_alpha = oct_alpha
elif oct_mode == "norm":
in_alpha = oct_alpha
out_alpha = oct_alpha
elif oct_mode == "last":
in_alpha = oct_alpha
out_alpha = 0.0
elif oct_mode == "std":
in_alpha = 0.0
out_alpha = 0.0
else:
raise ValueError("Unsupported octave convolution mode: {}".format(oct_mode))
self.h_in_channels = int(in_channels * (1.0 - in_alpha))
self.h_out_channels = int(out_channels * (1.0 - out_alpha))
self.l_out_channels = out_channels - self.h_out_channels
self.oct_alpha = oct_alpha
self.oct_mode = oct_mode
self.oct_value = oct_value
super(OctConv, self).__init__(
in_channels=in_channels,
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
**kwargs)
self.conv_kwargs = self._kwargs.copy()
del self.conv_kwargs["num_filter"]
def hybrid_forward(self, F, hx, lx=None, weight=None, bias=None):
if self.oct_mode == "std":
return super(OctConv, self).hybrid_forward(F, hx, weight=weight, bias=bias), None
if self.downsample:
hx = F.Pooling(
hx,
kernel=(self.oct_value, self.oct_value),
stride=(self.oct_value, self.oct_value),
pool_type="avg")
hhy = F.Convolution(
hx,
weight=weight.slice(begin=(None, None), end=(self.h_out_channels, self.h_in_channels)),
bias=bias.slice(begin=(None,), end=(self.h_out_channels,)) if bias is not None else None,
num_filter=self.h_out_channels,
**self.conv_kwargs)
if self.oct_mode != "first":
hlx = F.Convolution(
lx,
weight=weight.slice(begin=(None, self.h_in_channels), end=(self.h_out_channels, None)),
bias=bias.slice(begin=(None,), end=(self.h_out_channels,)) if bias is not None else None,
num_filter=self.h_out_channels,
**self.conv_kwargs)
if self.oct_mode == "last":
hy = hhy + hlx
ly = None
return hy, ly
lhx = F.Pooling(
hx,
kernel=(self.oct_value, self.oct_value),
stride=(self.oct_value, self.oct_value),
pool_type="avg")
lhy = F.Convolution(
lhx,
weight=weight.slice(begin=(self.h_out_channels, None), end=(None, self.h_in_channels)),
bias=bias.slice(begin=(self.h_out_channels,), end=(None,)) if bias is not None else None,
num_filter=self.l_out_channels,
**self.conv_kwargs)
if self.oct_mode == "first":
hy = hhy
ly = lhy
return hy, ly
if self.downsample:
hly = hlx
llx = F.Pooling(
lx,
kernel=(self.oct_value, self.oct_value),
stride=(self.oct_value, self.oct_value),
pool_type="avg")
else:
hly = F.UpSampling(hlx, scale=self.oct_value, sample_type="nearest")
llx = lx
lly = F.Convolution(
llx,
weight=weight.slice(begin=(self.h_out_channels, self.h_in_channels), end=(None, None)),
bias=bias.slice(begin=(self.h_out_channels,), end=(None,)) if bias is not None else None,
num_filter=self.l_out_channels,
**self.conv_kwargs)
hy = hhy + hly
ly = lhy + lly
return hy, ly
def __repr__(self):
s = '{name}({mapping}, kernel_size={kernel}, stride={stride}'
len_kernel_size = len(self._kwargs['kernel'])
if self._kwargs['pad'] != (0,) * len_kernel_size:
s += ', padding={pad}'
if self._kwargs['dilate'] != (1,) * len_kernel_size:
s += ', dilation={dilate}'
if hasattr(self, 'out_pad') and self.out_pad != (0,) * len_kernel_size:
s += ', output_padding={out_pad}'.format(out_pad=self.out_pad)
if self._kwargs['num_group'] != 1:
s += ', groups={num_group}'
if self.bias is None:
s += ', bias=False'
if self.act:
s += ', {}'.format(self.act)
s += ', oct_alpha={}'.format(self.oct_alpha)
s += ', oct_mode={}'.format(self.oct_mode)
s += ')'
shape = self.weight.shape
return s.format(name=self.__class__.__name__,
mapping='{0} -> {1}'.format(shape[1] if shape[1] else None, shape[0]),
**self._kwargs)
class OctConvBlock(HybridBlock):
"""
Octave convolution block with Batch normalization and ReLU/ReLU6 activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
oct_alpha : float, default 0.0
Octave alpha coefficient.
oct_mode : str, default 'std'
Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
activation : function or str or None, default nn.Activation("relu")
Activation function or name of activation function.
activate : bool, default True
Whether activate the convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
dilation=1,
groups=1,
use_bias=False,
oct_alpha=0.0,
oct_mode="std",
bn_epsilon=1e-5,
bn_use_global_stats=False,
activation=(lambda: nn.Activation("relu")),
activate=True,
**kwargs):
super(OctConvBlock, self).__init__(**kwargs)
self.activate = activate
self.last = (oct_mode == "last") or (oct_mode == "std")
out_alpha = 0.0 if self.last else oct_alpha
h_out_channels = int(out_channels * (1.0 - out_alpha))
l_out_channels = out_channels - h_out_channels
with self.name_scope():
self.conv = OctConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
oct_alpha=oct_alpha,
oct_mode=oct_mode)
self.h_bn = nn.BatchNorm(
in_channels=h_out_channels,
epsilon=bn_epsilon,
use_global_stats=bn_use_global_stats)
if not self.last:
self.l_bn = nn.BatchNorm(
in_channels=l_out_channels,
epsilon=bn_epsilon,
use_global_stats=bn_use_global_stats)
if self.activate:
assert (activation is not None)
if isfunction(activation):
self.activ = activation()
elif isinstance(activation, str):
if activation == "relu6":
self.activ = ReLU6()
else:
self.activ = nn.Activation(activation)
else:
self.activ = activation
def hybrid_forward(self, F, hx, lx=None):
hx, lx = self.conv(hx, lx)
hx = self.h_bn(hx)
if self.activate:
hx = self.activ(hx)
if not self.last:
lx = self.l_bn(lx)
if self.activate:
lx = self.activ(lx)
return hx, lx
def oct_conv1x1_block(in_channels,
out_channels,
strides=1,
groups=1,
use_bias=False,
oct_alpha=0.0,
oct_mode="std",
bn_epsilon=1e-5,
bn_use_global_stats=False,
activation=(lambda: nn.Activation("relu")),
activate=True,
**kwargs):
"""
1x1 version of the octave convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
oct_alpha : float, default 0.0
Octave alpha coefficient.
oct_mode : str, default 'std'
Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
activation : function or str or None, default nn.Activation("relu")
Activation function or name of activation function.
activate : bool, default True
Whether activate the convolution block.
"""
return OctConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
strides=strides,
padding=0,
groups=groups,
use_bias=use_bias,
oct_alpha=oct_alpha,
oct_mode=oct_mode,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
activation=activation,
activate=activate,
**kwargs)
def oct_conv3x3_block(in_channels,
out_channels,
strides=1,
padding=1,
dilation=1,
groups=1,
use_bias=False,
oct_alpha=0.0,
oct_mode="std",
bn_epsilon=1e-5,
bn_use_global_stats=False,
activation=(lambda: nn.Activation("relu")),
activate=True,
**kwargs):
"""
3x3 version of the octave convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int, default 1
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
groups : int, default 1
Number of groups.
use_bias : bool, default False
Whether the layer uses a bias vector.
oct_alpha : float, default 0.0
Octave alpha coefficient.
oct_mode : str, default 'std'
Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
activation : function or str or None, default nn.Activation("relu")
Activation function or name of activation function.
activate : bool, default True
Whether activate the convolution block.
"""
return OctConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
strides=strides,
padding=padding,
dilation=dilation,
groups=groups,
use_bias=use_bias,
oct_alpha=oct_alpha,
oct_mode=oct_mode,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats,
activation=activation,
activate=activate,
**kwargs)
class OctResBlock(HybridBlock):
"""
Simple Oct-ResNet block for residual path in Oct-ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
oct_alpha : float, default 0.0
Octave alpha coefficient.
oct_mode : str, default 'std'
Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
oct_alpha=0.0,
oct_mode="std",
bn_use_global_stats=False,
**kwargs):
super(OctResBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv1 = oct_conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
oct_alpha=oct_alpha,
oct_mode=oct_mode,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = oct_conv3x3_block(
in_channels=out_channels,
out_channels=out_channels,
oct_alpha=oct_alpha,
oct_mode=("std" if oct_mode == "last" else (oct_mode if oct_mode != "first" else "norm")),
bn_use_global_stats=bn_use_global_stats,
activation=None,
activate=False)
def hybrid_forward(self, F, hx, lx=None):
hx, lx = self.conv1(hx, lx)
hx, lx = self.conv2(hx, lx)
return hx, lx
class OctResBottleneck(HybridBlock):
"""
Oct-ResNet bottleneck block for residual path in Oct-ResNet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for the second convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for the second convolution layer.
oct_alpha : float, default 0.0
Octave alpha coefficient.
oct_mode : str, default 'std'
Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
conv1_stride : bool, default False
Whether to use stride in the first or the second convolution layer of the block.
bottleneck_factor : int, default 4
Bottleneck factor.
"""
def __init__(self,
in_channels,
out_channels,
strides,
padding=1,
dilation=1,
oct_alpha=0.0,
oct_mode="std",
bn_use_global_stats=False,
conv1_stride=False,
bottleneck_factor=4,
**kwargs):
super(OctResBottleneck, self).__init__(**kwargs)
mid_channels = out_channels // bottleneck_factor
with self.name_scope():
self.conv1 = oct_conv1x1_block(
in_channels=in_channels,
out_channels=mid_channels,
strides=(strides if conv1_stride else 1),
oct_alpha=oct_alpha,
oct_mode=(oct_mode if oct_mode != "last" else "norm"),
bn_use_global_stats=bn_use_global_stats)
self.conv2 = oct_conv3x3_block(
in_channels=mid_channels,
out_channels=mid_channels,
strides=(1 if conv1_stride else strides),
padding=padding,
dilation=dilation,
oct_alpha=oct_alpha,
oct_mode=(oct_mode if oct_mode != "first" else "norm"),
bn_use_global_stats=bn_use_global_stats)
self.conv3 = oct_conv1x1_block(
in_channels=mid_channels,
out_channels=out_channels,
oct_alpha=oct_alpha,
oct_mode=("std" if oct_mode == "last" else (oct_mode if oct_mode != "first" else "norm")),
bn_use_global_stats=bn_use_global_stats,
activation=None,
activate=False)
def hybrid_forward(self, F, hx, lx=None):
hx, lx = self.conv1(hx, lx)
hx, lx = self.conv2(hx, lx)
hx, lx = self.conv3(hx, lx)
return hx, lx
class OctResUnit(HybridBlock):
"""
Oct-ResNet unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for the second convolution layer in bottleneck.
dilation : int or tuple/list of 2 int, default 1
Dilation value for the second convolution layer in bottleneck.
oct_alpha : float, default 0.0
Octave alpha coefficient.
oct_mode : str, default 'std'
Octave convolution mode. It can be 'first', 'norm', 'last', or 'std'.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
bottleneck : bool, default True
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default False
Whether to use stride in the first or the second convolution layer of the block.
"""
def __init__(self,
in_channels,
out_channels,
strides,
padding=1,
dilation=1,
oct_alpha=0.0,
oct_mode="std",
bn_use_global_stats=False,
bottleneck=True,
conv1_stride=False,
**kwargs):
super(OctResUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1) or\
((oct_mode == "first") and (oct_alpha != 0.0))
with self.name_scope():
if bottleneck:
self.body = OctResBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
padding=padding,
dilation=dilation,
oct_alpha=oct_alpha,
oct_mode=oct_mode,
bn_use_global_stats=bn_use_global_stats,
conv1_stride=conv1_stride)
else:
self.body = OctResBlock(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
oct_alpha=oct_alpha,
oct_mode=oct_mode,
bn_use_global_stats=bn_use_global_stats)
if self.resize_identity:
self.identity_conv = oct_conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
oct_alpha=oct_alpha,
oct_mode=oct_mode,
bn_use_global_stats=bn_use_global_stats,
activation=None,
activate=False)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, hx, lx=None):
if self.resize_identity:
h_identity, l_identity = self.identity_conv(hx, lx)
else:
h_identity, l_identity = hx, lx
hx, lx = self.body(hx, lx)
hx = hx + h_identity
hx = self.activ(hx)
if lx is not None:
lx = lx + l_identity
lx = self.activ(lx)
return hx, lx
class OctResNet(HybridBlock):
"""
Oct-ResNet model from 'Drop an Octave: Reducing Spatial Redundancy in Convolutional Neural Networks with Octave
Convolution,' https://arxiv.org/abs/1904.05049.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
oct_alpha : float, default 0.5
Octave alpha coefficient.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
bottleneck,
conv1_stride,
oct_alpha=0.5,
bn_use_global_stats=False,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(OctResNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = DualPathSequential(
return_two=False,
first_ordinals=1,
last_ordinals=1,
prefix="")
self.features.add(ResInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = DualPathSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
if (i == 0) and (j == 0):
oct_mode = "first"
elif (i == len(channels) - 1) and (j == 0):
oct_mode = "last"
elif (i == len(channels) - 1) and (j != 0):
oct_mode = "std"
else:
oct_mode = "norm"
stage.add(OctResUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
oct_alpha=oct_alpha,
oct_mode=oct_mode,
bn_use_global_stats=bn_use_global_stats,
bottleneck=bottleneck,
conv1_stride=conv1_stride))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_octresnet(blocks,
bottleneck=None,
conv1_stride=True,
oct_alpha=0.5,
width_scale=1.0,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create Oct-ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
bottleneck : bool, default None
Whether to use a bottleneck or simple block in units.
conv1_stride : bool, default True
Whether to use stride in the first or the second convolution layer in units.
oct_alpha : float, default 0.5
Octave alpha coefficient.
width_scale : float, default 1.0
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if bottleneck is None:
bottleneck = (blocks >= 50)
if blocks == 10:
layers = [1, 1, 1, 1]
elif blocks == 12:
layers = [2, 1, 1, 1]
elif blocks == 14 and not bottleneck:
layers = [2, 2, 1, 1]
elif (blocks == 14) and bottleneck:
layers = [1, 1, 1, 1]
elif blocks == 16:
layers = [2, 2, 2, 1]
elif blocks == 18:
layers = [2, 2, 2, 2]
elif (blocks == 26) and not bottleneck:
layers = [3, 3, 3, 3]
elif (blocks == 26) and bottleneck:
layers = [2, 2, 2, 2]
elif blocks == 34:
layers = [3, 4, 6, 3]
elif blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
elif blocks == 269:
layers = [3, 30, 48, 8]
else:
raise ValueError("Unsupported Oct-ResNet with number of blocks: {}".format(blocks))
if bottleneck:
assert (sum(layers) * 3 + 2 == blocks)
else:
assert (sum(layers) * 2 + 2 == blocks)
init_block_channels = 64
channels_per_layers = [64, 128, 256, 512]
if bottleneck:
bottleneck_factor = 4
channels_per_layers = [ci * bottleneck_factor for ci in channels_per_layers]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) if (i != len(channels) - 1) or (j != len(ci) - 1) else cij
for j, cij in enumerate(ci)] for i, ci in enumerate(channels)]
init_block_channels = int(init_block_channels * width_scale)
net = OctResNet(
channels=channels,
init_block_channels=init_block_channels,
bottleneck=bottleneck,
conv1_stride=conv1_stride,
oct_alpha=oct_alpha,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def octresnet10_ad2(**kwargs):
"""
Oct-ResNet-10 (alpha=1/2) model from 'Drop an Octave: Reducing Spatial Redundancy in Convolutional Neural Networks
with Octave Convolution,' https://arxiv.org/abs/1904.05049.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_octresnet(blocks=10, oct_alpha=0.5, model_name="octresnet10_ad2", **kwargs)
def octresnet50b_ad2(**kwargs):
"""
Oct-ResNet-50b (alpha=1/2) model from 'Drop an Octave: Reducing Spatial Redundancy in Convolutional Neural Networks
with Octave Convolution,' https://arxiv.org/abs/1904.05049.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_octresnet(blocks=50, conv1_stride=False, oct_alpha=0.5, model_name="octresnet50b_ad2", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
octresnet10_ad2,
octresnet50b_ad2,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != octresnet10_ad2 or weight_count == 5423016)
assert (model != octresnet50b_ad2 or weight_count == 25557032)
x = mx.nd.zeros((14, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (14, 1000))
if __name__ == "__main__":
_test()
| 32,656 | 35.245283 | 119 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/alexnet.py | """
AlexNet for ImageNet-1K, implemented in Gluon.
Original paper: 'One weird trick for parallelizing convolutional neural networks,'
https://arxiv.org/abs/1404.5997.
"""
__all__ = ['AlexNet', 'alexnet', 'alexnetb']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import ConvBlock
class AlexConv(ConvBlock):
"""
AlexNet specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
use_lrn : bool
Whether to use LRN layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
use_lrn,
**kwargs):
super(AlexConv, self).__init__(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
use_bias=True,
use_bn=False,
**kwargs)
self.use_lrn = use_lrn
def hybrid_forward(self, F, x):
x = super(AlexConv, self).hybrid_forward(F, x)
if self.use_lrn:
x = F.LRN(x, nsize=5)
return x
class AlexDense(HybridBlock):
"""
AlexNet specific dense block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels,
**kwargs):
super(AlexDense, self).__init__(**kwargs)
with self.name_scope():
self.fc = nn.Dense(
units=out_channels,
in_units=in_channels)
self.activ = nn.Activation("relu")
self.dropout = nn.Dropout(rate=0.5)
def hybrid_forward(self, F, x):
x = self.fc(x)
x = self.activ(x)
x = self.dropout(x)
return x
class AlexOutputBlock(HybridBlock):
"""
AlexNet specific output block.
Parameters:
----------
in_channels : int
Number of input channels.
classes : int
Number of classification classes.
"""
def __init__(self,
in_channels,
classes,
**kwargs):
super(AlexOutputBlock, self).__init__(**kwargs)
mid_channels = 4096
with self.name_scope():
self.fc1 = AlexDense(
in_channels=in_channels,
out_channels=mid_channels)
self.fc2 = AlexDense(
in_channels=mid_channels,
out_channels=mid_channels)
self.fc3 = nn.Dense(
units=classes,
in_units=mid_channels)
def hybrid_forward(self, F, x):
x = self.fc1(x)
x = self.fc2(x)
x = self.fc3(x)
return x
class AlexNet(HybridBlock):
"""
AlexNet model from 'One weird trick for parallelizing convolutional neural networks,'
https://arxiv.org/abs/1404.5997.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
kernel_sizes : list of list of int
Convolution window sizes for each unit.
strides : list of list of int or tuple/list of 2 int
Strides of the convolution for each unit.
paddings : list of list of int or tuple/list of 2 int
Padding value for convolution layer for each unit.
use_lrn : bool
Whether to use LRN layer.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
kernel_sizes,
strides,
paddings,
use_lrn,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(AlexNet, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
for i, channels_per_stage in enumerate(channels):
use_lrn_i = use_lrn and (i in [0, 1])
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
stage.add(AlexConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_sizes[i][j],
strides=strides[i][j],
padding=paddings[i][j],
use_lrn=use_lrn_i))
in_channels = out_channels
stage.add(nn.MaxPool2D(
pool_size=3,
strides=2,
padding=0,
ceil_mode=True))
self.features.add(stage)
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
in_channels = in_channels * 6 * 6
self.output.add(AlexOutputBlock(
in_channels=in_channels,
classes=classes))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_alexnet(version="a",
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create AlexNet model with specific parameters.
Parameters:
----------
version : str, default 'a'
Version of AlexNet ('a' or 'b').
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if version == "a":
channels = [[96], [256], [384, 384, 256]]
kernel_sizes = [[11], [5], [3, 3, 3]]
strides = [[4], [1], [1, 1, 1]]
paddings = [[0], [2], [1, 1, 1]]
use_lrn = True
elif version == "b":
channels = [[64], [192], [384, 256, 256]]
kernel_sizes = [[11], [5], [3, 3, 3]]
strides = [[4], [1], [1, 1, 1]]
paddings = [[2], [2], [1, 1, 1]]
use_lrn = False
else:
raise ValueError("Unsupported AlexNet version {}".format(version))
net = AlexNet(
channels=channels,
kernel_sizes=kernel_sizes,
strides=strides,
paddings=paddings,
use_lrn=use_lrn,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def alexnet(**kwargs):
"""
AlexNet model from 'One weird trick for parallelizing convolutional neural networks,'
https://arxiv.org/abs/1404.5997.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_alexnet(model_name="alexnet", **kwargs)
def alexnetb(**kwargs):
"""
AlexNet-b model from 'One weird trick for parallelizing convolutional neural networks,'
https://arxiv.org/abs/1404.5997. Non-standard version.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_alexnet(version="b", model_name="alexnetb", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
alexnet,
alexnetb,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != alexnet or weight_count == 62378344)
assert (model != alexnetb or weight_count == 61100840)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 9,854 | 29.137615 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/mobilenet_cub.py | """
MobileNet & FD-MobileNet for CUB-200-2011, implemented in Gluon.
Original papers:
- 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,'
https://arxiv.org/abs/1704.04861.
- 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,' https://arxiv.org/abs/1802.03750.
"""
__all__ = ['mobilenet_w1_cub', 'mobilenet_w3d4_cub', 'mobilenet_wd2_cub', 'mobilenet_wd4_cub', 'fdmobilenet_w1_cub',
'fdmobilenet_w3d4_cub', 'fdmobilenet_wd2_cub', 'fdmobilenet_wd4_cub']
from .mobilenet import get_mobilenet
from .fdmobilenet import get_fdmobilenet
def mobilenet_w1_cub(classes=200, **kwargs):
"""
1.0 MobileNet-224 model for CUB-200-2011 from 'MobileNets: Efficient Convolutional Neural Networks for Mobile
Vision Applications,' https://arxiv.org/abs/1704.04861.
Parameters:
----------
classes : int, default 200
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenet(classes=classes, width_scale=1.0, model_name="mobilenet_w1_cub", **kwargs)
def mobilenet_w3d4_cub(classes=200, **kwargs):
"""
0.75 MobileNet-224 model for CUB-200-2011 from 'MobileNets: Efficient Convolutional Neural Networks for Mobile
Vision Applications,' https://arxiv.org/abs/1704.04861.
Parameters:
----------
classes : int, default 200
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenet(classes=classes, width_scale=0.75, model_name="mobilenet_w3d4_cub", **kwargs)
def mobilenet_wd2_cub(classes=200, **kwargs):
"""
0.5 MobileNet-224 model for CUB-200-2011 from 'MobileNets: Efficient Convolutional Neural Networks for Mobile
Vision Applications,' https://arxiv.org/abs/1704.04861.
Parameters:
----------
classes : int, default 200
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenet(classes=classes, width_scale=0.5, model_name="mobilenet_wd2_cub", **kwargs)
def mobilenet_wd4_cub(classes=200, **kwargs):
"""
0.25 MobileNet-224 model for CUB-200-2011 from 'MobileNets: Efficient Convolutional Neural Networks for Mobile
Vision Applications,' https://arxiv.org/abs/1704.04861.
Parameters:
----------
classes : int, default 200
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_mobilenet(classes=classes, width_scale=0.25, model_name="mobilenet_wd4_cub", **kwargs)
def fdmobilenet_w1_cub(classes=200, **kwargs):
"""
FD-MobileNet 1.0x model for CUB-200-2011 from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
Parameters:
----------
classes : int, default 200
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_fdmobilenet(classes=classes, width_scale=1.0, model_name="fdmobilenet_w1_cub", **kwargs)
def fdmobilenet_w3d4_cub(classes=200, **kwargs):
"""
FD-MobileNet 0.75x model for CUB-200-2011 from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
Parameters:
----------
classes : int, default 200
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_fdmobilenet(classes=classes, width_scale=0.75, model_name="fdmobilenet_w3d4_cub", **kwargs)
def fdmobilenet_wd2_cub(classes=200, **kwargs):
"""
FD-MobileNet 0.5x model for CUB-200-2011 from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
Parameters:
----------
classes : int, default 200
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_fdmobilenet(classes=classes, width_scale=0.5, model_name="fdmobilenet_wd2_cub", **kwargs)
def fdmobilenet_wd4_cub(classes=200, **kwargs):
"""
FD-MobileNet 0.25x model for CUB-200-2011 from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
Parameters:
----------
classes : int, default 200
Number of classification classes.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_fdmobilenet(classes=classes, width_scale=0.25, model_name="fdmobilenet_wd4_cub", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
mobilenet_w1_cub,
mobilenet_w3d4_cub,
mobilenet_wd2_cub,
mobilenet_wd4_cub,
fdmobilenet_w1_cub,
fdmobilenet_w3d4_cub,
fdmobilenet_wd2_cub,
fdmobilenet_wd4_cub,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != mobilenet_w1_cub or weight_count == 3411976)
assert (model != mobilenet_w3d4_cub or weight_count == 1970360)
assert (model != mobilenet_wd2_cub or weight_count == 921192)
assert (model != mobilenet_wd4_cub or weight_count == 264472)
assert (model != fdmobilenet_w1_cub or weight_count == 2081288)
assert (model != fdmobilenet_w3d4_cub or weight_count == 1218104)
assert (model != fdmobilenet_wd2_cub or weight_count == 583528)
assert (model != fdmobilenet_wd4_cub or weight_count == 177560)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 200))
if __name__ == "__main__":
_test()
| 7,904 | 35.597222 | 120 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/wrn.py | """
WRN for ImageNet-1K, implemented in Gluon.
Original paper: 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.
"""
__all__ = ['WRN', 'wrn50_2']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
class WRNConv(HybridBlock):
"""
WRN specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
activate : bool
Whether activate the convolution block.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
activate,
**kwargs):
super(WRNConv, self).__init__(**kwargs)
self.activate = activate
with self.name_scope():
self.conv = nn.Conv2D(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
use_bias=True,
in_channels=in_channels)
if self.activate:
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
x = self.conv(x)
if self.activate:
x = self.activ(x)
return x
def wrn_conv1x1(in_channels,
out_channels,
strides,
activate):
"""
1x1 version of the WRN specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
activate : bool
Whether activate the convolution block.
"""
return WRNConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
strides=strides,
padding=0,
activate=activate)
def wrn_conv3x3(in_channels,
out_channels,
strides,
activate):
"""
3x3 version of the WRN specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
activate : bool
Whether activate the convolution block.
"""
return WRNConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
strides=strides,
padding=1,
activate=activate)
class WRNBottleneck(HybridBlock):
"""
WRN bottleneck block for residual path in WRN unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
width_factor : float
Wide scale factor for width of layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
width_factor,
**kwargs):
super(WRNBottleneck, self).__init__(**kwargs)
mid_channels = int(round(out_channels // 4 * width_factor))
with self.name_scope():
self.conv1 = wrn_conv1x1(
in_channels=in_channels,
out_channels=mid_channels,
strides=1,
activate=True)
self.conv2 = wrn_conv3x3(
in_channels=mid_channels,
out_channels=mid_channels,
strides=strides,
activate=True)
self.conv3 = wrn_conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
strides=1,
activate=False)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
class WRNUnit(HybridBlock):
"""
WRN unit with residual connection.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
width_factor : float
Wide scale factor for width of layers.
"""
def __init__(self,
in_channels,
out_channels,
strides,
width_factor,
**kwargs):
super(WRNUnit, self).__init__(**kwargs)
self.resize_identity = (in_channels != out_channels) or (strides != 1)
with self.name_scope():
self.body = WRNBottleneck(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
width_factor=width_factor)
if self.resize_identity:
self.identity_conv = wrn_conv1x1(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
activate=False)
self.activ = nn.Activation("relu")
def hybrid_forward(self, F, x):
if self.resize_identity:
identity = self.identity_conv(x)
else:
identity = x
x = self.body(x)
x = x + identity
x = self.activ(x)
return x
class WRNInitBlock(HybridBlock):
"""
WRN specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels,
**kwargs):
super(WRNInitBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv = WRNConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=7,
strides=2,
padding=3,
activate=True)
self.pool = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=1)
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.pool(x)
return x
class WRN(HybridBlock):
"""
WRN model from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
width_factor : float
Wide scale factor for width of layers.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
width_factor,
in_channels=3,
in_size=(224, 224),
classes=1000,
**kwargs):
super(WRN, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(WRNInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
strides = 2 if (j == 0) and (i != 0) else 1
stage.add(WRNUnit(
in_channels=in_channels,
out_channels=out_channels,
strides=strides,
width_factor=width_factor))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_wrn(blocks,
width_factor,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create WRN model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
width_factor : float
Wide scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
if blocks == 50:
layers = [3, 4, 6, 3]
elif blocks == 101:
layers = [3, 4, 23, 3]
elif blocks == 152:
layers = [3, 8, 36, 3]
elif blocks == 200:
layers = [3, 24, 36, 3]
else:
raise ValueError("Unsupported WRN with number of blocks: {}".format(blocks))
init_block_channels = 64
channels_per_layers = [256, 512, 1024, 2048]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = WRN(
channels=channels,
init_block_channels=init_block_channels,
width_factor=width_factor,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def wrn50_2(**kwargs):
"""
WRN-50-2 model from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_wrn(blocks=50, width_factor=2.0, model_name="wrn50_2", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
wrn50_2,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != wrn50_2 or weight_count == 68849128)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 12,149 | 27.723404 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/inceptionv3.py | """
InceptionV3 for ImageNet-1K, implemented in Gluon.
Original paper: 'Rethinking the Inception Architecture for Computer Vision,'
https://arxiv.org/abs/1512.00567.
"""
__all__ = ['InceptionV3', 'inceptionv3', 'inceptionv3_gl', 'MaxPoolBranch', 'AvgPoolBranch', 'Conv1x1Branch',
'ConvSeqBranch']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from mxnet.gluon.contrib.nn import HybridConcurrent
from .common import ConvBlock, conv1x1_block, conv3x3_block
class MaxPoolBranch(HybridBlock):
"""
Inception specific max pooling branch block.
"""
def __init__(self,
**kwargs):
super(MaxPoolBranch, self).__init__(**kwargs)
with self.name_scope():
self.pool = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=0)
def hybrid_forward(self, F, x):
x = self.pool(x)
return x
class AvgPoolBranch(HybridBlock):
"""
Inception specific average pooling branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_epsilon : float
Small float added to variance in Batch norm.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
count_include_pad : bool, default True
Whether to include the zero-padding in the averaging calculation.
"""
def __init__(self,
in_channels,
out_channels,
bn_epsilon,
bn_use_global_stats,
count_include_pad=True,
**kwargs):
super(AvgPoolBranch, self).__init__(**kwargs)
with self.name_scope():
self.pool = nn.AvgPool2D(
pool_size=3,
strides=1,
padding=1,
count_include_pad=count_include_pad)
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.pool(x)
x = self.conv(x)
return x
class Conv1x1Branch(HybridBlock):
"""
Inception specific convolutional 1x1 branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_epsilon : float
Small float added to variance in Batch norm.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_epsilon,
bn_use_global_stats,
**kwargs):
super(Conv1x1Branch, self).__init__(**kwargs)
with self.name_scope():
self.conv = conv1x1_block(
in_channels=in_channels,
out_channels=out_channels,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv(x)
return x
class ConvSeqBranch(HybridBlock):
"""
Inception specific convolutional sequence branch block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of tuple of int
List of numbers of output channels.
kernel_size_list : list of tuple of int or tuple of tuple/list of 2 int
List of convolution window sizes.
strides_list : list of tuple of int or tuple of tuple/list of 2 int
List of strides of the convolution.
padding_list : list of tuple of int or tuple of tuple/list of 2 int
List of padding values for convolution layers.
bn_epsilon : float
Small float added to variance in Batch norm.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels_list,
kernel_size_list,
strides_list,
padding_list,
bn_epsilon,
bn_use_global_stats,
**kwargs):
super(ConvSeqBranch, self).__init__(**kwargs)
assert (len(out_channels_list) == len(kernel_size_list))
assert (len(out_channels_list) == len(strides_list))
assert (len(out_channels_list) == len(padding_list))
with self.name_scope():
self.conv_list = nn.HybridSequential(prefix="")
for out_channels, kernel_size, strides, padding in zip(
out_channels_list, kernel_size_list, strides_list, padding_list):
self.conv_list.add(ConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
def hybrid_forward(self, F, x):
x = self.conv_list(x)
return x
class ConvSeq3x3Branch(HybridBlock):
"""
InceptionV3 specific convolutional sequence branch block with splitting by 3x3.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels_list : list of tuple of int
List of numbers of output channels.
kernel_size_list : list of tuple of int or tuple of tuple/list of 2 int
List of convolution window sizes.
strides_list : list of tuple of int or tuple of tuple/list of 2 int
List of strides of the convolution.
padding_list : list of tuple of int or tuple of tuple/list of 2 int
List of padding values for convolution layers.
bn_epsilon : float
Small float added to variance in Batch norm.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels_list,
kernel_size_list,
strides_list,
padding_list,
bn_epsilon,
bn_use_global_stats,
**kwargs):
super(ConvSeq3x3Branch, self).__init__(**kwargs)
with self.name_scope():
self.conv_list = nn.HybridSequential(prefix="")
for out_channels, kernel_size, strides, padding in zip(
out_channels_list, kernel_size_list, strides_list, padding_list):
self.conv_list.add(ConvBlock(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.conv1x3 = ConvBlock(
in_channels=in_channels,
out_channels=in_channels,
kernel_size=(1, 3),
strides=1,
padding=(0, 1),
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats)
self.conv3x1 = ConvBlock(
in_channels=in_channels,
out_channels=in_channels,
kernel_size=(3, 1),
strides=1,
padding=(1, 0),
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats)
def hybrid_forward(self, F, x):
x = self.conv_list(x)
y1 = self.conv1x3(x)
y2 = self.conv3x1(x)
x = F.concat(y1, y2, dim=1)
return x
class InceptionAUnit(HybridBlock):
"""
InceptionV3 type Inception-A unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_epsilon : float
Small float added to variance in Batch norm.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_epsilon,
bn_use_global_stats,
**kwargs):
super(InceptionAUnit, self).__init__(**kwargs)
assert (out_channels > 224)
pool_out_channels = out_channels - 224
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(Conv1x1Branch(
in_channels=in_channels,
out_channels=64,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(48, 64),
kernel_size_list=(1, 5),
strides_list=(1, 1),
padding_list=(0, 2),
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(64, 96, 96),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 1),
padding_list=(0, 1, 1),
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(AvgPoolBranch(
in_channels=in_channels,
out_channels=pool_out_channels,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
def hybrid_forward(self, F, x):
x = self.branches(x)
return x
class ReductionAUnit(HybridBlock):
"""
InceptionV3 type Reduction-A unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_epsilon : float
Small float added to variance in Batch norm.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_epsilon,
bn_use_global_stats,
**kwargs):
super(ReductionAUnit, self).__init__(**kwargs)
assert (in_channels == 288)
assert (out_channels == 768)
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(384,),
kernel_size_list=(3,),
strides_list=(2,),
padding_list=(0,),
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(64, 96, 96),
kernel_size_list=(1, 3, 3),
strides_list=(1, 1, 2),
padding_list=(0, 1, 0),
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(MaxPoolBranch())
def hybrid_forward(self, F, x):
x = self.branches(x)
return x
class InceptionBUnit(HybridBlock):
"""
InceptionV3 type Inception-B unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
mid_channels : int
Number of output channels in the 7x7 branches.
bn_epsilon : float
Small float added to variance in Batch norm.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
mid_channels,
bn_epsilon,
bn_use_global_stats,
**kwargs):
super(InceptionBUnit, self).__init__(**kwargs)
assert (in_channels == 768)
assert (out_channels == 768)
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(Conv1x1Branch(
in_channels=in_channels,
out_channels=192,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(mid_channels, mid_channels, 192),
kernel_size_list=(1, (1, 7), (7, 1)),
strides_list=(1, 1, 1),
padding_list=(0, (0, 3), (3, 0)),
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(mid_channels, mid_channels, mid_channels, mid_channels, 192),
kernel_size_list=(1, (7, 1), (1, 7), (7, 1), (1, 7)),
strides_list=(1, 1, 1, 1, 1),
padding_list=(0, (3, 0), (0, 3), (3, 0), (0, 3)),
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(AvgPoolBranch(
in_channels=in_channels,
out_channels=192,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
def hybrid_forward(self, F, x):
x = self.branches(x)
return x
class ReductionBUnit(HybridBlock):
"""
InceptionV3 type Reduction-B unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_epsilon : float
Small float added to variance in Batch norm.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_epsilon,
bn_use_global_stats,
**kwargs):
super(ReductionBUnit, self).__init__(**kwargs)
assert (in_channels == 768)
assert (out_channels == 1280)
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(192, 320),
kernel_size_list=(1, 3),
strides_list=(1, 2),
padding_list=(0, 0),
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(ConvSeqBranch(
in_channels=in_channels,
out_channels_list=(192, 192, 192, 192),
kernel_size_list=(1, (1, 7), (7, 1), 3),
strides_list=(1, 1, 1, 2),
padding_list=(0, (0, 3), (3, 0), 0),
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(MaxPoolBranch())
def hybrid_forward(self, F, x):
x = self.branches(x)
return x
class InceptionCUnit(HybridBlock):
"""
InceptionV3 type Inception-C unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_epsilon : float
Small float added to variance in Batch norm.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_epsilon,
bn_use_global_stats,
**kwargs):
super(InceptionCUnit, self).__init__(**kwargs)
assert (out_channels == 2048)
with self.name_scope():
self.branches = HybridConcurrent(axis=1, prefix="")
self.branches.add(Conv1x1Branch(
in_channels=in_channels,
out_channels=320,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(ConvSeq3x3Branch(
in_channels=in_channels,
out_channels_list=(384,),
kernel_size_list=(1,),
strides_list=(1,),
padding_list=(0,),
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(ConvSeq3x3Branch(
in_channels=in_channels,
out_channels_list=(448, 384),
kernel_size_list=(1, 3),
strides_list=(1, 1),
padding_list=(0, 1),
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
self.branches.add(AvgPoolBranch(
in_channels=in_channels,
out_channels=192,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
def hybrid_forward(self, F, x):
x = self.branches(x)
return x
class InceptInitBlock(HybridBlock):
"""
InceptionV3 specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
bn_epsilon : float
Small float added to variance in Batch norm.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""
def __init__(self,
in_channels,
out_channels,
bn_epsilon,
bn_use_global_stats,
**kwargs):
super(InceptInitBlock, self).__init__(**kwargs)
assert (out_channels == 192)
with self.name_scope():
self.conv1 = conv3x3_block(
in_channels=in_channels,
out_channels=32,
strides=2,
padding=0,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats)
self.conv2 = conv3x3_block(
in_channels=32,
out_channels=32,
strides=1,
padding=0,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats)
self.conv3 = conv3x3_block(
in_channels=32,
out_channels=64,
strides=1,
padding=1,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats)
self.pool1 = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=0)
self.conv4 = conv1x1_block(
in_channels=64,
out_channels=80,
strides=1,
padding=0,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats)
self.conv5 = conv3x3_block(
in_channels=80,
out_channels=192,
strides=1,
padding=0,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats)
self.pool2 = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=0)
def hybrid_forward(self, F, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.pool1(x)
x = self.conv4(x)
x = self.conv5(x)
x = self.pool2(x)
return x
class InceptionV3(HybridBlock):
"""
InceptionV3 model from 'Rethinking the Inception Architecture for Computer Vision,'
https://arxiv.org/abs/1512.00567.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
b_mid_channels : list of int
Number of middle channels for each Inception-B unit.
dropout_rate : float, default 0.0
Fraction of the input units to drop. Must be a number between 0 and 1.
bn_epsilon : float, default 1e-5
Small float added to variance in Batch norm.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (299, 299)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
b_mid_channels,
dropout_rate=0.5,
bn_epsilon=1e-5,
bn_use_global_stats=False,
in_channels=3,
in_size=(299, 299),
classes=1000,
**kwargs):
super(InceptionV3, self).__init__(**kwargs)
self.in_size = in_size
self.classes = classes
normal_units = [InceptionAUnit, InceptionBUnit, InceptionCUnit]
reduction_units = [ReductionAUnit, ReductionBUnit]
with self.name_scope():
self.features = nn.HybridSequential(prefix="")
self.features.add(InceptInitBlock(
in_channels=in_channels,
out_channels=init_block_channels,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix="stage{}_".format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
if (j == 0) and (i != 0):
unit = reduction_units[i - 1]
else:
unit = normal_units[i]
if unit == InceptionBUnit:
stage.add(unit(
in_channels=in_channels,
out_channels=out_channels,
mid_channels=b_mid_channels[j - 1],
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
else:
stage.add(unit(
in_channels=in_channels,
out_channels=out_channels,
bn_epsilon=bn_epsilon,
bn_use_global_stats=bn_use_global_stats))
in_channels = out_channels
self.features.add(stage)
self.features.add(nn.AvgPool2D(
pool_size=8,
strides=1))
self.output = nn.HybridSequential(prefix="")
self.output.add(nn.Flatten())
self.output.add(nn.Dropout(rate=dropout_rate))
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_inceptionv3(model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create InceptionV3 model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
init_block_channels = 192
channels = [[256, 288, 288],
[768, 768, 768, 768, 768],
[1280, 2048, 2048]]
b_mid_channels = [128, 160, 160, 192]
net = InceptionV3(
channels=channels,
init_block_channels=init_block_channels,
b_mid_channels=b_mid_channels,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def inceptionv3(**kwargs):
"""
InceptionV3 model from 'Rethinking the Inception Architecture for Computer Vision,'
https://arxiv.org/abs/1512.00567.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_inceptionv3(model_name="inceptionv3", bn_epsilon=1e-3, **kwargs)
def inceptionv3_gl(**kwargs):
"""
InceptionV3 model (Gluon-like) from 'Rethinking the Inception Architecture for Computer Vision,'
https://arxiv.org/abs/1512.00567.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_inceptionv3(model_name="inceptionv3_gl", bn_epsilon=1e-5, **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
inceptionv3,
inceptionv3_gl,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != inceptionv3 or weight_count == 23834568)
assert (model != inceptionv3_gl or weight_count == 23834568)
x = mx.nd.zeros((1, 3, 299, 299), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 27,784 | 33.644638 | 115 | py |
imgclsmob | imgclsmob-master/gluon/gluoncv2/models/fdmobilenet.py | """
FD-MobileNet for ImageNet-1K, implemented in Gluon.
Original paper: 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
"""
__all__ = ['fdmobilenet_w1', 'fdmobilenet_w3d4', 'fdmobilenet_wd2', 'fdmobilenet_wd4', 'get_fdmobilenet']
import os
from mxnet import cpu
from .mobilenet import MobileNet
def get_fdmobilenet(width_scale,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join("~", ".mxnet", "models"),
**kwargs):
"""
Create FD-MobileNet model with specific parameters.
Parameters:
----------
width_scale : float
Scale factor for width of layers.
model_name : str or None, default None
Model name for loading pretrained model.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
channels = [[32], [64], [128, 128], [256, 256], [512, 512, 512, 512, 512, 1024]]
first_stage_stride = True
if width_scale != 1.0:
channels = [[int(cij * width_scale) for cij in ci] for ci in channels]
net = MobileNet(
channels=channels,
first_stage_stride=first_stage_stride,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def fdmobilenet_w1(**kwargs):
"""
FD-MobileNet 1.0x model from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_fdmobilenet(width_scale=1.0, model_name="fdmobilenet_w1", **kwargs)
def fdmobilenet_w3d4(**kwargs):
"""
FD-MobileNet 0.75x model from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_fdmobilenet(width_scale=0.75, model_name="fdmobilenet_w3d4", **kwargs)
def fdmobilenet_wd2(**kwargs):
"""
FD-MobileNet 0.5x model from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_fdmobilenet(width_scale=0.5, model_name="fdmobilenet_wd2", **kwargs)
def fdmobilenet_wd4(**kwargs):
"""
FD-MobileNet 0.25x model from 'FD-MobileNet: Improved MobileNet with A Fast Downsampling Strategy,'
https://arxiv.org/abs/1802.03750.
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.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_fdmobilenet(width_scale=0.25, model_name="fdmobilenet_wd4", **kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
fdmobilenet_w1,
fdmobilenet_w3d4,
fdmobilenet_wd2,
fdmobilenet_wd4,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != fdmobilenet_w1 or weight_count == 2901288)
assert (model != fdmobilenet_w3d4 or weight_count == 1833304)
assert (model != fdmobilenet_wd2 or weight_count == 993928)
assert (model != fdmobilenet_wd4 or weight_count == 383160)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| 5,360 | 30.910714 | 115 | py |
imgclsmob | imgclsmob-master/gluon/metrics/seg_metrics_nd.py | """
Routines for segmentation metrics on mx.ndarray.
"""
import numpy as np
import mxnet as mx
__all__ = ['seg_pixel_accuracy_nd', 'segm_mean_accuracy', 'segm_mean_iou', 'seg_mean_iou2_nd', 'segm_fw_iou',
'segm_fw_iou2']
def seg_pixel_accuracy_nd(label_imask,
pred_imask,
vague_idx=-1,
use_vague=False,
macro_average=True,
empty_result=0.0):
"""
The segmentation pixel accuracy (for MXNet nd-arrays).
Parameters:
----------
label_imask : mx.nd.array
Ground truth index mask (maybe batch of).
pred_imask : mx.nd.array
Predicted index mask (maybe batch of).
vague_idx : int, default -1
Index of masked pixels.
use_vague : bool, default False
Whether to use pixel masking.
macro_average : bool, default True
Whether to use micro or macro averaging.
empty_result : float, default 0.0
Result value for an image without any classes.
Returns:
-------
float or tuple of two floats
PA metric value.
"""
assert (label_imask.shape == pred_imask.shape)
if use_vague:
mask = (label_imask != vague_idx)
sum_u_ij = mask.sum().asscalar()
if sum_u_ij == 0:
if macro_average:
return empty_result
else:
return 0, 0
sum_u_ii = ((label_imask == pred_imask) * mask).sum().asscalar()
else:
sum_u_ii = (label_imask == pred_imask).sum().asscalar()
sum_u_ij = pred_imask.size
if macro_average:
return float(sum_u_ii) / sum_u_ij
else:
return sum_u_ii, sum_u_ij
def segm_mean_accuracy(label_hmask,
pred_imask):
"""
The segmentation mean accuracy.
Parameters:
----------
label_hmask : nd.array
Ground truth one-hot mask.
pred_imask : nd.array
Predicted index mask.
Returns:
-------
float
MA metric value.
"""
assert (len(label_hmask.shape) == 3)
assert (len(pred_imask.shape) == 2)
assert (pred_imask.shape == label_hmask.shape[1:])
n = label_hmask.shape[0]
i_sum = 0
acc_sum = 0.0
for i in range(n):
class_i_pred_mask = (pred_imask == i)
class_i_label_mask = label_hmask[i, :, :]
u_i = class_i_label_mask.sum().asscalar()
if u_i == 0:
continue
u_ii = (class_i_pred_mask * class_i_label_mask).sum().asscalar()
class_acc = float(u_ii) / u_i
acc_sum += class_acc
i_sum += 1
if i_sum > 0:
mean_acc = acc_sum / i_sum
else:
mean_acc = 1.0
return mean_acc
def segm_mean_iou(label_hmask,
pred_imask):
"""
The segmentation mean intersection over union.
Parameters:
----------
label_hmask : nd.array
Ground truth one-hot mask.
pred_imask : nd.array
Predicted index mask.
Returns:
-------
float
MIoU metric value.
"""
assert (len(label_hmask.shape) == 3)
assert (len(pred_imask.shape) == 2)
assert (pred_imask.shape == label_hmask.shape[1:])
n = label_hmask.shape[0]
i_sum = 0
acc_iou = 0.0
for i in range(n):
class_i_pred_mask = (pred_imask == i)
class_i_label_mask = label_hmask[i, :, :]
u_i = class_i_label_mask.sum().asscalar()
u_ji_sj = class_i_pred_mask.sum().asscalar()
if (u_i + u_ji_sj) == 0:
continue
u_ii = (class_i_pred_mask * class_i_label_mask).sum().asscalar()
acc_iou += float(u_ii) / (u_i + u_ji_sj - u_ii)
i_sum += 1
if i_sum > 0:
mean_iou = acc_iou / i_sum
else:
mean_iou = 1.0
return mean_iou
def seg_mean_iou2_nd(label_hmask,
pred_hmask):
"""
The segmentation mean intersection over union.
Parameters:
----------
label_hmask : nd.array
Ground truth one-hot mask (batch of).
pred_hmask : nd.array
Predicted one-hot mask (batch of).
Returns:
-------
float
MIoU metric value.
"""
assert (len(label_hmask.shape) == 4)
assert (len(pred_hmask.shape) == 4)
assert (pred_hmask.shape == label_hmask.shape)
eps = np.finfo(np.float32).eps
batch_axis = 0 # The axis that represents mini-batch
class_axis = 1 # The axis that represents classes
inter_hmask = label_hmask * pred_hmask
u_i = label_hmask.sum(axis=[batch_axis, class_axis], exclude=True)
u_ji_sj = pred_hmask.sum(axis=[batch_axis, class_axis], exclude=True)
u_ii = inter_hmask.sum(axis=[batch_axis, class_axis], exclude=True)
class_count = (u_i + u_ji_sj > 0.0).sum(axis=class_axis) + eps
class_acc = u_ii / (u_i + u_ji_sj - u_ii + eps)
acc_iou = class_acc.sum(axis=class_axis) + eps
mean_iou = (acc_iou / class_count).mean().asscalar()
return mean_iou
def segm_fw_iou(label_hmask,
pred_imask):
"""
The segmentation frequency weighted intersection over union.
Parameters:
----------
label_hmask : nd.array
Ground truth one-hot mask.
pred_imask : nd.array
Predicted index mask.
Returns:
-------
float
FrIoU metric value.
"""
assert (len(label_hmask.shape) == 3)
assert (len(pred_imask.shape) == 2)
assert (pred_imask.shape == label_hmask.shape[1:])
n = label_hmask.shape[0]
acc_iou = 0.0
for i in range(n):
class_i_pred_mask = (pred_imask == i)
class_i_label_mask = label_hmask[i, :, :]
u_i = class_i_label_mask.sum().asscalar()
u_ji_sj = class_i_pred_mask.sum().asscalar()
if (u_i + u_ji_sj) == 0:
continue
u_ii = (class_i_pred_mask * class_i_label_mask).sum().asscalar()
acc_iou += float(u_i) * float(u_ii) / (u_i + u_ji_sj - u_ii)
fw_factor = pred_imask.size
return acc_iou / fw_factor
def segm_fw_iou2(label_hmask,
pred_imask):
"""
The segmentation frequency weighted intersection over union.
Parameters:
----------
label_hmask : nd.array
Ground truth one-hot mask.
pred_imask : nd.array
Predicted index mask.
Returns:
-------
float
FrIoU metric value.
"""
assert (len(label_hmask.shape) == 3)
assert (len(pred_imask.shape) == 2)
assert (pred_imask.shape == label_hmask.shape[1:])
n = label_hmask.shape[0]
acc_iou = mx.nd.array([0.0], ctx=label_hmask.context)
for i in range(n):
class_i_pred_mask = (pred_imask == i)
class_i_label_mask = label_hmask[i, :, :]
u_i = class_i_label_mask.sum()
u_ji_sj = class_i_pred_mask.sum()
if (u_i + u_ji_sj).asscalar() == 0:
continue
u_ii = (class_i_pred_mask * class_i_label_mask).sum()
acc_iou += mx.nd.cast(u_i, dtype=np.float32) *\
mx.nd.cast(u_ii, dtype=np.float32) / mx.nd.cast(u_i + u_ji_sj - u_ii, dtype=np.float32)
fw_factor = pred_imask.size
return acc_iou.asscalar() / fw_factor
| 7,161 | 25.924812 | 109 | py |
imgclsmob | imgclsmob-master/gluon/metrics/seg_metrics.py | """
Evaluation Metrics for Semantic Segmentation.
"""
__all__ = ['PixelAccuracyMetric', 'MeanIoUMetric']
import numpy as np
import mxnet as mx
from .seg_metrics_np import seg_pixel_accuracy_np, seg_mean_iou_imasks_np
from .seg_metrics_nd import seg_pixel_accuracy_nd
class PixelAccuracyMetric(mx.metric.EvalMetric):
"""
Computes the pixel-wise accuracy.
Parameters:
----------
axis : int, default 1
The axis that represents classes.
name : str, default 'pix_acc'
Name of this metric instance for display.
output_names : list of str, or None, default None
Name of predictions that should be used when updating with update_dict.
By default include all predictions.
label_names : list of str, or None, default None
Name of labels that should be used when updating with update_dict.
By default include all labels.
on_cpu : bool, default True
Calculate on CPU.
sparse_label : bool, default True
Whether label is an integer array instead of probability distribution.
vague_idx : int, default -1
Index of masked pixels.
use_vague : bool, default False
Whether to use pixel masking.
macro_average : bool, default True
Whether to use micro or macro averaging.
aux : bool, default False
Whether to support auxiliary predictions.
"""
def __init__(self,
axis=1,
name="pix_acc",
output_names=None,
label_names=None,
on_cpu=True,
sparse_label=True,
vague_idx=-1,
use_vague=False,
macro_average=True,
aux=False):
if name == "pix_acc":
name = "{}-pix_acc".format("macro" if macro_average else "micro")
self.macro_average = macro_average
super(PixelAccuracyMetric, self).__init__(
name,
axis=axis,
output_names=output_names,
label_names=label_names)
self.axis = axis
self.on_cpu = on_cpu
self.sparse_label = sparse_label
self.vague_idx = vague_idx
self.use_vague = use_vague
self.aux = aux
def update(self, labels, preds):
"""
Updates the internal evaluation result.
Parameters:
----------
labels : list of `NDArray`
The labels of the data.
preds : list of `NDArray`
Predicted values.
"""
if self.aux:
preds = [p[0] for p in preds]
assert (len(labels) == len(preds))
if self.on_cpu:
for label, pred in zip(labels, preds):
if self.sparse_label:
label_imask = label.asnumpy().astype(np.int32)
else:
label_imask = mx.nd.argmax(label, axis=self.axis).asnumpy().astype(np.int32)
pred_imask = mx.nd.argmax(pred, axis=self.axis).asnumpy().astype(np.int32)
acc = seg_pixel_accuracy_np(
label_imask=label_imask,
pred_imask=pred_imask,
vague_idx=self.vague_idx,
use_vague=self.use_vague,
macro_average=self.macro_average)
if self.macro_average:
self.sum_metric += acc
self.num_inst += 1
else:
self.sum_metric += acc[0]
self.num_inst += acc[1]
else:
for label, pred in zip(labels, preds):
if self.sparse_label:
label_imask = mx.nd.cast(label, dtype=np.int32)
else:
label_imask = mx.nd.cast(mx.nd.argmax(label, axis=self.axis), dtype=np.int32)
pred_imask = mx.nd.cast(mx.nd.argmax(pred, axis=self.axis), dtype=np.int32)
acc = seg_pixel_accuracy_nd(
label_imask=label_imask,
pred_imask=pred_imask,
vague_idx=self.vague_idx,
use_vague=self.use_vague,
macro_average=self.macro_average)
if self.macro_average:
self.sum_metric += acc
self.num_inst += 1
else:
self.sum_metric += acc[0]
self.num_inst += acc[1]
def reset(self):
"""
Resets the internal evaluation result to initial state.
"""
if self.macro_average:
self.num_inst = 0
self.sum_metric = 0.0
else:
self.num_inst = 0
self.sum_metric = 0
def get(self):
"""
Gets the current evaluation result.
Returns:
-------
names : list of str
Name of the metrics.
values : list of float
Value of the evaluations.
"""
if self.macro_average:
if self.num_inst == 0:
return self.name, float("nan")
else:
return self.name, self.sum_metric / self.num_inst
else:
if self.num_inst == 0:
return self.name, float("nan")
else:
return self.name, float(self.sum_metric) / self.num_inst
class MeanIoUMetric(mx.metric.EvalMetric):
"""
Computes the mean intersection over union.
Parameters:
----------
axis : int, default 1
The axis that represents classes
name : str, default 'mean_iou'
Name of this metric instance for display.
output_names : list of str, or None, default None
Name of predictions that should be used when updating with update_dict.
By default include all predictions.
label_names : list of str, or None, default None
Name of labels that should be used when updating with update_dict.
By default include all labels.
on_cpu : bool, default True
Calculate on CPU.
sparse_label : bool, default True
Whether label is an integer array instead of probability distribution.
num_classes : int
Number of classes
vague_idx : int, default -1
Index of masked pixels.
use_vague : bool, default False
Whether to use pixel masking.
bg_idx : int, default -1
Index of background class.
ignore_bg : bool, default False
Whether to ignore background class.
macro_average : bool, default True
Whether to use micro or macro averaging.
"""
def __init__(self,
axis=1,
name="mean_iou",
output_names=None,
label_names=None,
on_cpu=True,
sparse_label=True,
num_classes=None,
vague_idx=-1,
use_vague=False,
bg_idx=-1,
ignore_bg=False,
macro_average=True):
if name == "pix_acc":
name = "{}-pix_acc".format("macro" if macro_average else "micro")
self.macro_average = macro_average
self.num_classes = num_classes
self.ignore_bg = ignore_bg
super(MeanIoUMetric, self).__init__(
name,
axis=axis,
output_names=output_names,
label_names=label_names)
assert ((not ignore_bg) or (bg_idx in (0, num_classes - 1)))
self.axis = axis
self.on_cpu = on_cpu
self.sparse_label = sparse_label
self.vague_idx = vague_idx
self.use_vague = use_vague
self.bg_idx = bg_idx
assert (on_cpu and sparse_label)
def update(self, labels, preds):
"""
Updates the internal evaluation result.
Parameters:
----------
labels : list of `NDArray`
The labels of the data.
preds : list of `NDArray`
Predicted values.
"""
assert (len(labels) == len(preds))
if self.on_cpu:
for label, pred in zip(labels, preds):
if self.sparse_label:
label_imask = label.asnumpy().astype(np.int32)
# else:
# label_hmask = label.asnumpy().astype(np.int32)
pred_imask = mx.nd.argmax(pred, axis=self.axis).asnumpy().astype(np.int32)
batch_size = label.shape[0]
for k in range(batch_size):
if self.sparse_label:
acc = seg_mean_iou_imasks_np(
label_imask=label_imask[k, :, :],
pred_imask=pred_imask[k, :, :],
num_classes=self.num_classes,
vague_idx=self.vague_idx,
use_vague=self.use_vague,
bg_idx=self.bg_idx,
ignore_bg=self.ignore_bg,
macro_average=self.macro_average)
# else:
# acc = seg_mean_iou_np(
# label_hmask=label_hmask[k, :, :, :],
# pred_imask=pred_imask[k, :, :])
if self.macro_average:
self.sum_metric += acc
self.num_inst += 1
else:
self.area_inter += acc[0]
self.area_union += acc[1]
# else:
# for label, pred in zip(labels, preds):
# if self.sparse_label:
# label_imask = label
# n = self.num_classes
# label_hmask = mx.nd.one_hot(label_imask, depth=n).transpose((0, 3, 1, 2))
# else:
# label_hmask = label
# n = label_hmask.shape[1]
# pred_imask = mx.nd.argmax(pred, axis=self.axis)
# pred_hmask = mx.nd.one_hot(pred_imask, depth=n).transpose((0, 3, 1, 2))
# acc = seg_mean_iou2_nd(
# label_hmask=label_hmask,
# pred_hmask=pred_hmask)
# self.sum_metric += acc
# self.num_inst += 1
def reset(self):
"""
Resets the internal evaluation result to initial state.
"""
if self.macro_average:
self.num_inst = 0
self.sum_metric = 0.0
else:
class_count = self.num_classes - 1 if self.ignore_bg else self.num_classes
self.area_inter = np.zeros((class_count,), np.uint64)
self.area_union = np.zeros((class_count,), np.uint64)
def get(self):
"""
Gets the current evaluation result.
Returns:
-------
names : list of str
Name of the metrics.
values : list of float
Value of the evaluations.
"""
if self.macro_average:
if self.num_inst == 0:
return self.name, float("nan")
else:
return self.name, self.sum_metric / self.num_inst
else:
class_count = (self.area_union > 0).sum()
if class_count == 0:
return self.name, float("nan")
eps = np.finfo(np.float32).eps
area_union_eps = self.area_union + eps
mean_iou = (self.area_inter / area_union_eps).sum() / class_count
return self.name, mean_iou
| 11,492 | 35.485714 | 97 | py |
imgclsmob | imgclsmob-master/gluon/metrics/cls_metrics.py | """
Evaluation Metrics for Image Classification.
"""
import mxnet as mx
__all__ = ['Top1Error', 'TopKError']
class Top1Error(mx.metric.Accuracy):
"""
Computes top-1 error (inverted accuracy classification score).
Parameters:
----------
axis : int, default 1
The axis that represents classes.
name : str, default 'top_1_error'
Name of this metric instance for display.
output_names : list of str, or None, default None
Name of predictions that should be used when updating with update_dict.
By default include all predictions.
label_names : list of str, or None, default None
Name of labels that should be used when updating with update_dict.
By default include all labels.
"""
def __init__(self,
axis=1,
name="top_1_error",
output_names=None,
label_names=None):
super(Top1Error, self).__init__(
axis=axis,
name=name,
output_names=output_names,
label_names=label_names)
def get(self):
"""
Gets the current evaluation result.
Returns:
-------
names : list of str
Name of the metrics.
values : list of float
Value of the evaluations.
"""
if self.num_inst == 0:
return self.name, float("nan")
else:
return self.name, 1.0 - self.sum_metric / self.num_inst
class TopKError(mx.metric.TopKAccuracy):
"""
Computes top-k error (inverted top k predictions accuracy).
Parameters:
----------
top_k : int
Whether targets are out of top k predictions, default 1
name : str, default 'top_k_error'
Name of this metric instance for display.
output_names : list of str, or None, default None
Name of predictions that should be used when updating with update_dict.
By default include all predictions.
label_names : list of str, or None, default None
Name of labels that should be used when updating with update_dict.
By default include all labels.
"""
def __init__(self,
top_k=1,
name="top_k_error",
output_names=None,
label_names=None):
name_ = name
super(TopKError, self).__init__(
top_k=top_k,
name=name,
output_names=output_names,
label_names=label_names)
self.name = name_.replace("_k_", "_{}_".format(top_k))
def get(self):
"""
Gets the current evaluation result.
Returns:
-------
names : list of str
Name of the metrics.
values : list of float
Value of the evaluations.
"""
if self.num_inst == 0:
return self.name, float("nan")
else:
return self.name, 1.0 - self.sum_metric / self.num_inst
| 2,977 | 28.78 | 79 | py |
imgclsmob | imgclsmob-master/gluon/metrics/metrics.py | """
Evaluation metrics for common tasks.
"""
import mxnet as mx
if mx.__version__ < "2.0.0":
from mxnet.metric import EvalMetric
else:
from mxnet.gluon.metric import EvalMetric
__all__ = ['LossValue']
class LossValue(EvalMetric):
"""
Computes simple loss value fake metric.
Parameters:
----------
name : str
Name of this metric instance for display.
output_names : list of str, or None
Name of predictions that should be used when updating with update_dict.
By default include all predictions.
label_names : list of str, or None
Name of labels that should be used when updating with update_dict.
By default include all labels.
"""
def __init__(self,
name="loss",
output_names=None,
label_names=None):
super(LossValue, self).__init__(
name,
output_names=output_names,
label_names=label_names)
def update(self, labels, preds):
"""
Updates the internal evaluation result.
Parameters:
----------
labels : None
Unused argument.
preds : list of `NDArray`
Loss values.
"""
loss = sum([ll.mean().asscalar() for ll in preds]) / len(preds)
self.sum_metric += loss
self.global_sum_metric += loss
self.num_inst += 1
self.global_num_inst += 1
| 1,444 | 25.759259 | 79 | py |
imgclsmob | imgclsmob-master/gluon/metrics/det_metrics.py | """
Evaluation Metrics for Object Detection.
"""
import os
import math
import warnings
import numpy as np
import mxnet as mx
from collections import defaultdict
__all__ = ['CocoDetMApMetric', 'VOC07MApMetric', 'WiderfaceDetMetric']
class CocoDetMApMetric(mx.metric.EvalMetric):
"""
Detection metric for COCO bbox task.
Parameters:
----------
img_height : int
Processed image height.
coco_annotations_file_path : str
COCO anotation file path.
contiguous_id_to_json : list of int
Processed IDs.
validation_ids : bool, default False
Whether to use temporary file for estimation.
use_file : bool, default False
Whether to use temporary file for estimation.
score_thresh : float, default 0.05
Detection results with confident scores smaller than `score_thresh` will be discarded before saving to results.
data_shape : tuple of int, default is None
If `data_shape` is provided as (height, width), we will rescale bounding boxes when saving the predictions.
This is helpful when SSD/YOLO box predictions cannot be rescaled conveniently. Note that the data_shape must be
fixed for all validation images.
post_affine : a callable function with input signature (orig_w, orig_h, out_w, out_h)
If not None, the bounding boxes will be affine transformed rather than simply scaled.
name : str, default 'mAP'
Name of this metric instance for display.
"""
def __init__(self,
img_height,
coco_annotations_file_path,
contiguous_id_to_json,
validation_ids=None,
use_file=False,
score_thresh=0.05,
data_shape=None,
post_affine=None,
name="mAP"):
super(CocoDetMApMetric, self).__init__(name=name)
self.img_height = img_height
self.coco_annotations_file_path = coco_annotations_file_path
self.contiguous_id_to_json = contiguous_id_to_json
self.validation_ids = validation_ids
self.use_file = use_file
self.score_thresh = score_thresh
self.current_idx = 0
self.coco_result = []
if isinstance(data_shape, (tuple, list)):
assert len(data_shape) == 2, "Data shape must be (height, width)"
elif not data_shape:
data_shape = None
else:
raise ValueError("data_shape must be None or tuple of int as (height, width)")
self._data_shape = data_shape
if post_affine is not None:
assert self._data_shape is not None, "Using post affine transform requires data_shape"
self._post_affine = post_affine
else:
self._post_affine = None
from pycocotools.coco import COCO
self.gt = COCO(self.coco_annotations_file_path)
self._img_ids = sorted(self.gt.getImgIds())
def reset(self):
self.current_idx = 0
self.coco_result = []
def get(self):
"""
Get evaluation metrics.
"""
if self.current_idx != len(self._img_ids):
warnings.warn("Recorded {} out of {} validation images, incomplete results".format(
self.current_idx, len(self._img_ids)))
from pycocotools.coco import COCO
gt = COCO(self.coco_annotations_file_path)
import tempfile
import json
with tempfile.NamedTemporaryFile(mode="w", suffix=".json") as f:
json.dump(self.coco_result, f)
f.flush()
pred = gt.loadRes(f.name)
from pycocotools.cocoeval import COCOeval
coco_eval = COCOeval(gt, pred, "bbox")
if self.validation_ids is not None:
coco_eval.params.imgIds = self.validation_ids
coco_eval.evaluate()
coco_eval.accumulate()
coco_eval.summarize()
return self.name, tuple(coco_eval.stats[:3])
def update2(self,
pred_bboxes,
pred_labels,
pred_scores):
"""
Update internal buffer with latest predictions. Note that the statistics are not available until you call
self.get() to return the metrics.
Parameters:
----------
pred_bboxes : mxnet.NDArray or np.ndarray
Prediction bounding boxes with shape `B, N, 4`.
Where B is the size of mini-batch, N is the number of bboxes.
pred_labels : mxnet.NDArray or np.ndarray
Prediction bounding boxes labels with shape `B, N`.
pred_scores : mxnet.NDArray or np.ndarray
Prediction bounding boxes scores with shape `B, N`.
"""
def as_numpy(a):
"""
Convert a (list of) mx.NDArray into np.ndarray
"""
if isinstance(a, (list, tuple)):
out = [x.asnumpy() if isinstance(x, mx.nd.NDArray) else x for x in a]
return np.concatenate(out, axis=0)
elif isinstance(a, mx.nd.NDArray):
a = a.asnumpy()
return a
for pred_bbox, pred_label, pred_score in zip(*[as_numpy(x) for x in [pred_bboxes, pred_labels, pred_scores]]):
valid_pred = np.where(pred_label.flat >= 0)[0]
pred_bbox = pred_bbox[valid_pred, :].astype(np.float)
pred_label = pred_label.flat[valid_pred].astype(int)
pred_score = pred_score.flat[valid_pred].astype(np.float)
imgid = self._img_ids[self.current_idx]
self.current_idx += 1
affine_mat = None
if self._data_shape is not None:
entry = self.gt.loadImgs(imgid)[0]
orig_height = entry["height"]
orig_width = entry["width"]
height_scale = float(orig_height) / self._data_shape[0]
width_scale = float(orig_width) / self._data_shape[1]
if self._post_affine is not None:
affine_mat = self._post_affine(orig_width, orig_height, self._data_shape[1], self._data_shape[0])
else:
height_scale, width_scale = (1.0, 1.0)
# for each bbox detection in each image
for bbox, label, score in zip(pred_bbox, pred_label, pred_score):
if label not in self.contiguous_id_to_json:
# ignore non-exist class
continue
if score < self.score_thresh:
continue
category_id = self.contiguous_id_to_json[label]
# rescale bboxes/affine transform bboxes
if affine_mat is not None:
bbox[0:2] = self.affine_transform(bbox[0:2], affine_mat)
bbox[2:4] = self.affine_transform(bbox[2:4], affine_mat)
else:
bbox[[0, 2]] *= width_scale
bbox[[1, 3]] *= height_scale
# convert [xmin, ymin, xmax, ymax] to [xmin, ymin, w, h]
bbox[2:4] -= (bbox[:2] - 1)
self.coco_result.append({"image_id": imgid,
"category_id": category_id,
"bbox": bbox[:4].tolist(),
"score": score})
def update(self, labels, preds):
"""
Updates the internal evaluation result.
Parameters:
----------
labels : list of `NDArray`
The labels of the data.
preds : list of `NDArray`
Predicted values.
"""
det_bboxes = []
det_ids = []
det_scores = []
for x_rr, y in zip(preds, labels):
bboxes = x_rr.slice_axis(axis=-1, begin=0, end=4)
ids = x_rr.slice_axis(axis=-1, begin=4, end=5).squeeze(axis=2)
scores = x_rr.slice_axis(axis=-1, begin=5, end=6).squeeze(axis=2)
det_ids.append(ids)
det_scores.append(scores)
# clip to image size
det_bboxes.append(bboxes.clip(0, self.img_height))
self.update2(det_bboxes, det_ids, det_scores)
@staticmethod
def affine_transform(pt, t):
"""
Apply affine transform to a bounding box given transform matrix t.
Parameters:
----------
pt : np.ndarray
Bounding box with shape (1, 2).
t : np.ndarray
Transformation matrix with shape (2, 3).
Returns:
-------
np.ndarray
New bounding box with shape (1, 2).
"""
new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32).T
new_pt = np.dot(t, new_pt)
return new_pt[:2]
class VOCMApMetric(mx.metric.EvalMetric):
"""
Calculate mean AP for object detection task
Parameters:
---------
iou_thresh : float
IOU overlap threshold for TP
class_names : list of str
optional, if provided, will print out AP for each class
name : str, default 'mAP'
Name of this metric instance for display.
"""
def __init__(self,
iou_thresh=0.5,
class_names=None,
name="mAP"):
super(VOCMApMetric, self).__init__(name=name)
if class_names is None:
self.num = None
else:
assert isinstance(class_names, (list, tuple))
for name in class_names:
assert isinstance(name, str), "must provide names as str"
num = len(class_names)
self.name = list(class_names) + ["mAP"]
self.num = num + 1
self.reset()
self.iou_thresh = iou_thresh
self.class_names = class_names
def reset(self):
"""
Clear the internal statistics to initial state.
"""
if getattr(self, 'num', None) is None:
self.num_inst = 0
self.sum_metric = 0.0
else:
self.num_inst = [0] * self.num
self.sum_metric = [0.0] * self.num
self._n_pos = defaultdict(int)
self._score = defaultdict(list)
self._match = defaultdict(list)
def get(self):
"""
Get the current evaluation result.
Returns:
-------
name : str
Name of the metric.
value : float
Value of the evaluation.
"""
self._update() # update metric at this time
if self.num is None:
if self.num_inst == 0:
return self.name, float("nan")
else:
return self.name, self.sum_metric / self.num_inst
else:
names = ["%s" % self.name[i] for i in range(self.num)]
values = [x / y if y != 0 else float("nan") for x, y in zip(self.sum_metric, self.num_inst)]
return names, values
def update(self,
pred_bboxes,
pred_labels,
pred_scores,
gt_bboxes,
gt_labels,
gt_difficults=None):
"""
Update internal buffer with latest prediction and gt pairs.
Parameters:
----------
pred_bboxes : mxnet.NDArray or np.ndarray
Prediction bounding boxes with shape `B, N, 4`.
Where B is the size of mini-batch, N is the number of bboxes.
pred_labels : mxnet.NDArray or np.ndarray
Prediction bounding boxes labels with shape `B, N`.
pred_scores : mxnet.NDArray or np.ndarray
Prediction bounding boxes scores with shape `B, N`.
gt_bboxes : mxnet.NDArray or np.ndarray
Ground-truth bounding boxes with shape `B, M, 4`.
Where B is the size of mini-batch, M is the number of ground-truths.
gt_labels : mxnet.NDArray or np.ndarray
Ground-truth bounding boxes labels with shape `B, M`.
gt_difficults : mxnet.NDArray or np.ndarray, optional, default is None
Ground-truth bounding boxes difficulty labels with shape `B, M`.
"""
def as_numpy(a):
"""
Convert a (list of) mx.NDArray into np.ndarray.
"""
if isinstance(a, (list, tuple)):
out = [x.asnumpy() if isinstance(x, mx.nd.NDArray) else x for x in a]
try:
out = np.concatenate(out, axis=0)
except ValueError:
out = np.array(out)
return out
elif isinstance(a, mx.nd.NDArray):
a = a.asnumpy()
return a
if gt_difficults is None:
gt_difficults = [None for _ in as_numpy(gt_labels)]
if isinstance(gt_labels, list):
gt_diff_shape = gt_difficults[0].shape[0] if hasattr(gt_difficults[0], "shape") else 0
if len(gt_difficults) * gt_diff_shape != \
len(gt_labels) * gt_labels[0].shape[0]:
gt_difficults = [None] * len(gt_labels) * gt_labels[0].shape[0]
for pred_bbox, pred_label, pred_score, gt_bbox, gt_label, gt_difficult in zip(
*[as_numpy(x) for x in [pred_bboxes, pred_labels, pred_scores,
gt_bboxes, gt_labels, gt_difficults]]):
# strip padding -1 for pred and gt
valid_pred = np.where(pred_label.flat >= 0)[0]
pred_bbox = pred_bbox[valid_pred, :]
pred_label = pred_label.flat[valid_pred].astype(int)
pred_score = pred_score.flat[valid_pred]
valid_gt = np.where(gt_label.flat >= 0)[0]
gt_bbox = gt_bbox[valid_gt, :]
gt_label = gt_label.flat[valid_gt].astype(int)
if gt_difficult is None:
gt_difficult = np.zeros(gt_bbox.shape[0])
else:
gt_difficult = gt_difficult.flat[valid_gt]
for ll in np.unique(np.concatenate((pred_label, gt_label)).astype(int)):
pred_mask_l = pred_label == ll
pred_bbox_l = pred_bbox[pred_mask_l]
pred_score_l = pred_score[pred_mask_l]
# sort by score
order = pred_score_l.argsort()[::-1]
pred_bbox_l = pred_bbox_l[order]
pred_score_l = pred_score_l[order]
gt_mask_l = gt_label == ll
gt_bbox_l = gt_bbox[gt_mask_l]
gt_difficult_l = gt_difficult[gt_mask_l]
self._n_pos[ll] += np.logical_not(gt_difficult_l).sum()
self._score[ll].extend(pred_score_l)
if len(pred_bbox_l) == 0:
continue
if len(gt_bbox_l) == 0:
self._match[ll].extend((0,) * pred_bbox_l.shape[0])
continue
# VOC evaluation follows integer typed bounding boxes.
pred_bbox_l = pred_bbox_l.copy()
pred_bbox_l[:, 2:] += 1
gt_bbox_l = gt_bbox_l.copy()
gt_bbox_l[:, 2:] += 1
iou = self.bbox_iou(pred_bbox_l, gt_bbox_l)
gt_index = iou.argmax(axis=1)
# set -1 if there is no matching ground truth
gt_index[iou.max(axis=1) < self.iou_thresh] = -1
del iou
selec = np.zeros(gt_bbox_l.shape[0], dtype=bool)
for gt_idx in gt_index:
if gt_idx >= 0:
if gt_difficult_l[gt_idx]:
self._match[ll].append(-1)
else:
if not selec[gt_idx]:
self._match[ll].append(1)
else:
self._match[ll].append(0)
selec[gt_idx] = True
else:
self._match[ll].append(0)
def _update(self):
"""
Update num_inst and sum_metric.
"""
aps = []
recall, precs = self._recall_prec()
for ll, rec, prec in zip(range(len(precs)), recall, precs):
ap = self._average_precision(rec, prec)
aps.append(ap)
if self.num is not None and ll < (self.num - 1):
self.sum_metric[ll] = ap
self.num_inst[ll] = 1
if self.num is None:
self.num_inst = 1
self.sum_metric = np.nanmean(aps)
else:
self.num_inst[-1] = 1
self.sum_metric[-1] = np.nanmean(aps)
def _recall_prec(self):
"""
Get recall and precision from internal records.
"""
n_fg_class = max(self._n_pos.keys()) + 1
prec = [None] * n_fg_class
rec = [None] * n_fg_class
for ll in self._n_pos.keys():
score_l = np.array(self._score[ll])
match_l = np.array(self._match[ll], dtype=np.int32)
order = score_l.argsort()[::-1]
match_l = match_l[order]
tp = np.cumsum(match_l == 1)
fp = np.cumsum(match_l == 0)
# If an element of fp + tp is 0,
# the corresponding element of prec[ll] is nan.
with np.errstate(divide="ignore", invalid="ignore"):
prec[ll] = tp / (fp + tp)
# If n_pos[ll] is 0, rec[ll] is None.
if self._n_pos[ll] > 0:
rec[ll] = tp / self._n_pos[ll]
return rec, prec
def _average_precision(self,
rec,
prec):
"""
Calculate average precision.
Params:
----------
rec : np.array
cumulated recall
prec : np.array
cumulated precision
Returns:
----------
float
AP
"""
if rec is None or prec is None:
return np.nan
# append sentinel values at both ends
mrec = np.concatenate(([0.0], rec, [1.0]))
mpre = np.concatenate(([0.0], np.nan_to_num(prec), [0.0]))
# compute precision integration ladder
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
# look for recall value changes
i = np.where(mrec[1:] != mrec[:-1])[0]
# sum (\delta recall) * prec
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap
@staticmethod
def bbox_iou(bbox_a, bbox_b, offset=0):
"""
Calculate Intersection-Over-Union(IOU) of two bounding boxes.
Parameters:
----------
bbox_a : np.ndarray
An ndarray with shape :math:`(N, 4)`.
bbox_b : np.ndarray
An ndarray with shape :math:`(M, 4)`.
offset : float or int, default is 0
The ``offset`` is used to control the whether the width(or height) is computed as
(right - left + ``offset``).
Note that the offset must be 0 for normalized bboxes, whose ranges are in ``[0, 1]``.
Returns:
-------
np.ndarray
An ndarray with shape :math:`(N, M)` indicates IOU between each pairs of
bounding boxes in `bbox_a` and `bbox_b`.
"""
if bbox_a.shape[1] < 4 or bbox_b.shape[1] < 4:
raise IndexError("Bounding boxes axis 1 must have at least length 4")
tl = np.maximum(bbox_a[:, None, :2], bbox_b[:, :2])
br = np.minimum(bbox_a[:, None, 2:4], bbox_b[:, 2:4])
area_i = np.prod(br - tl + offset, axis=2) * (tl < br).all(axis=2)
area_a = np.prod(bbox_a[:, 2:4] - bbox_a[:, :2] + offset, axis=1)
area_b = np.prod(bbox_b[:, 2:4] - bbox_b[:, :2] + offset, axis=1)
return area_i / (area_a[:, None] + area_b - area_i)
class VOC07MApMetric(VOCMApMetric):
"""
Mean average precision metric for PASCAL V0C 07 dataset.
Parameters:
---------
iou_thresh : float
IOU overlap threshold for TP
class_names : list of str
optional, if provided, will print out AP for each class
"""
def __init__(self, *args, **kwargs):
super(VOC07MApMetric, self).__init__(*args, **kwargs)
def _average_precision(self, rec, prec):
"""
calculate average precision, override the default one,
special 11-point metric
Params:
----------
rec : np.array
cumulated recall
prec : np.array
cumulated precision
Returns:
----------
float
AP
"""
if rec is None or prec is None:
return np.nan
ap = 0.0
for t in np.arange(0.0, 1.1, 0.1):
if np.sum(rec >= t) == 0:
p = 0
else:
p = np.max(np.nan_to_num(prec)[rec >= t])
ap += p / 11.0
return ap
class WiderfaceDetMetric(mx.metric.EvalMetric):
"""
Detection metric for WIDER FACE detection task.
Parameters:
----------
receptive_field_center_starts : list of int
The start location of the first receptive field of each scale.
receptive_field_strides : list of int
Receptive field stride for each scale.
bbox_factors : list of float
A half of bbox upper bound for each scale.
output_dir_path : str
Output file path.
name : str, default 'WF'
Name of this metric instance for display.
"""
def __init__(self,
receptive_field_center_starts,
receptive_field_strides,
bbox_factors,
output_dir_path,
name="WF"):
super(WiderfaceDetMetric, self).__init__(name=name)
self.receptive_field_center_starts = receptive_field_center_starts
self.receptive_field_strides = receptive_field_strides
self.bbox_factors = bbox_factors
self.output_dir_path = output_dir_path
self.num_output_scales = len(self.bbox_factors)
self.score_threshold = 0.11
self.nms_threshold = 0.4
self.top_k = 10000
def reset(self):
pass
def get(self):
"""
Get evaluation metrics.
"""
return self.name, 1.0
def update(self, labels, preds):
"""
Updates the internal evaluation result.
Parameters:
----------
labels : list of `NDArray`
The labels of the data.
preds : list of `NDArray`
Predicted values.
"""
for x_rr, label in zip(preds, labels):
outputs = []
for output in x_rr:
outputs.append(output.asnumpy())
label_split = label.split("/")
resize_scale = float(label_split[2])
image_size = (int(label_split[3]), int(label_split[4]))
bboxes, _ = self.predict(outputs, resize_scale, image_size)
event_name = label_split[0]
event_dir_name = os.path.join(self.output_dir_path, event_name)
if not os.path.exists(event_dir_name):
os.makedirs(event_dir_name)
file_stem = label_split[1]
fout = open(os.path.join(event_dir_name, file_stem + ".txt"), "w")
fout.write(file_stem + "\n")
fout.write(str(len(bboxes)) + "\n")
for bbox in bboxes:
fout.write("%d %d %d %d %.03f" % (math.floor(bbox[0]),
math.floor(bbox[1]),
math.ceil(bbox[2] - bbox[0]),
math.ceil(bbox[3] - bbox[1]),
bbox[4] if bbox[4] <= 1 else 1) + "\n")
fout.close()
def predict(self, outputs, resize_scale, image_size):
bbox_collection = []
for i in range(self.num_output_scales):
score_map = np.squeeze(outputs[i * 2], (0, 1))
bbox_map = np.squeeze(outputs[i * 2 + 1], 0)
RF_center_Xs = np.array(
[self.receptive_field_center_starts[i] + self.receptive_field_strides[i] * x for x in
range(score_map.shape[1])])
RF_center_Xs_mat = np.tile(RF_center_Xs, [score_map.shape[0], 1])
RF_center_Ys = np.array(
[self.receptive_field_center_starts[i] + self.receptive_field_strides[i] * y for y in
range(score_map.shape[0])])
RF_center_Ys_mat = np.tile(RF_center_Ys, [score_map.shape[1], 1]).T
x_lt_mat = RF_center_Xs_mat - bbox_map[0, :, :] * self.bbox_factors[i]
y_lt_mat = RF_center_Ys_mat - bbox_map[1, :, :] * self.bbox_factors[i]
x_rb_mat = RF_center_Xs_mat - bbox_map[2, :, :] * self.bbox_factors[i]
y_rb_mat = RF_center_Ys_mat - bbox_map[3, :, :] * self.bbox_factors[i]
x_lt_mat = x_lt_mat / resize_scale
x_lt_mat[x_lt_mat < 0] = 0
y_lt_mat = y_lt_mat / resize_scale
y_lt_mat[y_lt_mat < 0] = 0
x_rb_mat = x_rb_mat / resize_scale
x_rb_mat[x_rb_mat > image_size[1]] = image_size[1]
y_rb_mat = y_rb_mat / resize_scale
y_rb_mat[y_rb_mat > image_size[0]] = image_size[0]
select_index = np.where(score_map > self.score_threshold)
for idx in range(select_index[0].size):
bbox_collection.append((x_lt_mat[select_index[0][idx], select_index[1][idx]],
y_lt_mat[select_index[0][idx], select_index[1][idx]],
x_rb_mat[select_index[0][idx], select_index[1][idx]],
y_rb_mat[select_index[0][idx], select_index[1][idx]],
score_map[select_index[0][idx], select_index[1][idx]]))
# NMS
bbox_collection = sorted(bbox_collection, key=lambda item: item[-1], reverse=True)
if len(bbox_collection) > self.top_k:
bbox_collection = bbox_collection[0:self.top_k]
bbox_collection_numpy = np.array(bbox_collection, dtype=np.float32)
final_bboxes = self.nms(bbox_collection_numpy, self.nms_threshold)
final_bboxes_ = []
for i in range(final_bboxes.shape[0]):
final_bboxes_.append((final_bboxes[i, 0], final_bboxes[i, 1], final_bboxes[i, 2], final_bboxes[i, 3],
final_bboxes[i, 4]))
return final_bboxes_
@staticmethod
def nms(boxes, overlap_threshold):
if boxes.shape[0] == 0:
return boxes
if boxes.dtype != np.float32:
boxes = boxes.astype(np.float32)
pick = []
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
sc = boxes[:, 4]
widths = x2 - x1
heights = y2 - y1
area = heights * widths
idxs = np.argsort(sc)
while len(idxs) > 0:
last = len(idxs) - 1
i = idxs[last]
pick.append(i)
xx1 = np.maximum(x1[i], x1[idxs[:last]])
yy1 = np.maximum(y1[i], y1[idxs[:last]])
xx2 = np.minimum(x2[i], x2[idxs[:last]])
yy2 = np.minimum(y2[i], y2[idxs[:last]])
w = np.maximum(0, xx2 - xx1 + 1)
h = np.maximum(0, yy2 - yy1 + 1)
overlap = (w * h) / area[idxs[:last]]
idxs = np.delete(idxs, np.concatenate(([last], np.where(overlap > overlap_threshold)[0])))
return boxes[pick]
| 27,536 | 36.11186 | 119 | py |
imgclsmob | imgclsmob-master/gluon/metrics/hpe_metrics.py | """
Evaluation Metrics for Human Pose Estimation.
"""
import mxnet as mx
__all__ = ['CocoHpeOksApMetric']
class CocoHpeOksApMetric(mx.metric.EvalMetric):
"""
Detection metric for COCO bbox task.
Parameters:
----------
coco_annotations_file_path : str
COCO anotation file path.
pose_postprocessing_fn : func
An function for pose post-processing.
validation_ids : bool, default False
Whether to use temporary file for estimation.
use_file : bool, default False
Whether to use temporary file for estimation.
name : str, default 'CocoOksAp'
Name of this metric instance for display.
"""
def __init__(self,
coco_annotations_file_path,
pose_postprocessing_fn,
validation_ids=None,
use_file=False,
name="CocoOksAp"):
super(CocoHpeOksApMetric, self).__init__(name=name)
self.coco_annotations_file_path = coco_annotations_file_path
self.pose_postprocessing_fn = pose_postprocessing_fn
self.validation_ids = validation_ids
self.use_file = use_file
self.coco_result = []
def reset(self):
self.coco_result = []
def get(self):
"""
Get evaluation metrics.
"""
import copy
from pycocotools.coco import COCO
gt = COCO(self.coco_annotations_file_path)
if self.use_file:
import tempfile
import json
with tempfile.NamedTemporaryFile(mode="w", suffix=".json") as f:
json.dump(self.coco_result, f)
f.flush()
pred = gt.loadRes(f.name)
else:
def calc_pred(coco, anns):
import numpy as np
import copy
pred = COCO()
pred.dataset["images"] = [img for img in coco.dataset["images"]]
annsImgIds = [ann["image_id"] for ann in anns]
assert set(annsImgIds) == (set(annsImgIds) & set(coco.getImgIds()))
pred.dataset["categories"] = copy.deepcopy(coco.dataset["categories"])
for id, ann in enumerate(anns):
s = ann["keypoints"]
x = s[0::3]
y = s[1::3]
x0, x1, y0, y1 = np.min(x), np.max(x), np.min(y), np.max(y)
ann["area"] = (x1 - x0) * (y1 - y0)
ann["id"] = id + 1
ann["bbox"] = [x0, y0, x1 - x0, y1 - y0]
pred.dataset["annotations"] = anns
pred.createIndex()
return pred
pred = calc_pred(gt, copy.deepcopy(self.coco_result))
from pycocotools.cocoeval import COCOeval
coco_eval = COCOeval(gt, pred, "keypoints")
if self.validation_ids is not None:
coco_eval.params.imgIds = self.validation_ids
coco_eval.params.useSegm = None
coco_eval.evaluate()
coco_eval.accumulate()
coco_eval.summarize()
return self.name, tuple(coco_eval.stats[:3])
def update(self, labels, preds):
"""
Updates the internal evaluation result.
Parameters:
----------
labels : list of `NDArray`
The labels of the data.
preds : list of `NDArray`
Predicted values.
"""
for label, pred in zip(labels, preds):
label = label.asnumpy()
pred = pred.asnumpy()
pred_pts_score, pred_person_score, label_img_id = self.pose_postprocessing_fn(pred, label)
for idx in range(len(pred_pts_score)):
image_id = int(label_img_id[idx])
kpt = pred_pts_score[idx].flatten().tolist()
score = float(pred_person_score[idx])
self.coco_result.append({
"image_id": image_id,
"category_id": 1,
"keypoints": kpt,
"score": score})
| 4,037 | 32.371901 | 102 | py |
imgclsmob | imgclsmob-master/gluon/metrics/asr_metrics.py | """
Evaluation Metrics for Automatic Speech Recognition (ASR).
"""
import mxnet as mx
__all__ = ['WER']
class WER(mx.metric.EvalMetric):
"""
Computes Word Error Rate (WER) for Automatic Speech Recognition (ASR).
Parameters:
----------
vocabulary : list of str
Vocabulary of the dataset.
name : str, default 'wer'
Name of this metric instance for display.
output_names : list of str, or None, default None
Name of predictions that should be used when updating with update_dict.
By default include all predictions.
label_names : list of str, or None, default None
Name of labels that should be used when updating with update_dict.
By default include all labels.
"""
def __init__(self,
vocabulary,
name="wer",
output_names=None,
label_names=None):
super(WER, self).__init__(
name=name,
output_names=output_names,
label_names=label_names,
has_global_stats=True)
self.vocabulary = vocabulary
self.ctc_decoder = CtcDecoder(vocabulary=vocabulary)
def update(self, labels, preds):
"""
Updates the internal evaluation result.
Parameters:
----------
labels : list of `NDArray`
The labels of the data.
preds : list of `NDArray`
Predicted values.
"""
import editdistance
for labels_i, preds_i in zip(labels, preds):
labels_code = labels_i.asnumpy()
labels_i = []
for label_code in labels_code:
label_text = "".join([self.ctc_decoder.labels_map[c] for c in label_code])
labels_i.append(label_text)
preds_i = preds_i[0]
greedy_predictions = preds_i.swapaxes(1, 2).log_softmax(axis=-1).argmax(axis=-1, keepdims=False).asnumpy()
preds_i = self.ctc_decoder(greedy_predictions)
assert (len(labels_i) == len(preds_i))
for pred, label in zip(preds_i, labels_i):
pred = pred.split()
label = label.split()
word_error_count = editdistance.eval(label, pred)
word_count = max(len(label), len(pred))
assert (word_error_count <= word_count)
self.sum_metric += word_error_count
self.global_sum_metric += word_error_count
self.num_inst += word_count
self.global_num_inst += word_count
class CtcDecoder(object):
"""
CTC decoder (to decode a sequence of labels to words).
Parameters:
----------
vocabulary : list of str
Vocabulary of the dataset.
"""
def __init__(self,
vocabulary):
super().__init__()
self.blank_id = len(vocabulary)
self.labels_map = dict([(i, vocabulary[i]) for i in range(len(vocabulary))])
def __call__(self,
predictions):
"""
Decode a sequence of labels to words.
Parameters:
----------
predictions : np.array of int or list of list of int
Tensor with predicted labels.
Returns:
-------
list of str
Words.
"""
hypotheses = []
for prediction in predictions:
decoded_prediction = []
previous = self.blank_id
for p in prediction:
if (p != previous or previous == self.blank_id) and p != self.blank_id:
decoded_prediction.append(p)
previous = p
hypothesis = "".join([self.labels_map[c] for c in decoded_prediction])
hypotheses.append(hypothesis)
return hypotheses
| 3,800 | 30.413223 | 118 | py |
imgclsmob | imgclsmob-master/gluon/datasets/imagenet1k_cls_dataset.py | """
ImageNet-1K classification dataset.
"""
import os
import math
import mxnet as mx
from mxnet.gluon import HybridBlock
from mxnet.gluon.data.vision import ImageFolderDataset
from mxnet.gluon.data.vision import transforms
from .dataset_metainfo import DatasetMetaInfo
class ImageNet1K(ImageFolderDataset):
"""
ImageNet-1K classification dataset.
Refer to MXNet documentation for the description of this dataset and how to prepare it.
Parameters:
----------
root : str, default '~/.mxnet/datasets/imagenet'
Path to the folder stored the dataset.
mode : str, default 'train'
'train', 'val', or 'test'.
transform : function, default None
A function that takes data and label and transforms them.
"""
def __init__(self,
root=os.path.join("~", ".mxnet", "datasets", "imagenet"),
mode="train",
transform=None):
split = "train" if mode == "train" else "val"
root = os.path.join(root, split)
super(ImageNet1K, self).__init__(root=root, flag=1, transform=transform)
class ImageNet1KMetaInfo(DatasetMetaInfo):
"""
Descriptor of ImageNet-1K dataset.
"""
def __init__(self):
super(ImageNet1KMetaInfo, self).__init__()
self.label = "ImageNet1K"
self.short_label = "imagenet"
self.root_dir_name = "imagenet"
self.dataset_class = ImageNet1K
self.num_training_samples = None
self.in_channels = 3
self.num_classes = 1000
self.input_image_size = (224, 224)
self.resize_inv_factor = 0.875
self.aug_type = "aug0"
self.train_metric_capts = ["Train.Top1"]
self.train_metric_names = ["Top1Error"]
self.train_metric_extra_kwargs = [{"name": "err-top1"}]
self.val_metric_capts = ["Val.Top1", "Val.Top5"]
self.val_metric_names = ["Top1Error", "TopKError"]
self.val_metric_extra_kwargs = [{"name": "err-top1"}, {"name": "err-top5", "top_k": 5}]
self.saver_acc_ind = 1
self.train_transform = imagenet_train_transform
self.val_transform = imagenet_val_transform
self.test_transform = imagenet_val_transform
self.ml_type = "imgcls"
self.mean_rgb = (0.485, 0.456, 0.406)
self.std_rgb = (0.229, 0.224, 0.225)
self.interpolation = 1
self.loss_name = "SoftmaxCrossEntropy"
def add_dataset_parser_arguments(self,
parser,
work_dir_path):
"""
Create python script parameters (for ImageNet-1K dataset metainfo).
Parameters:
----------
parser : ArgumentParser
ArgumentParser instance.
work_dir_path : str
Path to working directory.
"""
super(ImageNet1KMetaInfo, self).add_dataset_parser_arguments(parser, work_dir_path)
parser.add_argument(
"--input-size",
type=int,
default=self.input_image_size[0],
help="size of the input for model")
parser.add_argument(
"--resize-inv-factor",
type=float,
default=self.resize_inv_factor,
help="inverted ratio for input image crop")
parser.add_argument(
"--aug-type",
type=str,
default="aug0",
help="augmentation type. options are aug0, aug1, aug2")
parser.add_argument(
"--mean-rgb",
nargs=3,
type=float,
default=self.mean_rgb,
help="Mean of RGB channels in the dataset")
parser.add_argument(
"--std-rgb",
nargs=3,
type=float,
default=self.std_rgb,
help="STD of RGB channels in the dataset")
parser.add_argument(
"--interpolation",
type=int,
default=self.interpolation,
help="Preprocessing interpolation")
def update(self,
args):
"""
Update ImageNet-1K dataset metainfo after user customizing.
Parameters:
----------
args : ArgumentParser
Main script arguments.
"""
super(ImageNet1KMetaInfo, self).update(args)
self.input_image_size = (args.input_size, args.input_size)
self.resize_inv_factor = args.resize_inv_factor
self.aug_type = args.aug_type
self.mean_rgb = args.mean_rgb
self.std_rgb = args.std_rgb
self.interpolation = args.interpolation
class ImgAugTransform(HybridBlock):
"""
ImgAug-like transform (geometric, noise, and blur).
"""
def __init__(self):
super(ImgAugTransform, self).__init__()
from imgaug import augmenters as iaa
from imgaug import parameters as iap
self.seq = iaa.Sequential(
children=[
iaa.Sequential(
children=[
iaa.Sequential(
children=[
iaa.OneOf(
children=[
iaa.Sometimes(
p=0.95,
then_list=iaa.Affine(
scale={"x": (0.9, 1.1), "y": (0.9, 1.1)},
translate_percent={"x": (-0.05, 0.05), "y": (-0.05, 0.05)},
rotate=(-30, 30),
shear=(-15, 15),
order=iap.Choice([0, 1, 3], p=[0.15, 0.80, 0.05]),
mode="reflect",
name="Affine")),
iaa.Sometimes(
p=0.05,
then_list=iaa.PerspectiveTransform(
scale=(0.01, 0.1)))],
name="Blur"),
iaa.Sometimes(
p=0.01,
then_list=iaa.PiecewiseAffine(
scale=(0.0, 0.01),
nb_rows=(4, 20),
nb_cols=(4, 20),
order=iap.Choice([0, 1, 3], p=[0.15, 0.80, 0.05]),
mode="reflect",
name="PiecewiseAffine"))],
random_order=True,
name="GeomTransform"),
iaa.Sequential(
children=[
iaa.Sometimes(
p=0.75,
then_list=iaa.Add(
value=(-10, 10),
per_channel=0.5,
name="Brightness")),
iaa.Sometimes(
p=0.05,
then_list=iaa.Emboss(
alpha=(0.0, 0.5),
strength=(0.5, 1.2),
name="Emboss")),
iaa.Sometimes(
p=0.1,
then_list=iaa.Sharpen(
alpha=(0.0, 0.5),
lightness=(0.5, 1.2),
name="Sharpen")),
iaa.Sometimes(
p=0.25,
then_list=iaa.ContrastNormalization(
alpha=(0.5, 1.5),
per_channel=0.5,
name="ContrastNormalization"))
],
random_order=True,
name="ColorTransform"),
iaa.Sequential(
children=[
iaa.Sometimes(
p=0.5,
then_list=iaa.AdditiveGaussianNoise(
loc=0,
scale=(0.0, 10.0),
per_channel=0.5,
name="AdditiveGaussianNoise")),
iaa.Sometimes(
p=0.1,
then_list=iaa.SaltAndPepper(
p=(0, 0.001),
per_channel=0.5,
name="SaltAndPepper"))],
random_order=True,
name="Noise"),
iaa.OneOf(
children=[
iaa.Sometimes(
p=0.05,
then_list=iaa.MedianBlur(
k=3,
name="MedianBlur")),
iaa.Sometimes(
p=0.05,
then_list=iaa.AverageBlur(
k=(2, 4),
name="AverageBlur")),
iaa.Sometimes(
p=0.5,
then_list=iaa.GaussianBlur(
sigma=(0.0, 2.0),
name="GaussianBlur"))],
name="Blur"),
],
random_order=True,
name="MainProcess")])
def hybrid_forward(self, F, x):
img = x.asnumpy().copy()
# cv2.imshow(winname="imgA", mat=img)
img_aug = self.seq.augment_image(img)
# cv2.imshow(winname="img_augA", mat=img_aug)
# cv2.waitKey()
x = mx.nd.array(img_aug, dtype=x.dtype, ctx=x.context)
return x
def imagenet_train_transform(ds_metainfo,
jitter_param=0.4,
lighting_param=0.1):
"""
Create image transform sequence for training subset.
Parameters:
----------
ds_metainfo : DatasetMetaInfo
ImageNet-1K dataset metainfo.
jitter_param : float
How much to jitter values.
lighting_param : float
How much to noise intensity of the image.
Returns:
-------
Sequential
Image transform sequence.
"""
input_image_size = ds_metainfo.input_image_size
if ds_metainfo.aug_type == "aug0":
interpolation = ds_metainfo.interpolation
transform_list = []
elif ds_metainfo.aug_type == "aug1":
interpolation = 10
transform_list = []
elif ds_metainfo.aug_type == "aug2":
interpolation = 10
transform_list = [
ImgAugTransform()
]
else:
raise RuntimeError("Unknown augmentation type: {}\n".format(ds_metainfo.aug_type))
transform_list += [
transforms.RandomResizedCrop(
size=input_image_size,
interpolation=interpolation),
transforms.RandomFlipLeftRight(),
transforms.RandomColorJitter(
brightness=jitter_param,
contrast=jitter_param,
saturation=jitter_param),
transforms.RandomLighting(lighting_param),
transforms.ToTensor(),
transforms.Normalize(
mean=ds_metainfo.mean_rgb,
std=ds_metainfo.std_rgb)
]
return transforms.Compose(transform_list)
def imagenet_val_transform(ds_metainfo):
"""
Create image transform sequence for validation subset.
Parameters:
----------
ds_metainfo : DatasetMetaInfo
ImageNet-1K dataset metainfo.
Returns:
-------
Sequential
Image transform sequence.
"""
input_image_size = ds_metainfo.input_image_size
resize_value = calc_val_resize_value(
input_image_size=ds_metainfo.input_image_size,
resize_inv_factor=ds_metainfo.resize_inv_factor)
return transforms.Compose([
transforms.Resize(
size=resize_value,
keep_ratio=True,
interpolation=ds_metainfo.interpolation),
transforms.CenterCrop(size=input_image_size),
transforms.ToTensor(),
transforms.Normalize(
mean=ds_metainfo.mean_rgb,
std=ds_metainfo.std_rgb)
])
def calc_val_resize_value(input_image_size=(224, 224),
resize_inv_factor=0.875):
"""
Calculate image resize value for validation subset.
Parameters:
----------
input_image_size : tuple of 2 int
Main script arguments.
resize_inv_factor : float
Resize inverted factor.
Returns:
-------
int
Resize value.
"""
if isinstance(input_image_size, int):
input_image_size = (input_image_size, input_image_size)
resize_value = int(math.ceil(float(input_image_size[0]) / resize_inv_factor))
return resize_value
| 13,686 | 36.705234 | 107 | py |
imgclsmob | imgclsmob-master/gluon/datasets/coco_hpe1_dataset.py | """
COCO keypoint detection (2D single human pose estimation) dataset.
"""
import os
import copy
import cv2
import numpy as np
import mxnet as mx
from mxnet.gluon.data import dataset
from .dataset_metainfo import DatasetMetaInfo
class CocoHpe1Dataset(dataset.Dataset):
"""
COCO keypoint detection (2D single human pose estimation) dataset.
Parameters:
----------
root : string
Path to `annotations`, `train2017`, and `val2017` folders.
mode : string, default 'train'
'train', 'val', 'test', or 'demo'.
transform : callable, optional
A function that transforms the image.
splits : list of str, default ['person_keypoints_val2017']
Json annotations name.
Candidates can be: person_keypoints_val2017, person_keypoints_train2017.
check_centers : bool, default is False
If true, will force check centers of bbox and keypoints, respectively.
If centers are far away from each other, remove this label.
skip_empty : bool, default is False
Whether skip entire image if no valid label is found. Use `False` if this dataset is
for validation to avoid COCO metric error.
"""
def __init__(self,
root,
mode="train",
transform=None,
splits=("person_keypoints_val2017",),
check_centers=False,
skip_empty=True):
super(CocoHpe1Dataset, self).__init__()
self.root = os.path.expanduser(root)
self.mode = mode
self._transform = transform
self.classes = ["person"]
self.num_class = len(self.classes)
self.keypoint_names = {
0: "nose",
1: "left_eye",
2: "right_eye",
3: "left_ear",
4: "right_ear",
5: "left_shoulder",
6: "right_shoulder",
7: "left_elbow",
8: "right_elbow",
9: "left_wrist",
10: "right_wrist",
11: "left_hip",
12: "right_hip",
13: "left_knee",
14: "right_knee",
15: "left_ankle",
16: "right_ankle"
}
self.skeleton = [
[16, 14], [14, 12], [17, 15], [15, 13], [12, 13], [6, 12], [7, 13], [6, 7], [6, 8],
[7, 9], [8, 10], [9, 11], [2, 3], [1, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7]]
# Joint pairs which defines the pairs of joint to be swapped when the image is flipped horizontally:
self.joint_pairs = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14], [15, 16]]
self.num_joints = 17
if isinstance(splits, mx.base.string_types):
splits = [splits]
self._splits = splits
self._coco = []
self._check_centers = check_centers
self._skip_empty = skip_empty
self.index_map = dict(zip(self.classes, range(self.num_class)))
self.json_id_to_contiguous = None
self.contiguous_id_to_json = None
self._items, self._labels = self._load_jsons()
mode_name = "train" if mode == "train" else "val"
annotations_dir_path = os.path.join(root, "annotations")
annotations_file_path = os.path.join(annotations_dir_path, "person_keypoints_" + mode_name + "2017.json")
self.annotations_file_path = annotations_file_path
def __str__(self):
detail = ",".join([str(s) for s in self._splits])
return self.__class__.__name__ + "(" + detail + ")"
def __len__(self):
return len(self._items)
def __getitem__(self, idx):
img_path = self._items[idx]
img_id = int(os.path.splitext(os.path.basename(img_path))[0])
label = copy.deepcopy(self._labels[idx])
img = mx.image.imread(img_path, 1)
if self._transform is not None:
img, scale, center, score = self._transform(img, label)
res_label = np.array([float(img_id)] + [float(score)] + list(center) + list(scale), np.float32)
return img, res_label
def _load_jsons(self):
"""
Load all image paths and labels from JSON annotation files into buffer.
"""
items = []
labels = []
from pycocotools.coco import COCO
for split in self._splits:
anno = os.path.join(self.root, "annotations", split) + ".json"
_coco = COCO(anno)
self._coco.append(_coco)
classes = [c["name"] for c in _coco.loadCats(_coco.getCatIds())]
if not classes == self.classes:
raise ValueError("Incompatible category names with COCO: ")
assert classes == self.classes
json_id_to_contiguous = {
v: k for k, v in enumerate(_coco.getCatIds())}
if self.json_id_to_contiguous is None:
self.json_id_to_contiguous = json_id_to_contiguous
self.contiguous_id_to_json = {
v: k for k, v in self.json_id_to_contiguous.items()}
else:
assert self.json_id_to_contiguous == json_id_to_contiguous
# iterate through the annotations
image_ids = sorted(_coco.getImgIds())
for entry in _coco.loadImgs(image_ids):
dirname, filename = entry["coco_url"].split("/")[-2:]
abs_path = os.path.join(self.root, dirname, filename)
if not os.path.exists(abs_path):
raise IOError("Image: {} not exists.".format(abs_path))
label = self._check_load_keypoints(_coco, entry)
if not label:
continue
# num of items are relative to person, not image
for obj in label:
items.append(abs_path)
labels.append(obj)
return items, labels
def _check_load_keypoints(self, coco, entry):
"""
Check and load ground-truth keypoints.
"""
ann_ids = coco.getAnnIds(imgIds=entry["id"], iscrowd=False)
objs = coco.loadAnns(ann_ids)
# check valid bboxes
valid_objs = []
width = entry["width"]
height = entry["height"]
for obj in objs:
contiguous_cid = self.json_id_to_contiguous[obj["category_id"]]
if contiguous_cid >= self.num_class:
# not class of interest
continue
if max(obj["keypoints"]) == 0:
continue
# convert from (x, y, w, h) to (xmin, ymin, xmax, ymax) and clip bound
xmin, ymin, xmax, ymax = self.bbox_clip_xyxy(self.bbox_xywh_to_xyxy(obj["bbox"]), width, height)
# require non-zero box area
if obj['area'] <= 0 or xmax <= xmin or ymax <= ymin:
continue
# joints 3d: (num_joints, 3, 2); 3 is for x, y, z; 2 is for position, visibility
joints_3d = np.zeros((self.num_joints, 3, 2), dtype=np.float32)
for i in range(self.num_joints):
joints_3d[i, 0, 0] = obj["keypoints"][i * 3 + 0]
joints_3d[i, 1, 0] = obj["keypoints"][i * 3 + 1]
# joints_3d[i, 2, 0] = 0
visible = min(1, obj["keypoints"][i * 3 + 2])
joints_3d[i, :2, 1] = visible
# joints_3d[i, 2, 1] = 0
if np.sum(joints_3d[:, 0, 1]) < 1:
# no visible keypoint
continue
if self._check_centers:
bbox_center, bbox_area = self._get_box_center_area((xmin, ymin, xmax, ymax))
kp_center, num_vis = self._get_keypoints_center_count(joints_3d)
ks = np.exp(-2 * np.sum(np.square(bbox_center - kp_center)) / bbox_area)
if (num_vis / 80.0 + 47 / 80.0) > ks:
continue
valid_objs.append({
"bbox": (xmin, ymin, xmax, ymax),
"joints_3d": joints_3d
})
if not valid_objs:
if not self._skip_empty:
# dummy invalid labels if no valid objects are found
valid_objs.append({
"bbox": np.array([-1, -1, 0, 0]),
"joints_3d": np.zeros((self.num_joints, 3, 2), dtype=np.float32)
})
return valid_objs
@staticmethod
def _get_box_center_area(bbox):
"""
Get bbox center.
"""
c = np.array([(bbox[0] + bbox[2]) / 2.0, (bbox[1] + bbox[3]) / 2.0])
area = (bbox[3] - bbox[1]) * (bbox[2] - bbox[0])
return c, area
@staticmethod
def _get_keypoints_center_count(keypoints):
"""
Get geometric center of all keypoints.
"""
keypoint_x = np.sum(keypoints[:, 0, 0] * (keypoints[:, 0, 1] > 0))
keypoint_y = np.sum(keypoints[:, 1, 0] * (keypoints[:, 1, 1] > 0))
num = float(np.sum(keypoints[:, 0, 1]))
return np.array([keypoint_x / num, keypoint_y / num]), num
@staticmethod
def bbox_clip_xyxy(xyxy, width, height):
"""
Clip bounding box with format (xmin, ymin, xmax, ymax) to specified boundary.
All bounding boxes will be clipped to the new region `(0, 0, width, height)`.
Parameters:
----------
xyxy : list, tuple or numpy.ndarray
The bbox in format (xmin, ymin, xmax, ymax).
If numpy.ndarray is provided, we expect multiple bounding boxes with
shape `(N, 4)`.
width : int or float
Boundary width.
height : int or float
Boundary height.
Returns:
-------
tuple or np.array
Description of returned object.
"""
if isinstance(xyxy, (tuple, list)):
if not len(xyxy) == 4:
raise IndexError("Bounding boxes must have 4 elements, given {}".format(len(xyxy)))
x1 = np.minimum(width - 1, np.maximum(0, xyxy[0]))
y1 = np.minimum(height - 1, np.maximum(0, xyxy[1]))
x2 = np.minimum(width - 1, np.maximum(0, xyxy[2]))
y2 = np.minimum(height - 1, np.maximum(0, xyxy[3]))
return x1, y1, x2, y2
elif isinstance(xyxy, np.ndarray):
if not xyxy.size % 4 == 0:
raise IndexError("Bounding boxes must have n * 4 elements, given {}".format(xyxy.shape))
x1 = np.minimum(width - 1, np.maximum(0, xyxy[:, 0]))
y1 = np.minimum(height - 1, np.maximum(0, xyxy[:, 1]))
x2 = np.minimum(width - 1, np.maximum(0, xyxy[:, 2]))
y2 = np.minimum(height - 1, np.maximum(0, xyxy[:, 3]))
return np.hstack((x1, y1, x2, y2))
else:
raise TypeError("Expect input xywh a list, tuple or numpy.ndarray, given {}".format(type(xyxy)))
@staticmethod
def bbox_xywh_to_xyxy(xywh):
"""
Convert bounding boxes from format (xmin, ymin, w, h) to (xmin, ymin, xmax, ymax)
Parameters:
----------
xywh : list, tuple or numpy.ndarray
The bbox in format (x, y, w, h).
If numpy.ndarray is provided, we expect multiple bounding boxes with
shape `(N, 4)`.
Returns:
-------
tuple or np.ndarray
The converted bboxes in format (xmin, ymin, xmax, ymax).
If input is numpy.ndarray, return is numpy.ndarray correspondingly.
"""
if isinstance(xywh, (tuple, list)):
if not len(xywh) == 4:
raise IndexError("Bounding boxes must have 4 elements, given {}".format(len(xywh)))
w, h = np.maximum(xywh[2] - 1, 0), np.maximum(xywh[3] - 1, 0)
return xywh[0], xywh[1], xywh[0] + w, xywh[1] + h
elif isinstance(xywh, np.ndarray):
if not xywh.size % 4 == 0:
raise IndexError("Bounding boxes must have n * 4 elements, given {}".format(xywh.shape))
xyxy = np.hstack((xywh[:, :2], xywh[:, :2] + np.maximum(0, xywh[:, 2:4] - 1)))
return xyxy
else:
raise TypeError("Expect input xywh a list, tuple or numpy.ndarray, given {}".format(type(xywh)))
# ---------------------------------------------------------------------------------------------------------------------
class CocoHpeValTransform1(object):
def __init__(self,
ds_metainfo):
self.ds_metainfo = ds_metainfo
self.image_size = self.ds_metainfo.input_image_size
height = self.image_size[0]
width = self.image_size[1]
self.aspect_ratio = float(width / height)
self.mean = ds_metainfo.mean_rgb
self.std = ds_metainfo.std_rgb
def __call__(self, src, label):
bbox = label["bbox"]
assert len(bbox) == 4
xmin, ymin, xmax, ymax = bbox
center, scale = _box_to_center_scale(xmin, ymin, xmax - xmin, ymax - ymin, self.aspect_ratio)
score = label.get("score", 1)
h, w = self.image_size
trans = get_affine_transform(center, scale, 0, [w, h])
img = cv2.warpAffine(src.asnumpy(), trans, (int(w), int(h)), flags=cv2.INTER_LINEAR)
img = mx.nd.image.to_tensor(mx.nd.array(img))
img = mx.nd.image.normalize(img, mean=self.mean, std=self.std)
return img, scale, center, score
def _box_to_center_scale(x, y, w, h, aspect_ratio=1.0, scale_mult=1.25):
pixel_std = 1
center = np.zeros((2,), dtype=np.float32)
center[0] = x + w * 0.5
center[1] = y + h * 0.5
if w > aspect_ratio * h:
h = w / aspect_ratio
elif w < aspect_ratio * h:
w = h * aspect_ratio
scale = np.array(
[w * 1.0 / pixel_std, h * 1.0 / pixel_std], dtype=np.float32)
if center[0] != -1:
scale = scale * scale_mult
return center, scale
def get_dir(src_point, rot_rad):
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
src_result = [0, 0]
src_result[0] = src_point[0] * cs - src_point[1] * sn
src_result[1] = src_point[0] * sn + src_point[1] * cs
return src_result
def crop(img, center, scale, output_size, rot=0):
trans = get_affine_transform(center, scale, rot, output_size)
dst_img = cv2.warpAffine(
img,
trans,
(int(output_size[0]), int(output_size[1])),
flags=cv2.INTER_LINEAR)
return dst_img
def get_3rd_point(a, b):
direct = a - b
return b + np.array([-direct[1], direct[0]], dtype=np.float32)
def get_affine_transform(center,
scale,
rot,
output_size,
shift=np.array([0, 0], dtype=np.float32),
inv=0):
if not isinstance(scale, np.ndarray) and not isinstance(scale, list):
scale = np.array([scale, scale])
scale_tmp = scale
src_w = scale_tmp[0]
dst_w = output_size[0]
dst_h = output_size[1]
rot_rad = np.pi * rot / 180
src_dir = get_dir([0, src_w * -0.5], rot_rad)
dst_dir = np.array([0, dst_w * -0.5], np.float32)
src = np.zeros((3, 2), dtype=np.float32)
dst = np.zeros((3, 2), dtype=np.float32)
src[0, :] = center + scale_tmp * shift
src[1, :] = center + src_dir + scale_tmp * shift
dst[0, :] = [dst_w * 0.5, dst_h * 0.5]
dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5]) + dst_dir
src[2:, :] = get_3rd_point(src[0, :], src[1, :])
dst[2:, :] = get_3rd_point(dst[0, :], dst[1, :])
if inv:
trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))
else:
trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))
return trans
# ---------------------------------------------------------------------------------------------------------------------
class CocoHpeValTransform2(object):
def __init__(self,
ds_metainfo):
self.ds_metainfo = ds_metainfo
self.image_size = self.ds_metainfo.input_image_size
height = self.image_size[0]
width = self.image_size[1]
self.aspect_ratio = float(width / height)
self.mean = ds_metainfo.mean_rgb
self.std = ds_metainfo.std_rgb
def __call__(self, src, label):
# print(src.shape)
src = src.asnumpy()
bbox = label["bbox"]
assert len(bbox) == 4
score = label.get('score', 1)
img, scale_box = detector_to_alpha_pose(
src,
class_ids=mx.nd.array([[0.]]),
scores=mx.nd.array([[1.]]),
bounding_boxs=mx.nd.array(np.array([bbox])),
output_shape=self.image_size)
if scale_box.shape[0] == 1:
pt1 = np.array(scale_box[0, (0, 1)], dtype=np.float32)
pt2 = np.array(scale_box[0, (2, 3)], dtype=np.float32)
else:
assert scale_box.shape[0] == 4
pt1 = np.array(scale_box[(0, 1)], dtype=np.float32)
pt2 = np.array(scale_box[(2, 3)], dtype=np.float32)
return img[0], pt1, pt2, score
def detector_to_alpha_pose(img,
class_ids,
scores,
bounding_boxs,
output_shape=(256, 192),
thr=0.5):
boxes, scores = alpha_pose_detection_processor(
img=img,
boxes=bounding_boxs,
class_idxs=class_ids,
scores=scores,
thr=thr)
pose_input, upscale_bbox = alpha_pose_image_cropper(
source_img=img,
boxes=boxes,
output_shape=output_shape)
return pose_input, upscale_bbox
def alpha_pose_detection_processor(img,
boxes,
class_idxs,
scores,
thr=0.5):
if len(boxes.shape) == 3:
boxes = boxes.squeeze(axis=0)
if len(class_idxs.shape) == 3:
class_idxs = class_idxs.squeeze(axis=0)
if len(scores.shape) == 3:
scores = scores.squeeze(axis=0)
# cilp coordinates
boxes[:, [0, 2]] = mx.nd.clip(boxes[:, [0, 2]], 0., img.shape[1] - 1)
boxes[:, [1, 3]] = mx.nd.clip(boxes[:, [1, 3]], 0., img.shape[0] - 1)
# select boxes
mask1 = (class_idxs == 0).asnumpy()
mask2 = (scores > thr).asnumpy()
picked_idxs = np.where((mask1 + mask2) > 1)[0]
if picked_idxs.shape[0] == 0:
return None, None
else:
return boxes[picked_idxs], scores[picked_idxs]
def alpha_pose_image_cropper(source_img,
boxes,
output_shape=(256, 192)):
if boxes is None:
return None, boxes
# crop person poses
img_width, img_height = source_img.shape[1], source_img.shape[0]
tensors = mx.nd.zeros([boxes.shape[0], 3, output_shape[0], output_shape[1]])
out_boxes = np.zeros([boxes.shape[0], 4])
for i, box in enumerate(boxes.asnumpy()):
img = source_img.copy()
box_width = box[2] - box[0]
box_height = box[3] - box[1]
if box_width > 100:
scale_rate = 0.2
else:
scale_rate = 0.3
# crop image
left = int(max(0, box[0] - box_width * scale_rate / 2))
up = int(max(0, box[1] - box_height * scale_rate / 2))
right = int(min(img_width - 1, max(left + 5, box[2] + box_width * scale_rate / 2)))
bottom = int(min(img_height - 1, max(up + 5, box[3] + box_height * scale_rate / 2)))
crop_width = right - left
if crop_width < 1:
continue
crop_height = bottom - up
if crop_height < 1:
continue
ul = np.array((left, up))
br = np.array((right, bottom))
img = cv_cropBox(img, ul, br, output_shape[0], output_shape[1])
img = mx.nd.image.to_tensor(mx.nd.array(img))
# img = img.transpose((2, 0, 1))
img[0] = img[0] - 0.406
img[1] = img[1] - 0.457
img[2] = img[2] - 0.480
assert (img.shape[0] == 3)
tensors[i] = img
out_boxes[i] = (left, up, right, bottom)
return tensors, out_boxes
def cv_cropBox(img, ul, br, resH, resW, pad_val=0):
ul = ul
br = (br - 1)
# br = br.int()
lenH = max((br[1] - ul[1]).item(), (br[0] - ul[0]).item() * resH / resW)
lenW = lenH * resW / resH
if img.ndim == 2:
img = img[:, np.newaxis]
box_shape = [br[1] - ul[1], br[0] - ul[0]]
pad_size = [(lenH - box_shape[0]) // 2, (lenW - box_shape[1]) // 2]
# Padding Zeros
img[:ul[1], :, :], img[:, :ul[0], :] = pad_val, pad_val
img[br[1] + 1:, :, :], img[:, br[0] + 1:, :] = pad_val, pad_val
src = np.zeros((3, 2), dtype=np.float32)
dst = np.zeros((3, 2), dtype=np.float32)
src[0, :] = np.array([ul[0] - pad_size[1], ul[1] - pad_size[0]], np.float32)
src[1, :] = np.array([br[0] + pad_size[1], br[1] + pad_size[0]], np.float32)
dst[0, :] = 0
dst[1, :] = np.array([resW - 1, resH - 1], np.float32)
src[2:, :] = get_3rd_point(src[0, :], src[1, :])
dst[2:, :] = get_3rd_point(dst[0, :], dst[1, :])
trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))
dst_img = cv2.warpAffine(img, trans, (resW, resH), flags=cv2.INTER_LINEAR)
return dst_img
# ---------------------------------------------------------------------------------------------------------------------
def recalc_pose1(keypoints,
bbs,
image_size):
def transform_preds(coords, center, scale, output_size):
def affine_transform(pt, t):
new_pt = np.array([pt[0], pt[1], 1.]).T
new_pt = np.dot(t, new_pt)
return new_pt[:2]
target_coords = np.zeros(coords.shape)
trans = get_affine_transform(center, scale, 0, output_size, inv=1)
for p in range(coords.shape[0]):
target_coords[p, 0:2] = affine_transform(coords[p, 0:2], trans)
return target_coords
center = bbs[:, :2]
scale = bbs[:, 2:4]
heatmap_height = image_size[0] // 4
heatmap_width = image_size[1] // 4
output_size = [heatmap_width, heatmap_height]
preds = np.zeros_like(keypoints)
for i in range(keypoints.shape[0]):
preds[i] = transform_preds(keypoints[i], center[i], scale[i], output_size)
return preds
def recalc_pose1b(pred,
label,
image_size,
visible_conf_threshold=0.0):
label_img_id = label[:, 0].astype(np.int32)
label_score = label[:, 1]
label_bbs = label[:, 2:6]
pred_keypoints = pred[:, :, :2]
pred_score = pred[:, :, 2]
pred[:, :, :2] = recalc_pose1(pred_keypoints, label_bbs, image_size)
pred_person_score = []
batch = pred_keypoints.shape[0]
num_joints = pred_keypoints.shape[1]
for idx in range(batch):
kpt_score = 0
count = 0
for i in range(num_joints):
mval = float(pred_score[idx][i])
if mval > visible_conf_threshold:
kpt_score += mval
count += 1
if count > 0:
kpt_score /= count
kpt_score = kpt_score * float(label_score[idx])
pred_person_score.append(kpt_score)
return pred, pred_person_score, label_img_id
def recalc_pose2(keypoints,
bbs,
image_size):
def transformBoxInvert(pt, ul, br, resH, resW):
center = np.zeros(2)
center[0] = (br[0] - 1 - ul[0]) / 2
center[1] = (br[1] - 1 - ul[1]) / 2
lenH = max(br[1] - ul[1], (br[0] - ul[0]) * resH / resW)
lenW = lenH * resW / resH
_pt = (pt * lenH) / resH
if bool(((lenW - 1) / 2 - center[0]) > 0):
_pt[0] = _pt[0] - ((lenW - 1) / 2 - center[0])
if bool(((lenH - 1) / 2 - center[1]) > 0):
_pt[1] = _pt[1] - ((lenH - 1) / 2 - center[1])
new_point = np.zeros(2)
new_point[0] = _pt[0] + ul[0]
new_point[1] = _pt[1] + ul[1]
return new_point
pt2 = bbs[:, :2]
pt1 = bbs[:, 2:4]
heatmap_height = image_size[0] // 4
heatmap_width = image_size[1] // 4
preds = np.zeros_like(keypoints)
for i in range(keypoints.shape[0]):
for j in range(keypoints.shape[1]):
preds[i, j] = transformBoxInvert(keypoints[i, j], pt1[i], pt2[i], heatmap_height, heatmap_width)
return preds
def recalc_pose2b(pred,
label,
image_size,
visible_conf_threshold=0.0):
label_img_id = label[:, 0].astype(np.int32)
label_score = label[:, 1]
label_bbs = label[:, 2:6]
pred_keypoints = pred[:, :, :2]
pred_score = pred[:, :, 2]
pred[:, :, :2] = recalc_pose2(pred_keypoints, label_bbs, image_size)
pred_person_score = []
batch = pred_keypoints.shape[0]
num_joints = pred_keypoints.shape[1]
for idx in range(batch):
kpt_score = 0
count = 0
for i in range(num_joints):
mval = float(pred_score[idx][i])
if mval > visible_conf_threshold:
kpt_score += mval
count += 1
if count > 0:
kpt_score /= count
kpt_score = kpt_score * float(label_score[idx])
pred_person_score.append(kpt_score)
return pred, pred_person_score, label_img_id
# ---------------------------------------------------------------------------------------------------------------------
class CocoHpe1MetaInfo(DatasetMetaInfo):
def __init__(self):
super(CocoHpe1MetaInfo, self).__init__()
self.label = "COCO"
self.short_label = "coco"
self.root_dir_name = "coco"
self.dataset_class = CocoHpe1Dataset
self.num_training_samples = None
self.in_channels = 3
self.num_classes = 17
self.input_image_size = (256, 192)
self.train_metric_capts = None
self.train_metric_names = None
self.train_metric_extra_kwargs = None
self.val_metric_capts = None
self.val_metric_names = None
self.test_metric_capts = ["Val.CocoOksAp"]
self.test_metric_names = ["CocoHpeOksApMetric"]
self.test_metric_extra_kwargs = [
{"name": "OksAp",
"coco_annotations_file_path": None,
"use_file": False,
"pose_postprocessing_fn": lambda x, y: recalc_pose1b(x, y, self.input_image_size)}]
self.saver_acc_ind = 0
self.do_transform = True
self.val_transform = CocoHpeValTransform1
self.test_transform = CocoHpeValTransform1
self.ml_type = "hpe"
self.allow_hybridize = False
self.test_net_extra_kwargs = {"fixed_size": False}
self.mean_rgb = (0.485, 0.456, 0.406)
self.std_rgb = (0.229, 0.224, 0.225)
self.model_type = 1
def add_dataset_parser_arguments(self,
parser,
work_dir_path):
"""
Create python script parameters (for ImageNet-1K dataset metainfo).
Parameters:
----------
parser : ArgumentParser
ArgumentParser instance.
work_dir_path : str
Path to working directory.
"""
super(CocoHpe1MetaInfo, self).add_dataset_parser_arguments(parser, work_dir_path)
parser.add_argument(
"--input-size",
type=int,
nargs=2,
default=self.input_image_size,
help="size of the input for model")
parser.add_argument(
"--model-type",
type=int,
default=self.model_type,
help="model type (1=SimplePose, 2=AlphaPose)")
def update(self,
args):
"""
Update ImageNet-1K dataset metainfo after user customizing.
Parameters:
----------
args : ArgumentParser
Main script arguments.
"""
super(CocoHpe1MetaInfo, self).update(args)
self.input_image_size = args.input_size
self.model_type = args.model_type
if self.model_type == 1:
self.test_metric_extra_kwargs[0]["pose_postprocessing_fn"] =\
lambda x, y: recalc_pose1b(x, y, self.input_image_size)
self.val_transform = CocoHpeValTransform1
self.test_transform = CocoHpeValTransform1
else:
self.test_metric_extra_kwargs[0]["pose_postprocessing_fn"] =\
lambda x, y: recalc_pose2b(x, y, self.input_image_size)
self.val_transform = CocoHpeValTransform2
self.test_transform = CocoHpeValTransform2
def update_from_dataset(self,
dataset):
"""
Update dataset metainfo after a dataset class instance creation.
Parameters:
----------
args : obj
A dataset class instance.
"""
self.test_metric_extra_kwargs[0]["coco_annotations_file_path"] = dataset.annotations_file_path
| 28,936 | 34.289024 | 119 | py |
imgclsmob | imgclsmob-master/gluon/datasets/widerface_det_dataset.py | """
WIDER FACE detection dataset.
"""
import os
import cv2
import mxnet as mx
import numpy as np
from mxnet.gluon.data import dataset
from .dataset_metainfo import DatasetMetaInfo
__all__ = ['WiderfaceDetMetaInfo']
class WiderfaceDetDataset(dataset.Dataset):
"""
WIDER FACE detection dataset.
Parameters:
----------
root : str
Path to folder storing the dataset.
mode : string, default 'train'
'train', 'val', 'test', or 'demo'.
transform : callable, optional
A function that transforms the image.
"""
def __init__(self,
root,
mode="train",
transform=None):
super(WiderfaceDetDataset, self).__init__()
self.root = os.path.expanduser(root)
self.mode = mode
self._transform = transform
self.synsets = []
self.items = []
image_dir_path = "{}/WIDER_{}/images".format(self.root, self.mode)
for folder in sorted(os.listdir(image_dir_path)):
path = os.path.join(root, folder)
if not os.path.isdir(path):
continue
label = len(self.synsets)
self.synsets.append(folder)
for filename in sorted(os.listdir(path)):
filename = os.path.join(path, filename)
ext = os.path.splitext(filename)[1]
if ext.lower() not in (".jpg",):
continue
self.items.append((filename, label))
def __len__(self):
return len(self.items)
def __getitem__(self, idx):
img_path = self.items[idx][0]
# image = cv2.imread(img_path, flags=cv2.IMREAD_COLOR)
image = mx.image.imread(img_path, flag=1).asnumpy()
image_size = image.shape[:2]
shorter_side = min(image.shape[:2])
resize_scale = 1.0
if shorter_side < 128:
resize_scale = 128.0 / shorter_side
image = cv2.resize(image, (0, 0), fx=resize_scale, fy=resize_scale)
image = image.transpose(2, 0, 1).astype(np.float32)
image = mx.nd.array(image)
label = "{}/{}/{}/{}/{}".format(self.synsets[self.items[idx][1]], (img_path.split("/")[1]).split(".")[0],
resize_scale, image_size[0], image_size[1])
label = np.array(label).copy()
if self._transform is not None:
image, label = self._transform(image, label)
return image, label
# ---------------------------------------------------------------------------------------------------------------------
class WiderfaceDetValTransform(object):
def __init__(self,
ds_metainfo):
self.ds_metainfo = ds_metainfo
def __call__(self, image, label):
return image, label
# ---------------------------------------------------------------------------------------------------------------------
class WiderfaceDetMetaInfo(DatasetMetaInfo):
def __init__(self):
super(WiderfaceDetMetaInfo, self).__init__()
self.label = "WiderFace"
self.short_label = "widerface"
self.root_dir_name = "WIDER_FACE"
self.dataset_class = WiderfaceDetDataset
self.num_training_samples = None
self.in_channels = 3
self.input_image_size = (480, 640)
self.train_metric_capts = None
self.train_metric_names = None
self.train_metric_extra_kwargs = None
self.val_metric_capts = None
self.val_metric_names = None
self.test_metric_capts = ["WF"]
self.test_metric_names = ["WiderfaceDetMetric"]
self.test_metric_extra_kwargs = [
{"name": "WF"}]
self.saver_acc_ind = 0
self.do_transform = True
self.do_transform_first = False
self.last_batch = "keep"
self.val_transform = WiderfaceDetValTransform
self.test_transform = WiderfaceDetValTransform
self.ml_type = "det"
self.allow_hybridize = False
self.test_net_extra_kwargs = None
self.model_type = 1
self.receptive_field_center_starts = None
self.receptive_field_strides = None
self.bbox_factors = None
def add_dataset_parser_arguments(self,
parser,
work_dir_path):
"""
Create python script parameters (for ImageNet-1K dataset metainfo).
Parameters:
----------
parser : ArgumentParser
ArgumentParser instance.
work_dir_path : str
Path to working directory.
"""
super(WiderfaceDetMetaInfo, self).add_dataset_parser_arguments(parser, work_dir_path)
parser.add_argument(
"--model-type",
type=int,
default=self.model_type,
help="model type (1=320, 2=560)")
def update(self,
args):
"""
Update ImageNet-1K dataset metainfo after user customizing.
Parameters:
----------
args : ArgumentParser
Main script arguments.
"""
super(WiderfaceDetMetaInfo, self).update(args)
self.model_type = args.model_type
if self.model_type == 1:
self.receptive_field_center_starts = [3, 7, 15, 31, 63]
self.receptive_field_strides = [4, 8, 16, 32, 64]
self.bbox_factors = [10.0, 20.0, 40.0, 80.0, 160.0]
else:
self.receptive_field_center_starts = [3, 3, 7, 7, 15, 31, 31, 31]
self.receptive_field_strides = [4, 4, 8, 8, 16, 32, 32, 32]
self.bbox_factors = [7.5, 10.0, 20.0, 35.0, 55.0, 125.0, 200.0, 280.0]
| 5,676 | 32.791667 | 119 | py |
imgclsmob | imgclsmob-master/gluon/datasets/coco_det_dataset.py | """
MS COCO object detection dataset.
"""
__all__ = ['CocoDetMetaInfo']
import os
import cv2
import logging
import mxnet as mx
import numpy as np
from PIL import Image
from mxnet.gluon.data import dataset
from .dataset_metainfo import DatasetMetaInfo
class CocoDetDataset(dataset.Dataset):
"""
MS COCO detection dataset.
Parameters:
----------
root : str
Path to folder storing the dataset.
mode : string, default 'train'
'train', 'val', 'test', or 'demo'.
transform : callable, optional
A function that transforms the image.
splits : list of str, default ['instances_val2017']
Json annotations name.
Candidates can be: instances_val2017, instances_train2017.
min_object_area : float
Minimum accepted ground-truth area, if an object's area is smaller than this value,
it will be ignored.
skip_empty : bool, default is True
Whether skip images with no valid object. This should be `True` in training, otherwise
it will cause undefined behavior.
use_crowd : bool, default is True
Whether use boxes labeled as crowd instance.
"""
CLASSES = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train',
'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign',
'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep',
'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella',
'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard',
'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard',
'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork',
'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange',
'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair',
'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv',
'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave',
'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase',
'scissors', 'teddy bear', 'hair drier', 'toothbrush']
def __init__(self,
root,
mode="train",
transform=None,
splits=('instances_val2017',),
min_object_area=0,
skip_empty=True,
use_crowd=True):
super(CocoDetDataset, self).__init__()
self._root = os.path.expanduser(root)
self.mode = mode
self._transform = transform
self.num_class = len(self.CLASSES)
self._min_object_area = min_object_area
self._skip_empty = skip_empty
self._use_crowd = use_crowd
if isinstance(splits, mx.base.string_types):
splits = [splits]
self._splits = splits
self.index_map = dict(zip(type(self).CLASSES, range(self.num_class)))
self.json_id_to_contiguous = None
self.contiguous_id_to_json = None
self._coco = []
self._items, self._labels, self._im_aspect_ratios = self._load_jsons()
mode_name = "train" if mode == "train" else "val"
annotations_dir_path = os.path.join(root, "annotations")
annotations_file_path = os.path.join(annotations_dir_path, "instances_" + mode_name + "2017.json")
self.annotations_file_path = annotations_file_path
def __str__(self):
detail = ','.join([str(s) for s in self._splits])
return self.__class__.__name__ + '(' + detail + ')'
@property
def coco(self):
"""
Return pycocotools object for evaluation purposes.
"""
if not self._coco:
raise ValueError("No coco objects found, dataset not initialized.")
if len(self._coco) > 1:
raise NotImplementedError(
"Currently we don't support evaluating {} JSON files. \
Please use single JSON dataset and evaluate one by one".format(len(self._coco)))
return self._coco[0]
@property
def classes(self):
"""
Category names.
"""
return type(self).CLASSES
@property
def annotation_dir(self):
"""
The subdir for annotations. Default is 'annotations'(coco default)
For example, a coco format json file will be searched as
'root/annotation_dir/xxx.json'
You can override if custom dataset don't follow the same pattern
"""
return 'annotations'
def get_im_aspect_ratio(self):
"""Return the aspect ratio of each image in the order of the raw data."""
if self._im_aspect_ratios is not None:
return self._im_aspect_ratios
self._im_aspect_ratios = [None] * len(self._items)
for i, img_path in enumerate(self._items):
with Image.open(img_path) as im:
w, h = im.size
self._im_aspect_ratios[i] = 1.0 * w / h
return self._im_aspect_ratios
def _parse_image_path(self, entry):
"""How to parse image dir and path from entry.
Parameters:
----------
entry : dict
COCO entry, e.g. including width, height, image path, etc..
Returns:
-------
abs_path : str
Absolute path for corresponding image.
"""
dirname, filename = entry["coco_url"].split("/")[-2:]
abs_path = os.path.join(self._root, dirname, filename)
return abs_path
def __len__(self):
return len(self._items)
def __getitem__(self, idx):
img_path = self._items[idx]
label = self._labels[idx]
img = mx.image.imread(img_path, 1)
label = np.array(label).copy()
if self._transform is not None:
img, label = self._transform(img, label)
return img, label
def _load_jsons(self):
"""
Load all image paths and labels from JSON annotation files into buffer.
"""
items = []
labels = []
im_aspect_ratios = []
from pycocotools.coco import COCO
for split in self._splits:
anno = os.path.join(self._root, self.annotation_dir, split) + ".json"
_coco = COCO(anno)
self._coco.append(_coco)
classes = [c["name"] for c in _coco.loadCats(_coco.getCatIds())]
if not classes == self.classes:
raise ValueError("Incompatible category names with COCO: ")
assert classes == self.classes
json_id_to_contiguous = {
v: k for k, v in enumerate(_coco.getCatIds())}
if self.json_id_to_contiguous is None:
self.json_id_to_contiguous = json_id_to_contiguous
self.contiguous_id_to_json = {
v: k for k, v in self.json_id_to_contiguous.items()}
else:
assert self.json_id_to_contiguous == json_id_to_contiguous
# iterate through the annotations
image_ids = sorted(_coco.getImgIds())
for entry in _coco.loadImgs(image_ids):
abs_path = self._parse_image_path(entry)
if not os.path.exists(abs_path):
raise IOError("Image: {} not exists.".format(abs_path))
label = self._check_load_bbox(_coco, entry)
if not label:
continue
im_aspect_ratios.append(float(entry["width"]) / entry["height"])
items.append(abs_path)
labels.append(label)
return items, labels, im_aspect_ratios
def _check_load_bbox(self, coco, entry):
"""
Check and load ground-truth labels.
"""
entry_id = entry['id']
# fix pycocotools _isArrayLike which don't work for str in python3
entry_id = [entry_id] if not isinstance(entry_id, (list, tuple)) else entry_id
ann_ids = coco.getAnnIds(imgIds=entry_id, iscrowd=None)
objs = coco.loadAnns(ann_ids)
# check valid bboxes
valid_objs = []
width = entry["width"]
height = entry["height"]
for obj in objs:
if obj["area"] < self._min_object_area:
continue
if obj.get("ignore", 0) == 1:
continue
if not self._use_crowd and obj.get("iscrowd", 0):
continue
# convert from (x, y, w, h) to (xmin, ymin, xmax, ymax) and clip bound
xmin, ymin, xmax, ymax = self.bbox_clip_xyxy(self.bbox_xywh_to_xyxy(obj["bbox"]), width, height)
# require non-zero box area
if obj["area"] > 0 and xmax > xmin and ymax > ymin:
contiguous_cid = self.json_id_to_contiguous[obj["category_id"]]
valid_objs.append([xmin, ymin, xmax, ymax, contiguous_cid])
if not valid_objs:
if not self._skip_empty:
# dummy invalid labels if no valid objects are found
valid_objs.append([-1, -1, -1, -1, -1])
return valid_objs
@staticmethod
def bbox_clip_xyxy(xyxy, width, height):
"""
Clip bounding box with format (xmin, ymin, xmax, ymax) to specified boundary.
All bounding boxes will be clipped to the new region `(0, 0, width, height)`.
Parameters:
----------
xyxy : list, tuple or numpy.ndarray
The bbox in format (xmin, ymin, xmax, ymax).
If numpy.ndarray is provided, we expect multiple bounding boxes with
shape `(N, 4)`.
width : int or float
Boundary width.
height : int or float
Boundary height.
Returns:
-------
tuple or np.array
Description of returned object.
"""
if isinstance(xyxy, (tuple, list)):
if not len(xyxy) == 4:
raise IndexError("Bounding boxes must have 4 elements, given {}".format(len(xyxy)))
x1 = np.minimum(width - 1, np.maximum(0, xyxy[0]))
y1 = np.minimum(height - 1, np.maximum(0, xyxy[1]))
x2 = np.minimum(width - 1, np.maximum(0, xyxy[2]))
y2 = np.minimum(height - 1, np.maximum(0, xyxy[3]))
return x1, y1, x2, y2
elif isinstance(xyxy, np.ndarray):
if not xyxy.size % 4 == 0:
raise IndexError("Bounding boxes must have n * 4 elements, given {}".format(xyxy.shape))
x1 = np.minimum(width - 1, np.maximum(0, xyxy[:, 0]))
y1 = np.minimum(height - 1, np.maximum(0, xyxy[:, 1]))
x2 = np.minimum(width - 1, np.maximum(0, xyxy[:, 2]))
y2 = np.minimum(height - 1, np.maximum(0, xyxy[:, 3]))
return np.hstack((x1, y1, x2, y2))
else:
raise TypeError("Expect input xywh a list, tuple or numpy.ndarray, given {}".format(type(xyxy)))
@staticmethod
def bbox_xywh_to_xyxy(xywh):
"""
Convert bounding boxes from format (xmin, ymin, w, h) to (xmin, ymin, xmax, ymax)
Parameters:
----------
xywh : list, tuple or numpy.ndarray
The bbox in format (x, y, w, h).
If numpy.ndarray is provided, we expect multiple bounding boxes with
shape `(N, 4)`.
Returns:
-------
tuple or np.ndarray
The converted bboxes in format (xmin, ymin, xmax, ymax).
If input is numpy.ndarray, return is numpy.ndarray correspondingly.
"""
if isinstance(xywh, (tuple, list)):
if not len(xywh) == 4:
raise IndexError("Bounding boxes must have 4 elements, given {}".format(len(xywh)))
w, h = np.maximum(xywh[2] - 1, 0), np.maximum(xywh[3] - 1, 0)
return xywh[0], xywh[1], xywh[0] + w, xywh[1] + h
elif isinstance(xywh, np.ndarray):
if not xywh.size % 4 == 0:
raise IndexError("Bounding boxes must have n * 4 elements, given {}".format(xywh.shape))
xyxy = np.hstack((xywh[:, :2], xywh[:, :2] + np.maximum(0, xywh[:, 2:4] - 1)))
return xyxy
else:
raise TypeError("Expect input xywh a list, tuple or numpy.ndarray, given {}".format(type(xywh)))
# ---------------------------------------------------------------------------------------------------------------------
class CocoDetValTransform(object):
def __init__(self,
ds_metainfo):
self.ds_metainfo = ds_metainfo
self.image_size = self.ds_metainfo.input_image_size
self._height = self.image_size[0]
self._width = self.image_size[1]
self._mean = np.array(ds_metainfo.mean_rgb, dtype=np.float32).reshape(1, 1, 3)
self._std = np.array(ds_metainfo.std_rgb, dtype=np.float32).reshape(1, 1, 3)
def __call__(self, src, label):
# resize
img, bbox = src.asnumpy(), label
input_h, input_w = self._height, self._width
h, w, _ = src.shape
s = max(h, w) * 1.0
c = np.array([w / 2., h / 2.], dtype=np.float32)
trans_input = self.get_affine_transform(c, s, 0, [input_w, input_h])
inp = cv2.warpAffine(img, trans_input, (input_w, input_h), flags=cv2.INTER_LINEAR)
output_w = input_w
output_h = input_h
trans_output = self.get_affine_transform(c, s, 0, [output_w, output_h])
for i in range(bbox.shape[0]):
bbox[i, :2] = self.affine_transform(bbox[i, :2], trans_output)
bbox[i, 2:4] = self.affine_transform(bbox[i, 2:4], trans_output)
bbox[:, :2] = np.clip(bbox[:, :2], 0, output_w - 1)
bbox[:, 2:4] = np.clip(bbox[:, 2:4], 0, output_h - 1)
img = inp
# to tensor
img = img.astype(np.float32) / 255.0
img = (img - self._mean) / self._std
img = img.transpose(2, 0, 1).astype(np.float32)
img = mx.nd.array(img)
return img, bbox.astype(img.dtype)
@staticmethod
def get_affine_transform(center,
scale,
rot,
output_size,
shift=np.array([0, 0], dtype=np.float32),
inv=0):
"""
Get affine transform matrix given center, scale and rotation.
Parameters:
----------
center : tuple of float
Center point.
scale : float
Scaling factor.
rot : float
Rotation degree.
output_size : tuple of int
(width, height) of the output size.
shift : float
Shift factor.
inv : bool
Whether inverse the computation.
Returns:
-------
numpy.ndarray
Affine matrix.
"""
if not isinstance(scale, np.ndarray) and not isinstance(scale, list):
scale = np.array([scale, scale], dtype=np.float32)
scale_tmp = scale
src_w = scale_tmp[0]
dst_w = output_size[0]
dst_h = output_size[1]
rot_rad = np.pi * rot / 180
src_dir = CocoDetValTransform.get_rot_dir([0, src_w * -0.5], rot_rad)
dst_dir = np.array([0, dst_w * -0.5], np.float32)
src = np.zeros((3, 2), dtype=np.float32)
dst = np.zeros((3, 2), dtype=np.float32)
src[0, :] = center + scale_tmp * shift
src[1, :] = center + src_dir + scale_tmp * shift
dst[0, :] = [dst_w * 0.5, dst_h * 0.5]
dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5], np.float32) + dst_dir
src[2:, :] = CocoDetValTransform.get_3rd_point(src[0, :], src[1, :])
dst[2:, :] = CocoDetValTransform.get_3rd_point(dst[0, :], dst[1, :])
if inv:
trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))
else:
trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))
return trans
@staticmethod
def get_rot_dir(src_point, rot_rad):
"""
Get rotation direction.
Parameters:
----------
src_point : tuple of float
Original point.
rot_rad : float
Rotation radian.
Returns:
-------
tuple of float
Rotation.
"""
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
src_result = [0, 0]
src_result[0] = src_point[0] * cs - src_point[1] * sn
src_result[1] = src_point[0] * sn + src_point[1] * cs
return src_result
@staticmethod
def get_3rd_point(a, b):
"""
Get the 3rd point position given first two points.
Parameters:
----------
a : tuple of float
First point.
b : tuple of float
Second point.
Returns:
-------
tuple of float
Third point.
"""
direct = a - b
return b + np.array([-direct[1], direct[0]], dtype=np.float32)
@staticmethod
def affine_transform(pt, t):
"""
Apply affine transform to a bounding box given transform matrix t.
Parameters:
----------
pt : numpy.ndarray
Bounding box with shape (1, 2).
t : numpy.ndarray
Transformation matrix with shape (2, 3).
Returns:
-------
numpy.ndarray
New bounding box with shape (1, 2).
"""
new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32).T
new_pt = np.dot(t, new_pt)
return new_pt[:2]
class Tuple(object):
"""
Wrap multiple batchify functions to form a function apply each input function on each
input fields respectively.
"""
def __init__(self, fn, *args):
if isinstance(fn, (list, tuple)):
self._fn = fn
else:
self._fn = (fn,) + args
def __call__(self, data):
"""
Batchify the input data.
Parameters:
----------
data : list
The samples to batchfy. Each sample should contain N attributes.
Returns:
-------
tuple
A tuple of length N. Contains the batchified result of each attribute in the input.
"""
ret = []
for i, ele_fn in enumerate(self._fn):
ret.append(ele_fn([ele[i] for ele in data]))
return tuple(ret)
class Stack(object):
"""
Stack the input data samples to construct the batch.
"""
def __call__(self, data):
"""
Batchify the input data.
Parameters:
----------
data : list
The input data samples
Returns:
-------
NDArray
Result.
"""
return self._stack_arrs(data, True)
@staticmethod
def _stack_arrs(arrs, use_shared_mem=False):
"""
Internal imple for stacking arrays.
"""
if isinstance(arrs[0], mx.nd.NDArray):
if use_shared_mem:
out = mx.nd.empty((len(arrs),) + arrs[0].shape, dtype=arrs[0].dtype,
ctx=mx.Context("cpu_shared", 0))
return mx.nd.stack(*arrs, out=out)
else:
return mx.nd.stack(*arrs)
else:
out = np.asarray(arrs)
if use_shared_mem:
return mx.nd.array(out, ctx=mx.Context("cpu_shared", 0))
else:
return mx.nd.array(out)
class Pad(object):
"""
Pad the input ndarrays along the specific padding axis and stack them to get the output.
"""
def __init__(self, axis=0, pad_val=0, num_shards=1, ret_length=False):
self._axis = axis
self._pad_val = pad_val
self._num_shards = num_shards
self._ret_length = ret_length
def __call__(self, data):
"""
Batchify the input data.
Parameters:
----------
data : list
A list of N samples. Each sample can be 1) ndarray or
2) a list/tuple of ndarrays
Returns:
-------
NDArray
Data in the minibatch. Shape is (N, ...)
NDArray, optional
The sequences' original lengths at the padded axis. Shape is (N,). This will only be
returned in `ret_length` is True.
"""
if isinstance(data[0], (mx.nd.NDArray, np.ndarray, list)):
padded_arr, original_length = self._pad_arrs_to_max_length(
data, self._axis, self._pad_val, self._num_shards, True)
if self._ret_length:
return padded_arr, original_length
else:
return padded_arr
else:
raise NotImplementedError
@staticmethod
def _pad_arrs_to_max_length(arrs, pad_axis, pad_val, num_shards=1, use_shared_mem=False):
"""
Inner Implementation of the Pad batchify.
"""
if not isinstance(arrs[0], (mx.nd.NDArray, np.ndarray)):
arrs = [np.asarray(ele) for ele in arrs]
if isinstance(pad_axis, tuple):
original_length = []
for axis in pad_axis:
original_length.append(np.array([ele.shape[axis] for ele in arrs]))
original_length = np.stack(original_length).T
else:
original_length = np.array([ele.shape[pad_axis] for ele in arrs])
pad_axis = [pad_axis]
if len(original_length) % num_shards != 0:
logging.warning(
'Batch size cannot be evenly split. Trying to shard %d items into %d shards',
len(original_length), num_shards)
original_length = np.array_split(original_length, num_shards)
max_lengths = [np.max(ll, axis=0, keepdims=len(pad_axis) == 1) for ll in original_length]
# add batch dimension
ret_shape = [[ll.shape[0], ] + list(arrs[0].shape) for ll in original_length]
for i, shape in enumerate(ret_shape):
for j, axis in enumerate(pad_axis):
shape[1 + axis] = max_lengths[i][j]
if use_shared_mem:
ret = [mx.nd.full(shape=tuple(shape), val=pad_val, ctx=mx.Context('cpu_shared', 0),
dtype=arrs[0].dtype) for shape in ret_shape]
original_length = [mx.nd.array(ll, ctx=mx.Context('cpu_shared', 0),
dtype=np.int32) for ll in original_length]
else:
ret = [mx.nd.full(shape=tuple(shape), val=pad_val, dtype=arrs[0].dtype) for shape in
ret_shape]
original_length = [mx.nd.array(ll, dtype=np.int32) for ll in original_length]
for i, arr in enumerate(arrs):
if ret[i // ret[0].shape[0]].shape[1:] == arr.shape:
ret[i // ret[0].shape[0]][i % ret[0].shape[0]] = arr
else:
slices = [slice(0, ll) for ll in arr.shape]
ret[i // ret[0].shape[0]][i % ret[0].shape[0]][tuple(slices)] = arr
if len(ret) == len(original_length) == 1:
return ret[0], original_length[0]
return ret, original_length
def get_post_transform(orig_w, orig_h, out_w, out_h):
"""Get the post prediction affine transforms. This will be used to adjust the prediction results
according to original coco image resolutions.
Parameters:
----------
orig_w : int
Original width of the image.
orig_h : int
Original height of the image.
out_w : int
Width of the output image after prediction.
out_h : int
Height of the output image after prediction.
Returns:
-------
numpy.ndarray
Affine transform matrix 3x2.
"""
s = max(orig_w, orig_h) * 1.0
c = np.array([orig_w / 2., orig_h / 2.], dtype=np.float32)
trans_output = CocoDetValTransform.get_affine_transform(c, s, 0, [out_w, out_h], inv=True)
return trans_output
class CocoDetMetaInfo(DatasetMetaInfo):
def __init__(self):
super(CocoDetMetaInfo, self).__init__()
self.label = "COCO"
self.short_label = "coco"
self.root_dir_name = "coco"
self.dataset_class = CocoDetDataset
self.num_training_samples = None
self.in_channels = 3
self.num_classes = CocoDetDataset.classes
self.input_image_size = (512, 512)
self.train_metric_capts = None
self.train_metric_names = None
self.train_metric_extra_kwargs = None
self.val_metric_capts = None
self.val_metric_names = None
self.test_metric_capts = ["Val.mAP"]
self.test_metric_names = ["CocoDetMApMetric"]
self.test_metric_extra_kwargs = [
{"name": "mAP",
"img_height": 512,
"coco_annotations_file_path": None,
"contiguous_id_to_json": None,
"data_shape": None,
"post_affine": get_post_transform}]
self.dataset_class_extra_kwargs = {"skip_empty": False}
self.saver_acc_ind = 0
self.do_transform = True
self.do_transform_first = False
self.last_batch = "keep"
self.batchify_fn = Tuple(Stack(), Pad(pad_val=-1))
self.val_transform = CocoDetValTransform
self.test_transform = CocoDetValTransform
self.ml_type = "det"
self.allow_hybridize = False
self.test_net_extra_kwargs = None
self.mean_rgb = (0.485, 0.456, 0.406)
self.std_rgb = (0.229, 0.224, 0.225)
def add_dataset_parser_arguments(self,
parser,
work_dir_path):
"""
Create python script parameters (for ImageNet-1K dataset metainfo).
Parameters:
----------
parser : ArgumentParser
ArgumentParser instance.
work_dir_path : str
Path to working directory.
"""
super(CocoDetMetaInfo, self).add_dataset_parser_arguments(parser, work_dir_path)
parser.add_argument(
"--input-size",
type=int,
nargs=2,
default=self.input_image_size,
help="size of the input for model")
def update(self,
args):
"""
Update ImageNet-1K dataset metainfo after user customizing.
Parameters:
----------
args : ArgumentParser
Main script arguments.
"""
super(CocoDetMetaInfo, self).update(args)
self.input_image_size = args.input_size
self.test_metric_extra_kwargs[0]["img_height"] = self.input_image_size[0]
self.test_metric_extra_kwargs[0]["data_shape"] = self.input_image_size
def update_from_dataset(self,
dataset):
"""
Update dataset metainfo after a dataset class instance creation.
Parameters:
----------
args : obj
A dataset class instance.
"""
self.test_metric_extra_kwargs[0]["coco_annotations_file_path"] = dataset.annotations_file_path
self.test_metric_extra_kwargs[0]["contiguous_id_to_json"] = dataset.contiguous_id_to_json
| 27,151 | 35.691892 | 119 | py |
imgclsmob | imgclsmob-master/gluon/datasets/ade20k_seg_dataset.py | """
ADE20K semantic segmentation dataset.
"""
import os
import numpy as np
import mxnet as mx
from PIL import Image
from .seg_dataset import SegDataset
from .voc_seg_dataset import VOCMetaInfo
class ADE20KSegDataset(SegDataset):
"""
ADE20K semantic segmentation dataset.
Parameters:
----------
root : str
Path to a folder with `ADEChallengeData2016` subfolder.
mode : str, default 'train'
'train', 'val', 'test', or 'demo'.
transform : callable, optional
A function that transforms the image.
"""
def __init__(self,
root,
mode="train",
transform=None,
**kwargs):
super(ADE20KSegDataset, self).__init__(
root=root,
mode=mode,
transform=transform,
**kwargs)
base_dir_path = os.path.join(root, "ADEChallengeData2016")
assert os.path.exists(base_dir_path), "Please prepare dataset"
image_dir_path = os.path.join(base_dir_path, "images")
mask_dir_path = os.path.join(base_dir_path, "annotations")
mode_dir_name = "training" if mode == "train" else "validation"
image_dir_path = os.path.join(image_dir_path, mode_dir_name)
mask_dir_path = os.path.join(mask_dir_path, mode_dir_name)
self.images = []
self.masks = []
for image_file_name in os.listdir(image_dir_path):
image_file_stem, _ = os.path.splitext(image_file_name)
if image_file_name.endswith(".jpg"):
image_file_path = os.path.join(image_dir_path, image_file_name)
mask_file_name = image_file_stem + ".png"
mask_file_path = os.path.join(mask_dir_path, mask_file_name)
if os.path.isfile(mask_file_path):
self.images.append(image_file_path)
self.masks.append(mask_file_path)
else:
print("Cannot find the mask: {}".format(mask_file_path))
assert (len(self.images) == len(self.masks))
if len(self.images) == 0:
raise RuntimeError("Found 0 images in subfolders of: {}\n".format(base_dir_path))
def __getitem__(self, index):
image = Image.open(self.images[index]).convert("RGB")
# image = mx.image.imread(self.images[index])
if self.mode == "demo":
image = self._img_transform(image)
if self.transform is not None:
image = self.transform(image)
return image, os.path.basename(self.images[index])
mask = Image.open(self.masks[index])
# mask = mx.image.imread(self.masks[index])
if self.mode == "train":
image, mask = self._train_sync_transform(image, mask)
elif self.mode == "val":
image, mask = self._val_sync_transform(image, mask)
else:
assert (self.mode == "test")
image = self._img_transform(image)
mask = self._mask_transform(mask)
if self.transform is not None:
image = self.transform(image)
return image, mask
classes = 150
vague_idx = 150
use_vague = True
background_idx = -1
ignore_bg = False
@staticmethod
def _mask_transform(mask):
np_mask = np.array(mask).astype(np.int32)
np_mask[np_mask == 0] = ADE20KSegDataset.vague_idx + 1
np_mask -= 1
return mx.nd.array(np_mask, mx.cpu())
def __len__(self):
return len(self.images)
class ADE20KMetaInfo(VOCMetaInfo):
def __init__(self):
super(ADE20KMetaInfo, self).__init__()
self.label = "ADE20K"
self.short_label = "voc"
self.root_dir_name = "ade20k"
self.dataset_class = ADE20KSegDataset
self.num_classes = ADE20KSegDataset.classes
self.test_metric_extra_kwargs = [
{"vague_idx": ADE20KSegDataset.vague_idx,
"use_vague": ADE20KSegDataset.use_vague,
"macro_average": False},
{"num_classes": ADE20KSegDataset.classes,
"vague_idx": ADE20KSegDataset.vague_idx,
"use_vague": ADE20KSegDataset.use_vague,
"bg_idx": ADE20KSegDataset.background_idx,
"ignore_bg": ADE20KSegDataset.ignore_bg,
"macro_average": False}]
| 4,339 | 34 | 93 | py |
imgclsmob | imgclsmob-master/gluon/datasets/dataset_metainfo.py | """
Base dataset metainfo class.
"""
import os
class DatasetMetaInfo(object):
"""
Base descriptor of dataset.
"""
def __init__(self):
self.use_imgrec = False
self.do_transform = False
self.do_transform_first = True
self.last_batch = None
self.batchify_fn = None
self.label = None
self.root_dir_name = None
self.root_dir_path = None
self.dataset_class = None
self.dataset_class_extra_kwargs = None
self.num_training_samples = None
self.in_channels = None
self.num_classes = None
self.input_image_size = None
self.train_metric_capts = None
self.train_metric_names = None
self.train_metric_extra_kwargs = None
self.train_use_weighted_sampler = False
self.val_metric_capts = None
self.val_metric_names = None
self.val_metric_extra_kwargs = None
self.test_metric_capts = None
self.test_metric_names = None
self.test_metric_extra_kwargs = None
self.saver_acc_ind = None
self.ml_type = None
self.allow_hybridize = True
self.train_net_extra_kwargs = {"root": os.path.join("~", ".mxnet", "models")}
self.test_net_extra_kwargs = None
self.load_ignore_extra = False
self.loss_name = None
self.loss_extra_kwargs = None
def add_dataset_parser_arguments(self,
parser,
work_dir_path):
"""
Create python script parameters (for dataset specific metainfo).
Parameters:
----------
parser : ArgumentParser
ArgumentParser instance.
work_dir_path : str
Path to working directory.
"""
parser.add_argument(
"--data-dir",
type=str,
default=os.path.join(work_dir_path, self.root_dir_name),
help="path to directory with {} dataset".format(self.label))
parser.add_argument(
"--num-classes",
type=int,
default=self.num_classes,
help="number of classes")
parser.add_argument(
"--in-channels",
type=int,
default=self.in_channels,
help="number of input channels")
parser.add_argument(
"--net-root",
type=str,
default=os.path.join("~", ".mxnet", "models"),
help="root for pretrained net cache")
def update(self,
args):
"""
Update dataset metainfo after user customizing.
Parameters:
----------
args : ArgumentParser
Main script arguments.
"""
self.root_dir_path = args.data_dir
self.num_classes = args.num_classes
self.in_channels = args.in_channels
self.train_net_extra_kwargs["root"] = args.net_root
def update_from_dataset(self,
dataset):
"""
Update dataset metainfo after a dataset class instance creation.
Parameters:
----------
args : obj
A dataset class instance.
"""
pass
| 3,226 | 29.158879 | 85 | py |
imgclsmob | imgclsmob-master/gluon/datasets/seg_dataset.py | import random
import numpy as np
import mxnet as mx
from PIL import Image, ImageOps, ImageFilter
from mxnet.gluon.data import dataset
class SegDataset(dataset.Dataset):
"""
Segmentation base dataset.
Parameters:
----------
root : str
Path to data folder.
mode : str
'train', 'val', 'test', or 'demo'.
transform : callable
A function that transforms the image.
"""
def __init__(self,
root,
mode,
transform,
base_size=520,
crop_size=480):
assert (mode in ("train", "val", "test", "demo"))
self.root = root
self.mode = mode
self.transform = transform
self.base_size = base_size
self.crop_size = crop_size
def _val_sync_transform(self, image, mask, ctx=mx.cpu()):
short_size = self.crop_size
w, h = image.size
if w > h:
oh = short_size
ow = int(float(w * oh) / h)
else:
ow = short_size
oh = int(float(h * ow) / w)
image = image.resize((ow, oh), Image.BILINEAR)
mask = mask.resize((ow, oh), Image.NEAREST)
# Center crop:
outsize = self.crop_size
x1 = int(round(0.5 * (ow - outsize)))
y1 = int(round(0.5 * (oh - outsize)))
image = image.crop((x1, y1, x1 + outsize, y1 + outsize))
mask = mask.crop((x1, y1, x1 + outsize, y1 + outsize))
# Final transform:
image, mask = self._img_transform(image, ctx=ctx), self._mask_transform(mask, ctx=ctx)
return image, mask
def _train_sync_transform(self, image, mask, ctx=mx.cpu()):
# Random mirror:
if random.random() < 0.5:
image = image.transpose(Image.FLIP_LEFT_RIGHT)
mask = mask.transpose(Image.FLIP_LEFT_RIGHT)
# Random scale (short edge):
short_size = random.randint(int(self.base_size * 0.5), int(self.base_size * 2.0))
w, h = image.size
if w > h:
oh = short_size
ow = int(float(w * oh) / h)
else:
ow = short_size
oh = int(float(h * ow) / w)
image = image.resize((ow, oh), Image.BILINEAR)
mask = mask.resize((ow, oh), Image.NEAREST)
# Pad crop:
crop_size = self.crop_size
if short_size < crop_size:
padh = crop_size - oh if oh < crop_size else 0
padw = crop_size - ow if ow < crop_size else 0
image = ImageOps.expand(image, border=(0, 0, padw, padh), fill=0)
mask = ImageOps.expand(mask, border=(0, 0, padw, padh), fill=0)
# Random crop crop_size:
w, h = image.size
x1 = random.randint(0, w - crop_size)
y1 = random.randint(0, h - crop_size)
image = image.crop((x1, y1, x1 + crop_size, y1 + crop_size))
mask = mask.crop((x1, y1, x1 + crop_size, y1 + crop_size))
# Gaussian blur as in PSP:
if random.random() < 0.5:
image = image.filter(ImageFilter.GaussianBlur(radius=random.random()))
# Final transform:
image, mask = self._img_transform(image, ctx=ctx), self._mask_transform(mask, ctx=ctx)
return image, mask
@staticmethod
def _img_transform(image, ctx=mx.cpu()):
return mx.nd.array(np.array(image), ctx=ctx)
@staticmethod
def _mask_transform(mask, ctx=mx.cpu()):
return mx.nd.array(np.array(mask), ctx=ctx, dtype=np.int32)
| 3,490 | 34.622449 | 94 | py |
imgclsmob | imgclsmob-master/gluon/datasets/coco_hpe2_dataset.py | """
COCO keypoint detection (2D multiple human pose estimation) dataset (for Lightweight OpenPose).
"""
import os
import json
import math
import cv2
from operator import itemgetter
import numpy as np
from mxnet.gluon.data import dataset
from .dataset_metainfo import DatasetMetaInfo
class CocoHpe2Dataset(dataset.Dataset):
"""
COCO keypoint detection (2D multiple human pose estimation) dataset.
Parameters:
----------
root : string
Path to `annotations`, `train2017`, and `val2017` folders.
mode : string, default 'train'
'train', 'val', 'test', or 'demo'.
transform : callable, optional
A function that transforms the image.
"""
def __init__(self,
root,
mode="train",
transform=None):
super(CocoHpe2Dataset, self).__init__()
self._root = os.path.expanduser(root)
self.mode = mode
self.transform = transform
mode_name = "train" if mode == "train" else "val"
annotations_dir_path = os.path.join(root, "annotations")
annotations_file_path = os.path.join(annotations_dir_path, "person_keypoints_" + mode_name + "2017.json")
with open(annotations_file_path, "r") as f:
self.file_names = json.load(f)["images"]
self.image_dir_path = os.path.join(root, mode_name + "2017")
self.annotations_file_path = annotations_file_path
def __str__(self):
return self.__class__.__name__ + "(" + self._root + ")"
def __len__(self):
return len(self.file_names)
def __getitem__(self, idx):
file_name = self.file_names[idx]["file_name"]
image_file_path = os.path.join(self.image_dir_path, file_name)
image = cv2.imread(image_file_path, flags=cv2.IMREAD_COLOR)
# image = cv2.cvtColor(img, code=cv2.COLOR_BGR2RGB)
img_mean = (128, 128, 128)
img_scale = 1.0 / 256
base_height = 368
stride = 8
pad_value = (0, 0, 0)
height, width, _ = image.shape
image = self.normalize(image, img_mean, img_scale)
ratio = base_height / float(image.shape[0])
image = cv2.resize(image, (0, 0), fx=ratio, fy=ratio, interpolation=cv2.INTER_CUBIC)
min_dims = [base_height, max(image.shape[1], base_height)]
image, pad = self.pad_width(
image,
stride,
pad_value,
min_dims)
image = image.astype(np.float32)
image = image.transpose((2, 0, 1))
# image = torch.from_numpy(image)
# if self.transform is not None:
# image = self.transform(image)
image_id = int(os.path.splitext(os.path.basename(file_name))[0])
label = np.array([image_id, 1.0] + pad + [height, width], np.float32)
# label = torch.from_numpy(label)
return image, label
@staticmethod
def normalize(img,
img_mean,
img_scale):
img = np.array(img, dtype=np.float32)
img = (img - img_mean) * img_scale
return img
@staticmethod
def pad_width(img,
stride,
pad_value,
min_dims):
h, w, _ = img.shape
h = min(min_dims[0], h)
min_dims[0] = math.ceil(min_dims[0] / float(stride)) * stride
min_dims[1] = max(min_dims[1], w)
min_dims[1] = math.ceil(min_dims[1] / float(stride)) * stride
top = int(math.floor((min_dims[0] - h) / 2.0))
left = int(math.floor((min_dims[1] - w) / 2.0))
bottom = int(min_dims[0] - h - top)
right = int(min_dims[1] - w - left)
pad = [top, left, bottom, right]
padded_img = cv2.copyMakeBorder(
src=img,
top=top,
bottom=bottom,
left=left,
right=right,
borderType=cv2.BORDER_CONSTANT,
value=pad_value)
return padded_img, pad
# ---------------------------------------------------------------------------------------------------------------------
class CocoHpe2ValTransform(object):
def __init__(self,
ds_metainfo):
self.ds_metainfo = ds_metainfo
def __call__(self, src, label):
return src, label
def extract_keypoints(heatmap,
all_keypoints,
total_keypoint_num):
heatmap[heatmap < 0.1] = 0
heatmap_with_borders = np.pad(heatmap, [(2, 2), (2, 2)], mode="constant")
heatmap_center = heatmap_with_borders[1:heatmap_with_borders.shape[0] - 1, 1:heatmap_with_borders.shape[1] - 1]
heatmap_left = heatmap_with_borders[1:heatmap_with_borders.shape[0] - 1, 2:heatmap_with_borders.shape[1]]
heatmap_right = heatmap_with_borders[1:heatmap_with_borders.shape[0] - 1, 0:heatmap_with_borders.shape[1] - 2]
heatmap_up = heatmap_with_borders[2:heatmap_with_borders.shape[0], 1:heatmap_with_borders.shape[1] - 1]
heatmap_down = heatmap_with_borders[0:heatmap_with_borders.shape[0] - 2, 1:heatmap_with_borders.shape[1] - 1]
heatmap_peaks = (heatmap_center > heatmap_left) &\
(heatmap_center > heatmap_right) &\
(heatmap_center > heatmap_up) &\
(heatmap_center > heatmap_down)
heatmap_peaks = heatmap_peaks[1:heatmap_center.shape[0] - 1, 1:heatmap_center.shape[1] - 1]
keypoints = list(zip(np.nonzero(heatmap_peaks)[1], np.nonzero(heatmap_peaks)[0])) # (w, h)
keypoints = sorted(keypoints, key=itemgetter(0))
suppressed = np.zeros(len(keypoints), np.uint8)
keypoints_with_score_and_id = []
keypoint_num = 0
for i in range(len(keypoints)):
if suppressed[i]:
continue
for j in range(i + 1, len(keypoints)):
if math.sqrt((keypoints[i][0] - keypoints[j][0]) ** 2 + (keypoints[i][1] - keypoints[j][1]) ** 2) < 6:
suppressed[j] = 1
keypoint_with_score_and_id = (
keypoints[i][0],
keypoints[i][1],
heatmap[keypoints[i][1], keypoints[i][0]],
total_keypoint_num + keypoint_num)
keypoints_with_score_and_id.append(keypoint_with_score_and_id)
keypoint_num += 1
all_keypoints.append(keypoints_with_score_and_id)
return keypoint_num
def group_keypoints(all_keypoints_by_type,
pafs,
pose_entry_size=20,
min_paf_score=0.05):
def linspace2d(start, stop, n=10):
points = 1 / (n - 1) * (stop - start)
return points[:, None] * np.arange(n) + start[:, None]
BODY_PARTS_KPT_IDS = [[1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], [1, 8], [8, 9], [9, 10], [1, 11],
[11, 12], [12, 13], [1, 0], [0, 14], [14, 16], [0, 15], [15, 17], [2, 16], [5, 17]]
BODY_PARTS_PAF_IDS = ([12, 13], [20, 21], [14, 15], [16, 17], [22, 23], [24, 25], [0, 1], [2, 3], [4, 5],
[6, 7], [8, 9], [10, 11], [28, 29], [30, 31], [34, 35], [32, 33], [36, 37], [18, 19],
[26, 27])
pose_entries = []
all_keypoints = np.array([item for sublist in all_keypoints_by_type for item in sublist])
for part_id in range(len(BODY_PARTS_PAF_IDS)):
part_pafs = pafs[:, :, BODY_PARTS_PAF_IDS[part_id]]
kpts_a = all_keypoints_by_type[BODY_PARTS_KPT_IDS[part_id][0]]
kpts_b = all_keypoints_by_type[BODY_PARTS_KPT_IDS[part_id][1]]
num_kpts_a = len(kpts_a)
num_kpts_b = len(kpts_b)
kpt_a_id = BODY_PARTS_KPT_IDS[part_id][0]
kpt_b_id = BODY_PARTS_KPT_IDS[part_id][1]
if num_kpts_a == 0 and num_kpts_b == 0: # no keypoints for such body part
continue
elif num_kpts_a == 0: # body part has just 'b' keypoints
for i in range(num_kpts_b):
num = 0
for j in range(len(pose_entries)): # check if already in some pose, was added by another body part
if pose_entries[j][kpt_b_id] == kpts_b[i][3]:
num += 1
continue
if num == 0:
pose_entry = np.ones(pose_entry_size) * -1
pose_entry[kpt_b_id] = kpts_b[i][3] # keypoint idx
pose_entry[-1] = 1 # num keypoints in pose
pose_entry[-2] = kpts_b[i][2] # pose score
pose_entries.append(pose_entry)
continue
elif num_kpts_b == 0: # body part has just 'a' keypoints
for i in range(num_kpts_a):
num = 0
for j in range(len(pose_entries)):
if pose_entries[j][kpt_a_id] == kpts_a[i][3]:
num += 1
continue
if num == 0:
pose_entry = np.ones(pose_entry_size) * -1
pose_entry[kpt_a_id] = kpts_a[i][3]
pose_entry[-1] = 1
pose_entry[-2] = kpts_a[i][2]
pose_entries.append(pose_entry)
continue
connections = []
for i in range(num_kpts_a):
kpt_a = np.array(kpts_a[i][0:2])
for j in range(num_kpts_b):
kpt_b = np.array(kpts_b[j][0:2])
mid_point = [(), ()]
mid_point[0] = (int(round((kpt_a[0] + kpt_b[0]) * 0.5)),
int(round((kpt_a[1] + kpt_b[1]) * 0.5)))
mid_point[1] = mid_point[0]
vec = [kpt_b[0] - kpt_a[0], kpt_b[1] - kpt_a[1]]
vec_norm = math.sqrt(vec[0] ** 2 + vec[1] ** 2)
if vec_norm == 0:
continue
vec[0] /= vec_norm
vec[1] /= vec_norm
cur_point_score = (vec[0] * part_pafs[mid_point[0][1], mid_point[0][0], 0] +
vec[1] * part_pafs[mid_point[1][1], mid_point[1][0], 1])
height_n = pafs.shape[0] // 2
success_ratio = 0
point_num = 10 # number of points to integration over paf
if cur_point_score > -100:
passed_point_score = 0
passed_point_num = 0
x, y = linspace2d(kpt_a, kpt_b)
for point_idx in range(point_num):
px = int(round(x[point_idx]))
py = int(round(y[point_idx]))
paf = part_pafs[py, px, 0:2]
cur_point_score = vec[0] * paf[0] + vec[1] * paf[1]
if cur_point_score > min_paf_score:
passed_point_score += cur_point_score
passed_point_num += 1
success_ratio = passed_point_num / point_num
ratio = 0
if passed_point_num > 0:
ratio = passed_point_score / passed_point_num
ratio += min(height_n / vec_norm - 1, 0)
if ratio > 0 and success_ratio > 0.8:
score_all = ratio + kpts_a[i][2] + kpts_b[j][2]
connections.append([i, j, ratio, score_all])
if len(connections) > 0:
connections = sorted(connections, key=itemgetter(2), reverse=True)
num_connections = min(num_kpts_a, num_kpts_b)
has_kpt_a = np.zeros(num_kpts_a, dtype=np.int32)
has_kpt_b = np.zeros(num_kpts_b, dtype=np.int32)
filtered_connections = []
for row in range(len(connections)):
if len(filtered_connections) == num_connections:
break
i, j, cur_point_score = connections[row][0:3]
if not has_kpt_a[i] and not has_kpt_b[j]:
filtered_connections.append([kpts_a[i][3], kpts_b[j][3], cur_point_score])
has_kpt_a[i] = 1
has_kpt_b[j] = 1
connections = filtered_connections
if len(connections) == 0:
continue
if part_id == 0:
pose_entries = [np.ones(pose_entry_size) * -1 for _ in range(len(connections))]
for i in range(len(connections)):
pose_entries[i][BODY_PARTS_KPT_IDS[0][0]] = connections[i][0]
pose_entries[i][BODY_PARTS_KPT_IDS[0][1]] = connections[i][1]
pose_entries[i][-1] = 2
pose_entries[i][-2] = np.sum(all_keypoints[connections[i][0:2], 2]) + connections[i][2]
elif part_id == 17 or part_id == 18:
kpt_a_id = BODY_PARTS_KPT_IDS[part_id][0]
kpt_b_id = BODY_PARTS_KPT_IDS[part_id][1]
for i in range(len(connections)):
for j in range(len(pose_entries)):
if pose_entries[j][kpt_a_id] == connections[i][0] and pose_entries[j][kpt_b_id] == -1:
pose_entries[j][kpt_b_id] = connections[i][1]
elif pose_entries[j][kpt_b_id] == connections[i][1] and pose_entries[j][kpt_a_id] == -1:
pose_entries[j][kpt_a_id] = connections[i][0]
continue
else:
kpt_a_id = BODY_PARTS_KPT_IDS[part_id][0]
kpt_b_id = BODY_PARTS_KPT_IDS[part_id][1]
for i in range(len(connections)):
num = 0
for j in range(len(pose_entries)):
if pose_entries[j][kpt_a_id] == connections[i][0]:
pose_entries[j][kpt_b_id] = connections[i][1]
num += 1
pose_entries[j][-1] += 1
pose_entries[j][-2] += all_keypoints[connections[i][1], 2] + connections[i][2]
if num == 0:
pose_entry = np.ones(pose_entry_size) * -1
pose_entry[kpt_a_id] = connections[i][0]
pose_entry[kpt_b_id] = connections[i][1]
pose_entry[-1] = 2
pose_entry[-2] = np.sum(all_keypoints[connections[i][0:2], 2]) + connections[i][2]
pose_entries.append(pose_entry)
filtered_entries = []
for i in range(len(pose_entries)):
if pose_entries[i][-1] < 3 or (pose_entries[i][-2] / pose_entries[i][-1] < 0.2):
continue
filtered_entries.append(pose_entries[i])
pose_entries = np.asarray(filtered_entries)
return pose_entries, all_keypoints
def convert_to_coco_format(pose_entries, all_keypoints):
coco_keypoints = []
scores = []
for n in range(len(pose_entries)):
if len(pose_entries[n]) == 0:
continue
keypoints = [0] * 17 * 3
to_coco_map = [0, -1, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3]
person_score = pose_entries[n][-2]
position_id = -1
for keypoint_id in pose_entries[n][:-2]:
position_id += 1
if position_id == 1: # no 'neck' in COCO
continue
cx, cy, score, visibility = 0, 0, 0, 0 # keypoint not found
if keypoint_id != -1:
cx, cy, score = all_keypoints[int(keypoint_id), 0:3]
cx = cx + 0.5
cy = cy + 0.5
visibility = 1
keypoints[to_coco_map[position_id] * 3 + 0] = cx
keypoints[to_coco_map[position_id] * 3 + 1] = cy
keypoints[to_coco_map[position_id] * 3 + 2] = visibility
coco_keypoints.append(keypoints)
scores.append(person_score * max(0, (pose_entries[n][-1] - 1))) # -1 for 'neck'
return coco_keypoints, scores
def recalc_pose(pred,
label):
label_img_id = label[:, 0].astype(np.int32)
# label_score = label[:, 1]
pads = label[:, 2:6].astype(np.int32)
heights = label[:, 6].astype(np.int32)
widths = label[:, 7].astype(np.int32)
keypoints = 19
stride = 8
heatmap2ds = pred[:, :keypoints]
paf2ds = pred[:, keypoints:(3 * keypoints)]
pred_pts_score = []
pred_person_score = []
label_img_id_ = []
batch = pred.shape[0]
for batch_i in range(batch):
label_img_id_i = label_img_id[batch_i]
pad = list(pads[batch_i])
height = int(heights[batch_i])
width = int(widths[batch_i])
heatmap2d = heatmap2ds[batch_i]
paf2d = paf2ds[batch_i]
heatmaps = np.transpose(heatmap2d, (1, 2, 0))
heatmaps = cv2.resize(heatmaps, (0, 0), fx=stride, fy=stride, interpolation=cv2.INTER_CUBIC)
heatmaps = heatmaps[pad[0]:heatmaps.shape[0] - pad[2], pad[1]:heatmaps.shape[1] - pad[3]:, :]
heatmaps = cv2.resize(heatmaps, (width, height), interpolation=cv2.INTER_CUBIC)
pafs = np.transpose(paf2d, (1, 2, 0))
pafs = cv2.resize(pafs, (0, 0), fx=stride, fy=stride, interpolation=cv2.INTER_CUBIC)
pafs = pafs[pad[0]:pafs.shape[0] - pad[2], pad[1]:pafs.shape[1] - pad[3], :]
pafs = cv2.resize(pafs, (width, height), interpolation=cv2.INTER_CUBIC)
total_keypoints_num = 0
all_keypoints_by_type = []
for kpt_idx in range(18): # 19th for bg
total_keypoints_num += extract_keypoints(
heatmaps[:, :, kpt_idx],
all_keypoints_by_type,
total_keypoints_num)
pose_entries, all_keypoints = group_keypoints(
all_keypoints_by_type,
pafs)
coco_keypoints, scores = convert_to_coco_format(
pose_entries,
all_keypoints)
pred_pts_score.append(coco_keypoints)
pred_person_score.append(scores)
label_img_id_.append([label_img_id_i] * len(scores))
return np.array(pred_pts_score).reshape((-1, 17, 3)), np.array(pred_person_score)[0], np.array(label_img_id_[0])
# ---------------------------------------------------------------------------------------------------------------------
class CocoHpe2MetaInfo(DatasetMetaInfo):
def __init__(self):
super(CocoHpe2MetaInfo, self).__init__()
self.label = "COCO"
self.short_label = "coco"
self.root_dir_name = "coco"
self.dataset_class = CocoHpe2Dataset
self.num_training_samples = None
self.in_channels = 3
self.num_classes = 17
self.input_image_size = (368, 368)
self.train_metric_capts = None
self.train_metric_names = None
self.train_metric_extra_kwargs = None
self.val_metric_capts = None
self.val_metric_names = None
self.test_metric_capts = ["Val.CocoOksAp"]
self.test_metric_names = ["CocoHpeOksApMetric"]
self.test_metric_extra_kwargs = [
{"name": "OksAp",
"coco_annotations_file_path": None,
"use_file": False,
"pose_postprocessing_fn": lambda x, y: recalc_pose(x, y)}]
self.saver_acc_ind = 0
self.do_transform = True
self.val_transform = CocoHpe2ValTransform
self.test_transform = CocoHpe2ValTransform
self.ml_type = "hpe"
self.test_net_extra_kwargs = None
self.mean_rgb = (0.485, 0.456, 0.406)
self.std_rgb = (0.229, 0.224, 0.225)
self.load_ignore_extra = False
def add_dataset_parser_arguments(self,
parser,
work_dir_path):
"""
Create python script parameters (for ImageNet-1K dataset metainfo).
Parameters:
----------
parser : ArgumentParser
ArgumentParser instance.
work_dir_path : str
Path to working directory.
"""
super(CocoHpe2MetaInfo, self).add_dataset_parser_arguments(parser, work_dir_path)
parser.add_argument(
"--input-size",
type=int,
nargs=2,
default=self.input_image_size,
help="size of the input for model")
parser.add_argument(
"--load-ignore-extra",
action="store_true",
help="ignore extra layers in the source PyTroch model")
def update(self,
args):
"""
Update ImageNet-1K dataset metainfo after user customizing.
Parameters:
----------
args : ArgumentParser
Main script arguments.
"""
super(CocoHpe2MetaInfo, self).update(args)
self.input_image_size = args.input_size
self.load_ignore_extra = args.load_ignore_extra
def update_from_dataset(self,
dataset):
"""
Update dataset metainfo after a dataset class instance creation.
Parameters:
----------
args : obj
A dataset class instance.
"""
self.test_metric_extra_kwargs[0]["coco_annotations_file_path"] = dataset.annotations_file_path
| 20,786 | 39.8389 | 119 | py |
imgclsmob | imgclsmob-master/gluon/datasets/svhn_cls_dataset.py | """
SVHN classification dataset.
"""
import os
import numpy as np
import mxnet as mx
from mxnet import gluon
from mxnet.gluon.utils import download, check_sha1
from .cifar10_cls_dataset import CIFAR10MetaInfo
class SVHN(gluon.data.dataset._DownloadedDataset):
"""
SVHN image classification dataset from http://ufldl.stanford.edu/housenumbers/.
Each sample is an image (in 3D NDArray) with shape (32, 32, 3).
Note: The SVHN dataset assigns the label `10` to the digit `0`. However, in this Dataset,
we assign the label `0` to the digit `0`.
Parameters:
----------
root : str, default $MXNET_HOME/datasets/svhn
Path to temp folder for storing data.
mode : str, default 'train'
'train', 'val', or 'test'.
transform : function, default None
A user defined callback that transforms each sample.
"""
def __init__(self,
root=os.path.join("~", ".mxnet", "datasets", "svhn"),
mode="train",
transform=None):
self._mode = mode
self._train_data = [("http://ufldl.stanford.edu/housenumbers/train_32x32.mat", "train_32x32.mat",
"e6588cae42a1a5ab5efe608cc5cd3fb9aaffd674")]
self._test_data = [("http://ufldl.stanford.edu/housenumbers/test_32x32.mat", "test_32x32.mat",
"29b312382ca6b9fba48d41a7b5c19ad9a5462b20")]
super(SVHN, self).__init__(root, transform)
def _get_data(self):
if any(not os.path.exists(path) or not check_sha1(path, sha1) for path, sha1 in
((os.path.join(self._root, name), sha1) for _, name, sha1 in self._train_data + self._test_data)):
for url, _, sha1 in self._train_data + self._test_data:
download(url=url, path=self._root, sha1_hash=sha1)
if self._mode == "train":
data_files = self._train_data[0]
else:
data_files = self._test_data[0]
import scipy.io as sio
loaded_mat = sio.loadmat(os.path.join(self._root, data_files[1]))
data = loaded_mat["X"]
data = np.transpose(data, (3, 0, 1, 2))
self._data = mx.nd.array(data, dtype=data.dtype)
self._label = loaded_mat["y"].astype(np.int32).squeeze()
np.place(self._label, self._label == 10, 0)
class SVHNMetaInfo(CIFAR10MetaInfo):
def __init__(self):
super(SVHNMetaInfo, self).__init__()
self.label = "SVHN"
self.root_dir_name = "svhn"
self.dataset_class = SVHN
self.num_training_samples = 73257
| 2,574 | 35.785714 | 113 | py |
imgclsmob | imgclsmob-master/gluon/datasets/coco_hpe3_dataset.py | """
COCO keypoint detection (2D multiple human pose estimation) dataset (for IBPPose).
"""
import os
# import json
import math
import cv2
import numpy as np
from mxnet.gluon.data import dataset
from .dataset_metainfo import DatasetMetaInfo
class CocoHpe3Dataset(dataset.Dataset):
"""
COCO keypoint detection (2D multiple human pose estimation) dataset.
Parameters:
----------
root : string
Path to `annotations`, `train2017`, and `val2017` folders.
mode : string, default 'train'
'train', 'val', 'test', or 'demo'.
transform : callable, optional
A function that transforms the image.
"""
def __init__(self,
root,
mode="train",
transform=None):
super(CocoHpe3Dataset, self).__init__()
self._root = os.path.expanduser(root)
self.mode = mode
self.transform = transform
mode_name = "train" if mode == "train" else "val"
annotations_dir_path = os.path.join(root, "annotations")
annotations_file_path = os.path.join(annotations_dir_path, "person_keypoints_" + mode_name + "2017.json")
# with open(annotations_file_path, "r") as f:
# self.file_names = json.load(f)["images"]
self.image_dir_path = os.path.join(root, mode_name + "2017")
self.annotations_file_path = annotations_file_path
from pycocotools.coco import COCO
self.coco_gt = COCO(self.annotations_file_path)
self.validation_ids = self.coco_gt.getImgIds()[:]
def __str__(self):
return self.__class__.__name__ + "(" + self._root + ")"
def __len__(self):
return len(self.validation_ids)
def __getitem__(self, idx):
# file_name = self.file_names[idx]["file_name"]
image_id = self.validation_ids[idx]
file_name = self.coco_gt.imgs[image_id]["file_name"]
image_file_path = os.path.join(self.image_dir_path, file_name)
image = cv2.imread(image_file_path, flags=cv2.IMREAD_COLOR)
# image = cv2.cvtColor(img, code=cv2.COLOR_BGR2RGB)
image_src_shape = image.shape[:2]
boxsize = 512
max_downsample = 64
pad_value = 128
scale = boxsize / image.shape[0]
if scale * image.shape[0] > 2600 or scale * image.shape[1] > 3800:
scale = min(2600 / image.shape[0], 3800 / image.shape[1])
image = cv2.resize(image, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)
image, pad = self.pad_right_down_corner(image, max_downsample, pad_value)
image = np.float32(image / 255)
image = image.transpose((2, 0, 1))
# image_id = int(os.path.splitext(os.path.basename(file_name))[0])
label = np.array([image_id, 1.0] + pad + list(image_src_shape), np.float32)
return image, label
@staticmethod
def pad_right_down_corner(img,
stride,
pad_value):
h = img.shape[0]
w = img.shape[1]
pad = 4 * [None]
pad[0] = 0 # up
pad[1] = 0 # left
pad[2] = 0 if (h % stride == 0) else stride - (h % stride) # down
pad[3] = 0 if (w % stride == 0) else stride - (w % stride) # right
img_padded = img
pad_up = np.tile(img_padded[0:1, :, :] * 0 + pad_value, (pad[0], 1, 1))
img_padded = np.concatenate((pad_up, img_padded), axis=0)
pad_left = np.tile(img_padded[:, 0:1, :] * 0 + pad_value, (1, pad[1], 1))
img_padded = np.concatenate((pad_left, img_padded), axis=1)
pad_down = np.tile(img_padded[-2:-1, :, :] * 0 + pad_value, (pad[2], 1, 1))
img_padded = np.concatenate((img_padded, pad_down), axis=0)
pad_right = np.tile(img_padded[:, -2:-1, :] * 0 + pad_value, (1, pad[3], 1))
img_padded = np.concatenate((img_padded, pad_right), axis=1)
return img_padded, pad
# ---------------------------------------------------------------------------------------------------------------------
class CocoHpe2ValTransform(object):
def __init__(self,
ds_metainfo):
self.ds_metainfo = ds_metainfo
def __call__(self, src, label):
return src, label
def recalc_pose(pred,
label):
dt_gt_mapping = {0: 0, 1: None, 2: 6, 3: 8, 4: 10, 5: 5, 6: 7, 7: 9, 8: 12, 9: 14, 10: 16, 11: 11, 12: 13, 13: 15,
14: 2, 15: 1, 16: 4, 17: 3}
parts = ["nose", "neck", "Rsho", "Relb", "Rwri", "Lsho", "Lelb", "Lwri", "Rhip", "Rkne", "Rank", "Lhip", "Lkne",
"Lank", "Reye", "Leye", "Rear", "Lear"]
num_parts = len(parts)
parts_dict = dict(zip(parts, range(num_parts)))
limb_from = ['neck', 'neck', 'neck', 'neck', 'neck', 'nose', 'nose', 'Reye', 'Leye', 'neck', 'Rsho', 'Relb', 'neck',
'Lsho', 'Lelb', 'neck', 'Rhip', 'Rkne', 'neck', 'Lhip', 'Lkne', 'nose', 'nose', 'Rsho', 'Rhip', 'Lsho',
'Lhip', 'Rear', 'Lear', 'Rhip']
limb_to = ['nose', 'Reye', 'Leye', 'Rear', 'Lear', 'Reye', 'Leye', 'Rear', 'Lear', 'Rsho', 'Relb', 'Rwri', 'Lsho',
'Lelb', 'Lwri', 'Rhip', 'Rkne', 'Rank', 'Lhip', 'Lkne', 'Lank', 'Rsho', 'Lsho', 'Rhip', 'Lkne', 'Lhip',
'Rkne', 'Rsho', 'Lsho', 'Lhip']
limb_from = [parts_dict[n] for n in limb_from]
limb_to = [parts_dict[n] for n in limb_to]
assert limb_from == [x for x in [
1, 1, 1, 1, 1, 0, 0, 14, 15, 1, 2, 3, 1, 5, 6, 1, 8, 9, 1, 11, 12, 0, 0, 2, 8, 5, 11, 16, 17, 8]]
assert limb_to == [x for x in [
0, 14, 15, 16, 17, 14, 15, 16, 17, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 2, 5, 8, 12, 11, 9, 2, 5, 11]]
limbs_conn = list(zip(limb_from, limb_to))
limb_seq = limbs_conn
paf_layers = 30
num_layers = 50
stride = 4
label_img_id = label[:, 0].astype(np.int32)
# label_score = label[:, 1]
pads = label[:, 2:6].astype(np.int32)
image_src_shapes = label[:, 6:8].astype(np.int32)
pred_pts_score = []
pred_person_score = []
label_img_id_ = []
batch = pred.shape[0]
for batch_i in range(batch):
label_img_id_i = label_img_id[batch_i]
pad = list(pads[batch_i])
image_src_shape = list(image_src_shapes[batch_i])
output_blob = pred[batch_i].transpose((1, 2, 0))
output_paf = output_blob[:, :, :paf_layers]
output_heatmap = output_blob[:, :, paf_layers:num_layers]
heatmap = cv2.resize(output_heatmap, (0, 0), fx=stride, fy=stride, interpolation=cv2.INTER_CUBIC)
heatmap = heatmap[
pad[0]:(output_blob.shape[0] * stride - pad[2]),
pad[1]:(output_blob.shape[1] * stride - pad[3]),
:]
heatmap = cv2.resize(heatmap, (image_src_shape[1], image_src_shape[0]), interpolation=cv2.INTER_CUBIC)
paf = cv2.resize(output_paf, (0, 0), fx=stride, fy=stride, interpolation=cv2.INTER_CUBIC)
paf = paf[
pad[0]:(output_blob.shape[0] * stride - pad[2]),
pad[1]:(output_blob.shape[1] * stride - pad[3]),
:]
paf = cv2.resize(paf, (image_src_shape[1], image_src_shape[0]), interpolation=cv2.INTER_CUBIC)
all_peaks = find_peaks(heatmap)
connection_all, special_k = find_connections(all_peaks, paf, image_src_shape[0], limb_seq)
subset, candidate = find_people(connection_all, special_k, all_peaks, limb_seq)
for s in subset[..., 0]:
keypoint_indexes = s[:18]
person_keypoint_coordinates = []
for index in keypoint_indexes:
if index == -1:
X, Y, C = 0, 0, 0
else:
X, Y, C = list(candidate[index.astype(int)][:2]) + [1]
person_keypoint_coordinates.append([X, Y, C])
person_keypoint_coordinates_coco = [None] * 17
for dt_index, gt_index in dt_gt_mapping.items():
if gt_index is None:
continue
person_keypoint_coordinates_coco[gt_index] = person_keypoint_coordinates[dt_index]
pred_pts_score.append(person_keypoint_coordinates_coco)
pred_person_score.append(1 - 1.0 / s[18])
label_img_id_.append(label_img_id_i)
return np.array(pred_pts_score).reshape((-1, 17, 3)), np.array(pred_person_score), np.array(label_img_id_)
def find_peaks(heatmap_avg):
import torch
thre1 = 0.1
offset_radius = 2
all_peaks = []
peak_counter = 0
heatmap_avg = heatmap_avg.astype(np.float32)
filter_map = heatmap_avg[:, :, :18].copy().transpose((2, 0, 1))[None, ...]
filter_map = torch.from_numpy(filter_map).cuda()
filter_map = keypoint_heatmap_nms(filter_map, kernel=3, thre=thre1)
filter_map = filter_map.cpu().numpy().squeeze().transpose((1, 2, 0))
for part in range(18):
map_ori = heatmap_avg[:, :, part]
peaks_binary = filter_map[:, :, part]
peaks = list(zip(np.nonzero(peaks_binary)[1], np.nonzero(peaks_binary)[0])) # note reverse
refined_peaks_with_score = [refine_centroid(map_ori, anchor, offset_radius) for anchor in peaks]
id = range(peak_counter, peak_counter + len(refined_peaks_with_score))
peaks_with_score_and_id = [refined_peaks_with_score[i] + (id[i],) for i in range(len(id))]
all_peaks.append(peaks_with_score_and_id)
peak_counter += len(peaks)
return all_peaks
def keypoint_heatmap_nms(heat, kernel=3, thre=0.1):
from torch.nn import functional as F
# keypoint NMS on heatmap (score map)
pad = (kernel - 1) // 2
pad_heat = F.pad(heat, (pad, pad, pad, pad), mode="reflect")
hmax = F.max_pool2d(pad_heat, (kernel, kernel), stride=1, padding=0)
keep = (hmax == heat).float() * (heat >= thre).float()
return heat * keep
def refine_centroid(scorefmp, anchor, radius):
"""
Refine the centroid coordinate. It dose not affect the results after testing.
:param scorefmp: 2-D numpy array, original regressed score map
:param anchor: python tuple, (x,y) coordinates
:param radius: int, range of considered scores
:return: refined anchor, refined score
"""
x_c, y_c = anchor
x_min = x_c - radius
x_max = x_c + radius + 1
y_min = y_c - radius
y_max = y_c + radius + 1
if y_max > scorefmp.shape[0] or y_min < 0 or x_max > scorefmp.shape[1] or x_min < 0:
return anchor + (scorefmp[y_c, x_c], )
score_box = scorefmp[y_min:y_max, x_min:x_max]
x_grid, y_grid = np.mgrid[-radius:radius + 1, -radius:radius + 1]
offset_x = (score_box * x_grid).sum() / score_box.sum()
offset_y = (score_box * y_grid).sum() / score_box.sum()
x_refine = x_c + offset_x
y_refine = y_c + offset_y
refined_anchor = (x_refine, y_refine)
return refined_anchor + (score_box.mean(),)
def find_connections(all_peaks, paf_avg, image_width, limb_seq):
mid_num_ = 20
thre2 = 0.1
connect_ration = 0.8
connection_all = []
special_k = []
for k in range(len(limb_seq)):
score_mid = paf_avg[:, :, k]
candA = all_peaks[limb_seq[k][0]]
candB = all_peaks[limb_seq[k][1]]
nA = len(candA)
nB = len(candB)
if nA != 0 and nB != 0:
connection_candidate = []
for i in range(nA):
for j in range(nB):
vec = np.subtract(candB[j][:2], candA[i][:2])
norm = math.sqrt(vec[0] * vec[0] + vec[1] * vec[1])
mid_num = min(int(round(norm + 1)), mid_num_)
if norm == 0:
continue
startend = list(zip(np.linspace(candA[i][0], candB[j][0], num=mid_num),
np.linspace(candA[i][1], candB[j][1], num=mid_num)))
limb_response = np.array([score_mid[int(round(startend[I][1])), int(round(startend[I][0]))] for
I in range(len(startend))])
score_midpts = limb_response
score_with_dist_prior = sum(score_midpts) / len(score_midpts) + min(0.5 * image_width / norm - 1, 0)
criterion1 = len(np.nonzero(score_midpts > thre2)[0]) >= connect_ration * len(score_midpts)
criterion2 = score_with_dist_prior > 0
if criterion1 and criterion2:
connection_candidate.append([
i,
j,
score_with_dist_prior,
norm,
0.5 * score_with_dist_prior + 0.25 * candA[i][2] + 0.25 * candB[j][2]])
connection_candidate = sorted(connection_candidate, key=lambda x: x[4], reverse=True)
connection = np.zeros((0, 6))
for c in range(len(connection_candidate)):
i, j, s, limb_len = connection_candidate[c][0:4]
if i not in connection[:, 3] and j not in connection[:, 4]:
connection = np.vstack([connection, [candA[i][3], candB[j][3], s, i, j, limb_len]])
if len(connection) >= min(nA, nB):
break
connection_all.append(connection)
else:
special_k.append(k)
connection_all.append([])
return connection_all, special_k
def find_people(connection_all, special_k, all_peaks, limb_seq):
len_rate = 16.0
connection_tole = 0.7
remove_recon = 0
subset = -1 * np.ones((0, 20, 2))
candidate = np.array([item for sublist in all_peaks for item in sublist])
for k in range(len(limb_seq)):
if k not in special_k:
partAs = connection_all[k][:, 0]
partBs = connection_all[k][:, 1]
indexA, indexB = np.array(limb_seq[k])
for i in range(len(connection_all[k])):
found = 0
subset_idx = [-1, -1]
for j in range(len(subset)):
if subset[j][indexA][0].astype(int) == (partAs[i]).astype(int) or subset[j][indexB][0].astype(
int) == partBs[i].astype(int):
if found >= 2:
continue
subset_idx[found] = j
found += 1
if found == 1:
j = subset_idx[0]
if subset[j][indexB][0].astype(int) == -1 and\
len_rate * subset[j][-1][1] > connection_all[k][i][-1]:
subset[j][indexB][0] = partBs[i]
subset[j][indexB][1] = connection_all[k][i][2]
subset[j][-1][0] += 1
subset[j][-2][0] += candidate[partBs[i].astype(int), 2] + connection_all[k][i][2]
subset[j][-1][1] = max(connection_all[k][i][-1], subset[j][-1][1])
elif subset[j][indexB][0].astype(int) != partBs[i].astype(int):
if subset[j][indexB][1] >= connection_all[k][i][2]:
pass
else:
if len_rate * subset[j][-1][1] <= connection_all[k][i][-1]:
continue
subset[j][-2][0] -= candidate[subset[j][indexB][0].astype(int), 2] + subset[j][indexB][1]
subset[j][indexB][0] = partBs[i]
subset[j][indexB][1] = connection_all[k][i][2]
subset[j][-2][0] += candidate[partBs[i].astype(int), 2] + connection_all[k][i][2]
subset[j][-1][1] = max(connection_all[k][i][-1], subset[j][-1][1])
elif subset[j][indexB][0].astype(int) == partBs[i].astype(int) and\
subset[j][indexB][1] <= connection_all[k][i][2]:
subset[j][-2][0] -= candidate[subset[j][indexB][0].astype(int), 2] + subset[j][indexB][1]
subset[j][indexB][0] = partBs[i]
subset[j][indexB][1] = connection_all[k][i][2]
subset[j][-2][0] += candidate[partBs[i].astype(int), 2] + connection_all[k][i][2]
subset[j][-1][1] = max(connection_all[k][i][-1], subset[j][-1][1])
else:
pass
elif found == 2:
j1, j2 = subset_idx
membership1 = ((subset[j1][..., 0] >= 0).astype(int))[:-2]
membership2 = ((subset[j2][..., 0] >= 0).astype(int))[:-2]
membership = membership1 + membership2
if len(np.nonzero(membership == 2)[0]) == 0:
min_limb1 = np.min(subset[j1, :-2, 1][membership1 == 1])
min_limb2 = np.min(subset[j2, :-2, 1][membership2 == 1])
min_tolerance = min(min_limb1, min_limb2)
if connection_all[k][i][2] < connection_tole * min_tolerance or\
len_rate * subset[j1][-1][1] <= connection_all[k][i][-1]:
continue
subset[j1][:-2][...] += (subset[j2][:-2][...] + 1)
subset[j1][-2:][:, 0] += subset[j2][-2:][:, 0]
subset[j1][-2][0] += connection_all[k][i][2]
subset[j1][-1][1] = max(connection_all[k][i][-1], subset[j1][-1][1])
subset = np.delete(subset, j2, 0)
else:
if connection_all[k][i][0] in subset[j1, :-2, 0]:
c1 = np.where(subset[j1, :-2, 0] == connection_all[k][i][0])
c2 = np.where(subset[j2, :-2, 0] == connection_all[k][i][1])
else:
c1 = np.where(subset[j1, :-2, 0] == connection_all[k][i][1])
c2 = np.where(subset[j2, :-2, 0] == connection_all[k][i][0])
c1 = int(c1[0])
c2 = int(c2[0])
assert c1 != c2, "an candidate keypoint is used twice, shared by two people"
if connection_all[k][i][2] < subset[j1][c1][1] and connection_all[k][i][2] < subset[j2][c2][1]:
continue
small_j = j1
remove_c = c1
if subset[j1][c1][1] > subset[j2][c2][1]:
small_j = j2
remove_c = c2
if remove_recon > 0:
subset[small_j][-2][0] -= candidate[subset[small_j][remove_c][0].astype(int), 2] + \
subset[small_j][remove_c][1]
subset[small_j][remove_c][0] = -1
subset[small_j][remove_c][1] = -1
subset[small_j][-1][0] -= 1
elif not found and k < len(limb_seq):
row = -1 * np.ones((20, 2))
row[indexA][0] = partAs[i]
row[indexA][1] = connection_all[k][i][2]
row[indexB][0] = partBs[i]
row[indexB][1] = connection_all[k][i][2]
row[-1][0] = 2
row[-1][1] = connection_all[k][i][-1]
row[-2][0] = sum(candidate[connection_all[k][i, :2].astype(int), 2]) + connection_all[k][i][2]
row = row[np.newaxis, :, :]
subset = np.concatenate((subset, row), axis=0)
deleteIdx = []
for i in range(len(subset)):
if subset[i][-1][0] < 2 or subset[i][-2][0] / subset[i][-1][0] < 0.45:
deleteIdx.append(i)
subset = np.delete(subset, deleteIdx, axis=0)
return subset, candidate
# ---------------------------------------------------------------------------------------------------------------------
class CocoHpe3MetaInfo(DatasetMetaInfo):
def __init__(self):
super(CocoHpe3MetaInfo, self).__init__()
self.label = "COCO"
self.short_label = "coco"
self.root_dir_name = "coco"
self.dataset_class = CocoHpe3Dataset
self.num_training_samples = None
self.in_channels = 3
self.num_classes = 17
self.input_image_size = (256, 256)
self.train_metric_capts = None
self.train_metric_names = None
self.train_metric_extra_kwargs = None
self.val_metric_capts = None
self.val_metric_names = None
self.test_metric_capts = ["Val.CocoOksAp"]
self.test_metric_names = ["CocoHpeOksApMetric"]
self.test_metric_extra_kwargs = [
{"name": "OksAp",
"coco_annotations_file_path": None,
"validation_ids": None,
"use_file": False,
"pose_postprocessing_fn": lambda x, y: recalc_pose(x, y)}]
self.saver_acc_ind = 0
self.do_transform = True
self.val_transform = CocoHpe2ValTransform
self.test_transform = CocoHpe2ValTransform
self.ml_type = "hpe"
self.test_net_extra_kwargs = None
self.mean_rgb = (0.485, 0.456, 0.406)
self.std_rgb = (0.229, 0.224, 0.225)
self.load_ignore_extra = False
def add_dataset_parser_arguments(self,
parser,
work_dir_path):
"""
Create python script parameters (for ImageNet-1K dataset metainfo).
Parameters:
----------
parser : ArgumentParser
ArgumentParser instance.
work_dir_path : str
Path to working directory.
"""
super(CocoHpe3MetaInfo, self).add_dataset_parser_arguments(parser, work_dir_path)
parser.add_argument(
"--input-size",
type=int,
nargs=2,
default=self.input_image_size,
help="size of the input for model")
parser.add_argument(
"--load-ignore-extra",
action="store_true",
help="ignore extra layers in the source PyTroch model")
def update(self,
args):
"""
Update ImageNet-1K dataset metainfo after user customizing.
Parameters:
----------
args : ArgumentParser
Main script arguments.
"""
super(CocoHpe3MetaInfo, self).update(args)
self.input_image_size = args.input_size
self.load_ignore_extra = args.load_ignore_extra
def update_from_dataset(self,
dataset):
"""
Update dataset metainfo after a dataset class instance creation.
Parameters:
----------
args : obj
A dataset class instance.
"""
self.test_metric_extra_kwargs[0]["coco_annotations_file_path"] = dataset.annotations_file_path
# self.test_metric_extra_kwargs[0]["validation_ids"] = dataset.validation_ids
| 23,125 | 40.003546 | 120 | py |
imgclsmob | imgclsmob-master/gluon/datasets/imagenet1k_rec_cls_dataset.py | """
ImageNet-1K classification dataset (via MXNet image record iterators).
"""
import os
import mxnet as mx
from .imagenet1k_cls_dataset import ImageNet1KMetaInfo, calc_val_resize_value
class ImageNet1KRecMetaInfo(ImageNet1KMetaInfo):
def __init__(self):
super(ImageNet1KRecMetaInfo, self).__init__()
self.use_imgrec = True
self.label = "ImageNet1K_rec"
self.root_dir_name = "imagenet_rec"
self.dataset_class = None
self.num_training_samples = 1281167
self.train_imgrec_file_path = "train.rec"
self.train_imgidx_file_path = "train.idx"
self.val_imgrec_file_path = "val.rec"
self.val_imgidx_file_path = "val.idx"
self.train_imgrec_iter = imagenet_train_imgrec_iter
self.val_imgrec_iter = imagenet_val_imgrec_iter
def imagenet_train_imgrec_iter(ds_metainfo,
batch_size,
num_workers,
mean_rgb=(123.68, 116.779, 103.939),
std_rgb=(58.393, 57.12, 57.375),
jitter_param=0.4,
lighting_param=0.1):
assert (isinstance(ds_metainfo.input_image_size, tuple) and len(ds_metainfo.input_image_size) == 2)
imgrec_file_path = os.path.join(ds_metainfo.root_dir_path, ds_metainfo.train_imgrec_file_path)
imgidx_file_path = os.path.join(ds_metainfo.root_dir_path, ds_metainfo.train_imgidx_file_path)
data_shape = (ds_metainfo.in_channels,) + ds_metainfo.input_image_size
kwargs = {
"path_imgrec": imgrec_file_path,
"path_imgidx": imgidx_file_path,
"preprocess_threads": num_workers,
"shuffle": True,
"batch_size": batch_size,
"data_shape": data_shape,
"mean_r": mean_rgb[0],
"mean_g": mean_rgb[1],
"mean_b": mean_rgb[2],
"std_r": std_rgb[0],
"std_g": std_rgb[1],
"std_b": std_rgb[2],
"rand_mirror": True,
"random_resized_crop": True,
"max_aspect_ratio": (4.0 / 3.0),
"min_aspect_ratio": (3.0 / 4.0),
"max_random_area": 1,
"min_random_area": 0.08,
"brightness": jitter_param,
"saturation": jitter_param,
"contrast": jitter_param,
"pca_noise": lighting_param
}
if ds_metainfo.aug_type == "aug0":
pass
elif ds_metainfo.aug_type == "aug1":
kwargs["inter_method"] = 10
elif ds_metainfo.aug_type == "aug2":
kwargs["inter_method"] = 10
kwargs["max_rotate_angle"] = 30
kwargs["max_shear_ratio"] = 0.05
else:
raise RuntimeError("Unknown augmentation type: {}\n".format(ds_metainfo.aug_type))
return mx.io.ImageRecordIter(**kwargs)
def imagenet_val_imgrec_iter(ds_metainfo,
batch_size,
num_workers,
mean_rgb=(123.68, 116.779, 103.939),
std_rgb=(58.393, 57.12, 57.375)):
assert (isinstance(ds_metainfo.input_image_size, tuple) and len(ds_metainfo.input_image_size) == 2)
imgrec_file_path = os.path.join(ds_metainfo.root_dir_path, ds_metainfo.val_imgrec_file_path)
imgidx_file_path = os.path.join(ds_metainfo.root_dir_path, ds_metainfo.val_imgidx_file_path)
data_shape = (ds_metainfo.in_channels,) + ds_metainfo.input_image_size
resize_value = calc_val_resize_value(
input_image_size=ds_metainfo.input_image_size,
resize_inv_factor=ds_metainfo.resize_inv_factor)
return mx.io.ImageRecordIter(
path_imgrec=imgrec_file_path,
path_imgidx=imgidx_file_path,
preprocess_threads=num_workers,
shuffle=False,
batch_size=batch_size,
resize=resize_value,
data_shape=data_shape,
mean_r=mean_rgb[0],
mean_g=mean_rgb[1],
mean_b=mean_rgb[2],
std_r=std_rgb[0],
std_g=std_rgb[1],
std_b=std_rgb[2])
| 3,974 | 38.75 | 103 | py |
imgclsmob | imgclsmob-master/gluon/datasets/asr_dataset.py | """
Automatic Speech Recognition (ASR) abstract dataset.
"""
__all__ = ['AsrDataset', 'asr_test_transform']
from mxnet.gluon.data import dataset
from mxnet.gluon.data.vision import transforms
from gluon.gluoncv2.models.jasper import NemoAudioReader
class AsrDataset(dataset.Dataset):
"""
Automatic Speech Recognition (ASR) abstract dataset.
Parameters:
----------
root : str
Path to the folder stored the dataset.
mode : str
'train', 'val', 'test', or 'demo'.
transform : func
A function that takes data and transforms it.
"""
def __init__(self,
root,
mode,
transform):
super(AsrDataset, self).__init__()
assert (mode in ("train", "val", "test", "demo"))
self.root = root
self.mode = mode
self._transform = transform
self.data = []
self.audio_reader = NemoAudioReader()
def __getitem__(self, index):
wav_file_path, label_text = self.data[index]
audio_data = self.audio_reader.read_from_file(wav_file_path)
audio_len = audio_data.shape[0]
return (audio_data, audio_len), label_text
def __len__(self):
return len(self.data)
def asr_test_transform(ds_metainfo):
assert (ds_metainfo is not None)
return transforms.Compose([])
| 1,358 | 26.18 | 68 | py |
imgclsmob | imgclsmob-master/gluon/datasets/cifar10_cls_dataset.py | """
CIFAR-10 classification dataset.
"""
import os
import numpy as np
import mxnet as mx
from mxnet.gluon import Block
from mxnet.gluon.data.vision import CIFAR10
from mxnet.gluon.data.vision import transforms
from .dataset_metainfo import DatasetMetaInfo
class CIFAR10Fine(CIFAR10):
"""
CIFAR-10 image classification dataset.
Parameters:
----------
root : str, default $MXNET_HOME/datasets/cifar10
Path to temp folder for storing data.
mode : str, default 'train'
'train', 'val', or 'test'.
transform : function, default None
A user defined callback that transforms each sample.
"""
def __init__(self,
root=os.path.join("~", ".mxnet", "datasets", "cifar10"),
mode="train",
transform=None):
super(CIFAR10Fine, self).__init__(
root=root,
train=(mode == "train"),
transform=transform)
class CIFAR10MetaInfo(DatasetMetaInfo):
def __init__(self):
super(CIFAR10MetaInfo, self).__init__()
self.label = "CIFAR10"
self.short_label = "cifar"
self.root_dir_name = "cifar10"
self.dataset_class = CIFAR10Fine
self.num_training_samples = 50000
self.in_channels = 3
self.num_classes = 10
self.input_image_size = (32, 32)
self.train_metric_capts = ["Train.Err"]
self.train_metric_names = ["Top1Error"]
self.train_metric_extra_kwargs = [{"name": "err"}]
self.val_metric_capts = ["Val.Err"]
self.val_metric_names = ["Top1Error"]
self.val_metric_extra_kwargs = [{"name": "err"}]
self.saver_acc_ind = 0
self.train_transform = cifar10_train_transform
self.val_transform = cifar10_val_transform
self.test_transform = cifar10_val_transform
self.ml_type = "imgcls"
self.loss_name = "SoftmaxCrossEntropy"
class RandomCrop(Block):
"""
Randomly crop `src` with `size` (width, height).
Padding is optional.
Upsample result if `src` is smaller than `size`.
Parameters:
----------
size : int or tuple of (W, H)
Size of the final output.
pad: int or tuple, default None
if int, size of the zero-padding
if tuple, number of values padded to the edges of each axis.
((before_1, after_1), ... (before_N, after_N)) unique pad widths for each axis.
((before, after),) yields same before and after pad for each axis.
(pad,) or int is a shortcut for before = after = pad width for all axes.
interpolation : int, default 2
Interpolation method for resizing. By default uses bilinear
interpolation. See OpenCV's resize function for available choices.
"""
def __init__(self,
size,
pad=None,
interpolation=2):
super(RandomCrop, self).__init__()
numeric_types = (float, int, np.generic)
if isinstance(size, numeric_types):
size = (size, size)
self._args = (size, interpolation)
if isinstance(pad, int):
self.pad = ((pad, pad), (pad, pad), (0, 0))
else:
self.pad = pad
def forward(self, x):
if self.pad:
x_pad = np.pad(x.asnumpy(), self.pad, mode="constant", constant_values=0)
return mx.image.random_crop(mx.nd.array(x_pad), *self._args)[0]
def cifar10_train_transform(ds_metainfo,
mean_rgb=(0.4914, 0.4822, 0.4465),
std_rgb=(0.2023, 0.1994, 0.2010),
jitter_param=0.4,
lighting_param=0.1):
assert (ds_metainfo is not None)
assert (ds_metainfo.input_image_size[0] == 32)
return transforms.Compose([
RandomCrop(
size=32,
pad=4),
transforms.RandomFlipLeftRight(),
transforms.RandomColorJitter(
brightness=jitter_param,
contrast=jitter_param,
saturation=jitter_param),
transforms.RandomLighting(lighting_param),
transforms.ToTensor(),
transforms.Normalize(
mean=mean_rgb,
std=std_rgb)
])
def cifar10_val_transform(ds_metainfo,
mean_rgb=(0.4914, 0.4822, 0.4465),
std_rgb=(0.2023, 0.1994, 0.2010)):
assert (ds_metainfo is not None)
return transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(
mean=mean_rgb,
std=std_rgb)
])
| 4,585 | 32.474453 | 91 | py |
imgclsmob | imgclsmob-master/gluon/datasets/cub200_2011_cls_dataset.py | """
CUB-200-2011 classification dataset.
"""
import os
import numpy as np
import pandas as pd
import mxnet as mx
from mxnet.gluon.data import dataset
from .imagenet1k_cls_dataset import ImageNet1KMetaInfo
class CUB200_2011(dataset.Dataset):
"""
CUB-200-2011 fine-grained classification dataset.
Parameters:
----------
root : str, default '~/.mxnet/datasets/CUB_200_2011'
Path to the folder stored the dataset.
mode : str, default 'train'
'train', 'val', or 'test'.
transform : function, default None
A function that takes data and label and transforms them.
"""
def __init__(self,
root=os.path.join("~", ".mxnet", "datasets", "CUB_200_2011"),
mode="train",
transform=None):
super(CUB200_2011, self).__init__()
root_dir_path = os.path.expanduser(root)
assert os.path.exists(root_dir_path)
images_file_name = "images.txt"
images_file_path = os.path.join(root_dir_path, images_file_name)
if not os.path.exists(images_file_path):
raise Exception("Images file doesn't exist: {}".format(images_file_name))
class_file_name = "image_class_labels.txt"
class_file_path = os.path.join(root_dir_path, class_file_name)
if not os.path.exists(class_file_path):
raise Exception("Image class file doesn't exist: {}".format(class_file_name))
split_file_name = "train_test_split.txt"
split_file_path = os.path.join(root_dir_path, split_file_name)
if not os.path.exists(split_file_path):
raise Exception("Split file doesn't exist: {}".format(split_file_name))
images_df = pd.read_csv(
images_file_path,
sep="\s+",
header=None,
index_col=False,
names=["image_id", "image_path"],
dtype={"image_id": np.int32, "image_path": np.unicode})
class_df = pd.read_csv(
class_file_path,
sep="\s+",
header=None,
index_col=False,
names=["image_id", "class_id"],
dtype={"image_id": np.int32, "class_id": np.uint8})
split_df = pd.read_csv(
split_file_path,
sep="\s+",
header=None,
index_col=False,
names=["image_id", "split_flag"],
dtype={"image_id": np.int32, "split_flag": np.uint8})
df = images_df.join(class_df, rsuffix="_class_df").join(split_df, rsuffix="_split_df")
split_flag = 1 if mode == "train" else 0
subset_df = df[df.split_flag == split_flag]
self.image_ids = subset_df["image_id"].values.astype(np.int32)
self.class_ids = subset_df["class_id"].values.astype(np.int32) - 1
self.image_file_names = subset_df["image_path"].values.astype(np.unicode)
images_dir_name = "images"
self.images_dir_path = os.path.join(root_dir_path, images_dir_name)
assert os.path.exists(self.images_dir_path)
self._transform = transform
def __getitem__(self, index):
image_file_name = self.image_file_names[index]
image_file_path = os.path.join(self.images_dir_path, image_file_name)
img = mx.image.imread(image_file_path, flag=1)
label = int(self.class_ids[index])
if self._transform is not None:
return self._transform(img, label)
return img, label
def __len__(self):
return len(self.image_ids)
class CUB200MetaInfo(ImageNet1KMetaInfo):
def __init__(self):
super(CUB200MetaInfo, self).__init__()
self.label = "CUB200_2011"
self.short_label = "cub"
self.root_dir_name = "CUB_200_2011"
self.dataset_class = CUB200_2011
self.num_training_samples = None
self.num_classes = 200
self.train_metric_capts = ["Train.Err"]
self.train_metric_names = ["Top1Error"]
self.train_metric_extra_kwargs = [{"name": "err"}]
self.val_metric_capts = ["Val.Err"]
self.val_metric_names = ["Top1Error"]
self.val_metric_extra_kwargs = [{"name": "err"}]
self.saver_acc_ind = 0
self.test_net_extra_kwargs = {"aux": False}
self.load_ignore_extra = True
def add_dataset_parser_arguments(self,
parser,
work_dir_path):
super(CUB200MetaInfo, self).add_dataset_parser_arguments(parser, work_dir_path)
parser.add_argument(
"--no-aux",
dest="no_aux",
action="store_true",
help="no `aux` mode in model")
def update(self,
args):
super(CUB200MetaInfo, self).update(args)
if args.no_aux:
self.test_net_extra_kwargs = None
self.load_ignore_extra = False
| 4,865 | 35.586466 | 94 | py |
imgclsmob | imgclsmob-master/gluon/datasets/mcv_asr_dataset.py | """
Mozilla Common Voice ASR dataset.
"""
__all__ = ['McvDataset', 'McvMetaInfo']
import os
import re
import numpy as np
import pandas as pd
from .dataset_metainfo import DatasetMetaInfo
from .asr_dataset import AsrDataset, asr_test_transform
class McvDataset(AsrDataset):
"""
Mozilla Common Voice dataset for Automatic Speech Recognition (ASR).
Parameters:
----------
root : str, default '~/.torch/datasets/mcv'
Path to the folder stored the dataset.
mode : str, default 'test'
'train', 'val', 'test', or 'demo'.
lang : str, default 'en'
Language.
subset : str, default 'dev'
Data subset.
transform : function, default None
A function that takes data and transforms it.
"""
def __init__(self,
root=os.path.join("~", ".torch", "datasets", "mcv"),
mode="test",
lang="en",
subset="dev",
transform=None):
super(McvDataset, self).__init__(
root=root,
mode=mode,
transform=transform)
assert (lang in ("en", "fr", "de", "it", "es", "ca", "pl", "ru", "ru34"))
self.vocabulary = self.get_vocabulary_for_lang(lang=lang)
desired_audio_sample_rate = 16000
vocabulary_dict = {c: i for i, c in enumerate(self.vocabulary)}
import soundfile
import librosa
from librosa.core import resample as lr_resample
import unicodedata
import unidecode
root_dir_path = os.path.expanduser(root)
assert os.path.exists(root_dir_path)
lang_ = lang if lang != "ru34" else "ru"
data_dir_path = os.path.join(root_dir_path, lang_)
assert os.path.exists(data_dir_path)
metainfo_file_path = os.path.join(data_dir_path, subset + ".tsv")
assert os.path.exists(metainfo_file_path)
metainfo_df = pd.read_csv(
metainfo_file_path,
sep="\t",
header=0,
index_col=False)
metainfo_df = metainfo_df[["path", "sentence"]]
self.data_paths = metainfo_df["path"].values
self.data_sentences = metainfo_df["sentence"].values
clips_dir_path = os.path.join(data_dir_path, "clips")
assert os.path.exists(clips_dir_path)
for clip_file_name, sentence in zip(self.data_paths, self.data_sentences):
mp3_file_path = os.path.join(clips_dir_path, clip_file_name)
assert os.path.exists(mp3_file_path)
wav_file_name = clip_file_name.replace(".mp3", ".wav")
wav_file_path = os.path.join(clips_dir_path, wav_file_name)
# print("==> {}".format(sentence))
text = sentence.lower()
if lang == "en":
text = re.sub("\.|-|–|—", " ", text)
text = re.sub("&", " and ", text)
text = re.sub("ō", "o", text)
text = re.sub("â|á", "a", text)
text = re.sub("é", "e", text)
text = re.sub(",|;|:|!|\?|\"|“|”|‘|’|\(|\)", "", text)
text = re.sub("\s+", " ", text)
text = re.sub(" '", " ", text)
text = re.sub("' ", " ", text)
elif lang == "fr":
text = "".join(c for c in text if unicodedata.combining(c) == 0)
text = re.sub("\.|-|–|—|=|×|\*|†|/|ቀ|_|…", " ", text)
text = re.sub(",|;|:|!|\?|ʻ|“|”|\"|„|«|»|\(|\)", "", text)
text = re.sub("먹|삼|생|고|기|집|\$|ʔ|の|ひ", "", text)
text = re.sub("’|´", "'", text)
text = re.sub("&", " and ", text)
text = re.sub("œ", "oe", text)
text = re.sub("æ", "ae", text)
text = re.sub("á|ā|ã|ä|ą|ă|å", "a", text)
text = re.sub("ö|ō|ó|ð|ổ|ø", "o", text)
text = re.sub("ē|ė|ę", "e", text)
text = re.sub("í|ī", "i", text)
text = re.sub("ú|ū", "u", text)
text = re.sub("ý", "y", text)
text = re.sub("š|ś|ș|ş", "s", text)
text = re.sub("ž|ź|ż", "z", text)
text = re.sub("ñ|ń|ṇ", "n", text)
text = re.sub("ł|ľ", "l", text)
text = re.sub("ć|č", "c", text)
text = re.sub("я", "ya", text)
text = re.sub("ř", "r", text)
text = re.sub("đ", "d", text)
text = re.sub("ț", "t", text)
text = re.sub("þ", "th", text)
text = re.sub("ğ", "g", text)
text = re.sub("ß", "ss", text)
text = re.sub("µ", "mu", text)
text = re.sub("\s+", " ", text)
elif lang == "de":
text = re.sub("\.|-|–|—|/|_|…", " ", text)
text = re.sub(",|;|:|!|\?|\"|'|‘|’|ʻ|ʿ|‚|“|”|\"|„|«|»|›|‹|\(|\)", "", text)
text = re.sub("°|幺|乡|辶", "", text)
text = re.sub("&", " and ", text)
text = re.sub("ə", "a", text)
text = re.sub("æ", "ae", text)
text = re.sub("å|ā|á|ã|ă|â|ą", "a", text)
text = re.sub("ó|ð|ø|ọ|ő|ō|ô", "o", text)
text = re.sub("é|ë|ê|ě|ę", "e", text)
text = re.sub("ū|ứ", "u", text)
text = re.sub("í|ï|ı", "i", text)
text = re.sub("š|ș|ś|ş", "s", text)
text = re.sub("č|ć", "c", text)
text = re.sub("đ", "d", text)
text = re.sub("ğ", "g", text)
text = re.sub("ł", "l", text)
text = re.sub("ř", "r", text)
text = re.sub("ñ", "n", text)
text = re.sub("ț", "t", text)
text = re.sub("ž|ź", "z", text)
text = re.sub("\s+", " ", text)
elif lang == "it":
text = re.sub("\.|-|–|—|/|_|…", " ", text)
text = re.sub(",|;|:|!|\?|\"|“|”|\"|„|«|»|›|‹|<|>|\(|\)", "", text)
text = re.sub("\$|#|禅", "", text)
text = re.sub("’|`", "'", text)
text = re.sub("ə", "a", text)
text = "".join((c if c in self.vocabulary else unidecode.unidecode(c)) for c in text)
text = re.sub("\s+", " ", text)
elif lang == "es":
text = re.sub("\.|-|–|—|/|=|_|{|…", " ", text)
text = re.sub(",|;|:|!|\?|\"|“|”|\"|„|«|»|›|‹|<|>|\(|\)|¿|¡", "", text)
text = re.sub("蝦|夷", "", text)
text = "".join((c if c in self.vocabulary else unidecode.unidecode(c)) for c in text)
text = re.sub("\s+", " ", text)
elif lang == "ca":
text = re.sub("\.|-|–|—|/|=|_|·|@|\+|…", " ", text)
text = re.sub(",|;|:|!|\?|\"|“|”|\"|„|«|»|›|‹|<|>|\(|\)|¿|¡", "", text)
text = re.sub("ঃ|ং", "", text)
text = "".join((c if c in self.vocabulary else unidecode.unidecode(c)) for c in text)
text = re.sub("\s+", " ", text)
elif lang == "pl":
text = re.sub("\.|-|–|—|/|=|_|·|@|\+|…", " ", text)
text = re.sub(",|;|:|!|\?|\"|“|”|\"|„|«|»|›|‹|<|>|\(|\)", "", text)
text = re.sub("q", "k", text)
text = re.sub("x", "ks", text)
text = re.sub("v", "w", text)
text = "".join((c if c in self.vocabulary else unidecode.unidecode(c)) for c in text)
text = re.sub("\s+", " ", text)
elif lang in ("ru", "ru34"):
text = re.sub("по-", "по", text)
text = re.sub("во-", "во", text)
text = re.sub("-то", "то", text)
text = re.sub("\.|−|-|–|—|…", " ", text)
text = re.sub(",|;|:|!|\?|‘|’|\"|“|”|«|»|'", "", text)
text = re.sub("m", "м", text)
text = re.sub("o", "о", text)
text = re.sub("z", "з", text)
text = re.sub("i", "и", text)
text = re.sub("l", "л", text)
text = re.sub("a", "а", text)
text = re.sub("f", "ф", text)
text = re.sub("r", "р", text)
text = re.sub("e", "е", text)
text = re.sub("x", "кс", text)
text = re.sub("h", "х", text)
text = re.sub("\s+", " ", text)
if lang == "ru34":
text = re.sub("ё", "е", text)
text = re.sub(" $", "", text)
# print("<== {}".format(text))
text = np.array([vocabulary_dict[c] for c in text], dtype=np.long)
self.data.append((wav_file_path, text))
# continue
if os.path.exists(wav_file_path):
continue
# pass
x, sr = librosa.load(path=mp3_file_path, sr=None)
if desired_audio_sample_rate != sr:
y = lr_resample(y=x, orig_sr=sr, target_sr=desired_audio_sample_rate)
soundfile.write(file=wav_file_path, data=y, samplerate=desired_audio_sample_rate)
@staticmethod
def get_vocabulary_for_lang(lang="en"):
"""
Get the vocabulary for a language.
Parameters:
----------
lang : str, default 'en'
Language.
Returns:
-------
list of str
Vocabulary set.
"""
assert (lang in ("en", "fr", "de", "it", "es", "ca", "pl", "ru", "ru34"))
if lang == "en":
return [' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z', "'"]
elif lang == "fr":
return [' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z', "'", 'ç', 'é', 'â', 'ê', 'î', 'ô', 'û', 'à', 'è', 'ù', 'ë', 'ï',
'ü', 'ÿ']
elif lang == "de":
return [' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z', 'ä', 'ö', 'ü', 'ß']
elif lang == "it":
return [' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z', "'", 'à', 'é', 'è', 'í', 'ì', 'î', 'ó', 'ò', 'ú', 'ù']
elif lang == "es":
return [' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z', "'", 'á', 'é', 'í', 'ó', 'ú', 'ñ', 'ü']
elif lang == "ca":
return [' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z', "'", 'à', 'é', 'è', 'í', 'ï', 'ó', 'ò', 'ú', 'ü', 'ŀ']
elif lang == "pl":
return [' ', 'a', 'ą', 'b', 'c', 'ć', 'd', 'e', 'ę', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'ł', 'm', 'n', 'ń',
'o', 'ó', 'p', 'r', 's', 'ś', 't', 'u', 'w', 'y', 'z', 'ź', 'ż']
elif lang == "ru":
return [' ', 'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с',
'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я']
elif lang == "ru34":
return [' ', 'а', 'б', 'в', 'г', 'д', 'е', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т',
'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я']
else:
return None
class McvMetaInfo(DatasetMetaInfo):
def __init__(self):
super(McvMetaInfo, self).__init__()
self.label = "MCV"
self.short_label = "mcv"
self.root_dir_name = "cv-corpus-6.1-2020-12-11"
self.dataset_class = McvDataset
self.lang = "en"
self.dataset_class_extra_kwargs = {
"lang": self.lang,
"subset": "dev"}
self.ml_type = "asr"
self.num_classes = None
self.val_metric_extra_kwargs = [{"vocabulary": None}]
self.val_metric_capts = ["Val.WER"]
self.val_metric_names = ["WER"]
self.test_metric_extra_kwargs = [{"vocabulary": None}]
self.test_metric_capts = ["Test.WER"]
self.test_metric_names = ["WER"]
self.val_transform = asr_test_transform
self.test_transform = asr_test_transform
self.saver_acc_ind = 0
def add_dataset_parser_arguments(self,
parser,
work_dir_path):
"""
Create python script parameters (for dataset specific metainfo).
Parameters:
----------
parser : ArgumentParser
ArgumentParser instance.
work_dir_path : str
Path to working directory.
"""
super(McvMetaInfo, self).add_dataset_parser_arguments(parser, work_dir_path)
parser.add_argument(
"--lang",
type=str,
default="en",
help="language")
parser.add_argument(
"--subset",
type=str,
default="dev",
help="data subset")
def update(self,
args):
"""
Update dataset metainfo after user customizing.
Parameters:
----------
args : ArgumentParser
Main script arguments.
"""
super(McvMetaInfo, self).update(args)
self.lang = args.lang
self.dataset_class_extra_kwargs["lang"] = args.lang
self.dataset_class_extra_kwargs["subset"] = args.subset
def update_from_dataset(self,
dataset):
"""
Update dataset metainfo after a dataset class instance creation.
Parameters:
----------
args : obj
A dataset class instance.
"""
vocabulary = dataset._data.vocabulary
self.num_classes = len(vocabulary) + 1
self.val_metric_extra_kwargs[0]["vocabulary"] = vocabulary
self.test_metric_extra_kwargs[0]["vocabulary"] = vocabulary
| 14,293 | 41.924925 | 119 | py |
imgclsmob | imgclsmob-master/gluon/datasets/cityscapes_seg_dataset.py | """
Cityscapes semantic segmentation dataset.
"""
import os
import numpy as np
import mxnet as mx
from PIL import Image
from .seg_dataset import SegDataset
from .voc_seg_dataset import VOCMetaInfo
class CityscapesSegDataset(SegDataset):
"""
Cityscapes semantic segmentation dataset.
Parameters:
----------
root : str
Path to a folder with `leftImg8bit` and `gtFine` subfolders.
mode : str, default 'train'
'train', 'val', 'test', or 'demo'.
transform : callable, optional
A function that transforms the image.
"""
def __init__(self,
root,
mode="train",
transform=None,
**kwargs):
super(CityscapesSegDataset, self).__init__(
root=root,
mode=mode,
transform=transform,
**kwargs)
image_dir_path = os.path.join(root, "leftImg8bit")
mask_dir_path = os.path.join(root, "gtFine")
assert os.path.exists(image_dir_path) and os.path.exists(mask_dir_path), "Please prepare dataset"
mode_dir_name = "train" if mode == "train" else "val"
image_dir_path = os.path.join(image_dir_path, mode_dir_name)
# mask_dir_path = os.path.join(mask_dir_path, mode_dir_name)
self.images = []
self.masks = []
for image_subdir_path, _, image_file_names in os.walk(image_dir_path):
for image_file_name in image_file_names:
if image_file_name.endswith(".png"):
image_file_path = os.path.join(image_subdir_path, image_file_name)
mask_file_name = image_file_name.replace("leftImg8bit", "gtFine_labelIds")
mask_subdir_path = image_subdir_path.replace("leftImg8bit", "gtFine")
mask_file_path = os.path.join(mask_subdir_path, mask_file_name)
if os.path.isfile(mask_file_path):
self.images.append(image_file_path)
self.masks.append(mask_file_path)
else:
print("Cannot find the mask: {}".format(mask_file_path))
assert (len(self.images) == len(self.masks))
if len(self.images) == 0:
raise RuntimeError("Found 0 images in subfolders of: {}\n".format(image_dir_path))
def __getitem__(self, index):
image = Image.open(self.images[index]).convert("RGB")
if self.mode == "demo":
image = self._img_transform(image)
if self.transform is not None:
image = self.transform(image)
return image, os.path.basename(self.images[index])
mask = Image.open(self.masks[index])
if self.mode == "train":
image, mask = self._train_sync_transform(image, mask)
elif self.mode == "val":
image, mask = self._val_sync_transform(image, mask)
else:
assert (self.mode == "test")
image = self._img_transform(image)
mask = self._mask_transform(mask)
if self.transform is not None:
image = self.transform(image)
return image, mask
classes = 19
vague_idx = 19
use_vague = True
background_idx = -1
ignore_bg = False
_key = np.array([-1, -1, -1, -1, -1, -1,
-1, -1, 0, 1, -1, -1,
2, 3, 4, -1, -1, -1,
5, -1, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15,
-1, -1, 16, 17, 18])
_mapping = np.array(range(-1, len(_key) - 1)).astype(np.int32)
@staticmethod
def _class_to_index(mask):
values = np.unique(mask)
for value in values:
assert(value in CityscapesSegDataset._mapping)
index = np.digitize(mask.ravel(), CityscapesSegDataset._mapping, right=True)
return CityscapesSegDataset._key[index].reshape(mask.shape)
@staticmethod
def _mask_transform(mask):
np_mask = np.array(mask).astype(np.int32)
np_mask = CityscapesSegDataset._class_to_index(np_mask)
np_mask[np_mask == -1] = CityscapesSegDataset.vague_idx
return mx.nd.array(np_mask, mx.cpu())
def __len__(self):
return len(self.images)
class CityscapesMetaInfo(VOCMetaInfo):
def __init__(self):
super(CityscapesMetaInfo, self).__init__()
self.label = "Cityscapes"
self.short_label = "voc"
self.root_dir_name = "cityscapes"
self.dataset_class = CityscapesSegDataset
self.num_classes = CityscapesSegDataset.classes
self.test_metric_extra_kwargs = [
{"vague_idx": CityscapesSegDataset.vague_idx,
"use_vague": CityscapesSegDataset.use_vague,
"macro_average": False},
{"num_classes": CityscapesSegDataset.classes,
"vague_idx": CityscapesSegDataset.vague_idx,
"use_vague": CityscapesSegDataset.use_vague,
"bg_idx": CityscapesSegDataset.background_idx,
"ignore_bg": CityscapesSegDataset.ignore_bg,
"macro_average": False}]
| 5,110 | 36.306569 | 105 | py |
imgclsmob | imgclsmob-master/gluon/datasets/coco_seg_dataset.py | """
COCO semantic segmentation dataset.
"""
import os
import logging
import numpy as np
import mxnet as mx
from PIL import Image
from tqdm import trange
from .seg_dataset import SegDataset
from .voc_seg_dataset import VOCMetaInfo
class CocoSegDataset(SegDataset):
"""
COCO semantic segmentation dataset.
Parameters:
----------
root : string
Path to `annotations`, `train2017`, and `val2017` folders.
mode : string, default 'train'
'train', 'val', 'test', or 'demo'.
transform : callable, optional
A function that transforms the image.
"""
def __init__(self,
root,
mode="train",
transform=None,
**kwargs):
super(CocoSegDataset, self).__init__(
root=root,
mode=mode,
transform=transform,
**kwargs)
year = "2017"
mode_name = "train" if mode == "train" else "val"
annotations_dir_path = os.path.join(root, "annotations")
annotations_file_path = os.path.join(annotations_dir_path, "instances_" + mode_name + year + ".json")
idx_file_path = os.path.join(annotations_dir_path, mode_name + "_idx.npy")
self.image_dir_path = os.path.join(root, mode_name + year)
from pycocotools.coco import COCO
from pycocotools import mask as coco_mask
self.coco = COCO(annotations_file_path)
self.coco_mask = coco_mask
if os.path.exists(idx_file_path):
self.idx = np.load(idx_file_path)
else:
idx_list = list(self.coco.imgs.keys())
self.idx = self._filter_idx(idx_list, idx_file_path)
def __getitem__(self, index):
image_id = int(self.idx[index])
image_metadata = self.coco.loadImgs(image_id)[0]
image_file_name = image_metadata["file_name"]
image_file_path = os.path.join(self.image_dir_path, image_file_name)
image = Image.open(image_file_path).convert("RGB")
if self.mode == "demo":
image = self._img_transform(image)
if self.transform is not None:
image = self.transform(image)
return image, os.path.basename(image_file_path)
coco_target = self.coco.loadAnns(self.coco.getAnnIds(imgIds=image_id))
mask = Image.fromarray(self._gen_seg_mask(
target=coco_target,
height=image_metadata["height"],
width=image_metadata["width"]))
if self.mode == "train":
image, mask = self._train_sync_transform(image, mask)
elif self.mode == "val":
image, mask = self._val_sync_transform(image, mask)
else:
assert (self.mode == "test")
image, mask = self._img_transform(image), self._mask_transform(mask)
if self.transform is not None:
image = self.transform(image)
return image, mask
def _gen_seg_mask(self, target, height, width):
cat_list = [0, 5, 2, 16, 9, 44, 6, 3, 17, 62, 21, 67, 18, 19, 4, 1, 64, 20, 63, 7, 72]
mask = np.zeros((height, width), dtype=np.uint8)
for instance in target:
rle = self.coco_mask.frPyObjects(instance["segmentation"], height, width)
m = self.coco_mask.decode(rle)
cat = instance["category_id"]
if cat in cat_list:
c = cat_list.index(cat)
else:
continue
if len(m.shape) < 3:
mask[:, :] += (mask == 0) * (m * c)
else:
mask[:, :] += (mask == 0) * (((np.sum(m, axis=2)) > 0) * c).astype(np.uint8)
return mask
def _filter_idx(self,
idx_list,
idx_file_path,
pixels_thr=1000):
logging.info("Filtering mask index:")
tbar = trange(len(idx_list))
filtered_idx = []
for i in tbar:
img_id = idx_list[i]
coco_target = self.coco.loadAnns(self.coco.getAnnIds(imgIds=img_id))
img_metadata = self.coco.loadImgs(img_id)[0]
mask = self._gen_seg_mask(
coco_target,
img_metadata["height"],
img_metadata["width"])
if (mask > 0).sum() > pixels_thr:
filtered_idx.append(img_id)
tbar.set_description("Doing: {}/{}, got {} qualified images".format(i, len(idx_list), len(filtered_idx)))
logging.info("Found number of qualified images: {}".format(len(filtered_idx)))
np.save(idx_file_path, np.array(filtered_idx, np.int32))
return filtered_idx
classes = 21
vague_idx = -1
use_vague = False
background_idx = 0
ignore_bg = True
@staticmethod
def _mask_transform(mask, ctx=mx.cpu()):
np_mask = np.array(mask).astype(np.int32)
# print("min={}, max={}".format(np_mask.min(), np_mask.max()))
return mx.nd.array(np_mask, ctx=ctx)
def __len__(self):
return len(self.idx)
class CocoSegMetaInfo(VOCMetaInfo):
def __init__(self):
super(CocoSegMetaInfo, self).__init__()
self.label = "COCO"
self.short_label = "coco"
self.root_dir_name = "coco"
self.dataset_class = CocoSegDataset
self.num_classes = CocoSegDataset.classes
self.train_metric_extra_kwargs = [
{"vague_idx": CocoSegDataset.vague_idx,
"use_vague": CocoSegDataset.use_vague,
"macro_average": False,
"aux": self.train_aux}]
self.val_metric_extra_kwargs = [
{"vague_idx": CocoSegDataset.vague_idx,
"use_vague": CocoSegDataset.use_vague,
"macro_average": False},
{"num_classes": CocoSegDataset.classes,
"vague_idx": CocoSegDataset.vague_idx,
"use_vague": CocoSegDataset.use_vague,
"bg_idx": CocoSegDataset.background_idx,
"ignore_bg": CocoSegDataset.ignore_bg,
"macro_average": False}]
self.test_metric_extra_kwargs = self.val_metric_extra_kwargs
| 6,102 | 35.54491 | 117 | py |
imgclsmob | imgclsmob-master/gluon/datasets/voc_seg_dataset.py | """
Pascal VOC2012 semantic segmentation dataset.
"""
import os
import numpy as np
import mxnet as mx
from PIL import Image
from mxnet.gluon.data.vision import transforms
from .seg_dataset import SegDataset
from .dataset_metainfo import DatasetMetaInfo
class VOCSegDataset(SegDataset):
"""
Pascal VOC2012 semantic segmentation dataset.
Parameters:
----------
root : str
Path to VOCdevkit folder.
mode : str, default 'train'
'train', 'val', 'test', or 'demo'.
transform : callable, optional
A function that transforms the image.
"""
def __init__(self,
root,
mode="train",
transform=None,
**kwargs):
super(VOCSegDataset, self).__init__(
root=root,
mode=mode,
transform=transform,
**kwargs)
base_dir_path = os.path.join(root, "VOC2012")
image_dir_path = os.path.join(base_dir_path, "JPEGImages")
mask_dir_path = os.path.join(base_dir_path, "SegmentationClass")
splits_dir_path = os.path.join(base_dir_path, "ImageSets", "Segmentation")
if mode == "train":
split_file_path = os.path.join(splits_dir_path, "train.txt")
elif mode in ("val", "test", "demo"):
split_file_path = os.path.join(splits_dir_path, "val.txt")
else:
raise RuntimeError("Unknown dataset splitting mode")
self.images = []
self.masks = []
with open(os.path.join(split_file_path), "r") as lines:
for line in lines:
image_file_path = os.path.join(image_dir_path, line.rstrip('\n') + ".jpg")
assert os.path.isfile(image_file_path)
self.images.append(image_file_path)
mask_file_path = os.path.join(mask_dir_path, line.rstrip('\n') + ".png")
assert os.path.isfile(mask_file_path)
self.masks.append(mask_file_path)
assert (len(self.images) == len(self.masks))
def __getitem__(self, index):
image = Image.open(self.images[index]).convert("RGB")
if self.mode == "demo":
image = self._img_transform(image)
if self.transform is not None:
image = self.transform(image)
return image, os.path.basename(self.images[index])
mask = Image.open(self.masks[index])
if self.mode == "train":
image, mask = self._train_sync_transform(image, mask)
elif self.mode == "val":
image, mask = self._val_sync_transform(image, mask)
else:
assert self.mode == "test"
image, mask = self._img_transform(image), self._mask_transform(mask)
if self.transform is not None:
image = self.transform(image)
return image, mask
classes = 21
vague_idx = 255
use_vague = True
background_idx = 0
ignore_bg = True
@staticmethod
def _mask_transform(mask, ctx=mx.cpu()):
np_mask = np.array(mask).astype(np.int32)
# np_mask[np_mask == 255] = VOCSegDataset.vague_idx
return mx.nd.array(np_mask, ctx=ctx)
def __len__(self):
return len(self.images)
def voc_transform(ds_metainfo,
mean_rgb=(0.485, 0.456, 0.406),
std_rgb=(0.229, 0.224, 0.225)):
assert (ds_metainfo is not None)
return transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(
mean=mean_rgb,
std=std_rgb)
])
class VOCMetaInfo(DatasetMetaInfo):
def __init__(self):
super(VOCMetaInfo, self).__init__()
self.label = "VOC"
self.short_label = "voc"
self.root_dir_name = "voc"
self.dataset_class = VOCSegDataset
self.num_training_samples = None
self.in_channels = 3
self.num_classes = VOCSegDataset.classes
self.train_aux = False
self.input_image_size = (480, 480)
self.train_metric_capts = ["Train.PixAcc"]
self.train_metric_names = ["PixelAccuracyMetric"]
self.train_metric_extra_kwargs = [
{"vague_idx": VOCSegDataset.vague_idx,
"use_vague": VOCSegDataset.use_vague,
"macro_average": False,
"aux": self.train_aux}]
self.val_metric_capts = ["Val.PixAcc", "Val.IoU"]
self.val_metric_names = ["PixelAccuracyMetric", "MeanIoUMetric"]
self.val_metric_extra_kwargs = [
{"vague_idx": VOCSegDataset.vague_idx,
"use_vague": VOCSegDataset.use_vague,
"macro_average": False},
{"num_classes": VOCSegDataset.classes,
"vague_idx": VOCSegDataset.vague_idx,
"use_vague": VOCSegDataset.use_vague,
"bg_idx": VOCSegDataset.background_idx,
"ignore_bg": VOCSegDataset.ignore_bg,
"macro_average": False}]
self.test_metric_capts = ["Test.PixAcc", "Test.IoU"]
self.test_metric_names = self.val_metric_names
self.test_metric_extra_kwargs = self.val_metric_extra_kwargs
self.saver_acc_ind = 1
self.do_transform = True
self.train_transform = voc_transform
self.val_transform = voc_transform
self.test_transform = voc_transform
self.ml_type = "imgseg"
self.allow_hybridize = False
self.train_net_extra_kwargs = {"aux": self.train_aux}
self.test_net_extra_kwargs = {"aux": False, "fixed_size": False}
self.load_ignore_extra = True
self.image_base_size = 520
self.image_crop_size = 480
self.loss_name = "SegSoftmaxCrossEntropy"
self.loss_extra_kwargs = None
# self.loss_name = "MixSoftmaxCrossEntropy"
# self.loss_extra_kwargs = {"aux": self.train_aux, "aux_weight": 0.5}
def add_dataset_parser_arguments(self,
parser,
work_dir_path):
super(VOCMetaInfo, self).add_dataset_parser_arguments(parser, work_dir_path)
parser.add_argument(
"--image-base-size",
type=int,
default=520,
help="base image size")
parser.add_argument(
"--image-crop-size",
type=int,
default=480,
help="crop image size")
def update(self,
args):
super(VOCMetaInfo, self).update(args)
self.image_base_size = args.image_base_size
self.image_crop_size = args.image_crop_size
| 6,554 | 34.625 | 90 | py |
imgclsmob | imgclsmob-master/gluon/datasets/cifar100_cls_dataset.py | """
CIFAR-100 classification dataset.
"""
import os
from mxnet.gluon.data.vision import CIFAR100
from .cifar10_cls_dataset import CIFAR10MetaInfo
class CIFAR100Fine(CIFAR100):
"""
CIFAR-100 image classification dataset.
Parameters:
----------
root : str, default $MXNET_HOME/datasets/cifar100
Path to temp folder for storing data.
mode : str, default 'train'
'train', 'val', or 'test'.
transform : function, default None
A user defined callback that transforms each sample.
"""
def __init__(self,
root=os.path.join("~", ".mxnet", "datasets", "cifar100"),
mode="train",
transform=None):
super(CIFAR100Fine, self).__init__(
root=root,
fine_label=True,
train=(mode == "train"),
transform=transform)
class CIFAR100MetaInfo(CIFAR10MetaInfo):
def __init__(self):
super(CIFAR100MetaInfo, self).__init__()
self.label = "CIFAR100"
self.root_dir_name = "cifar100"
self.dataset_class = CIFAR100Fine
self.num_classes = 100
| 1,133 | 26 | 74 | py |
imgclsmob | imgclsmob-master/gluon/datasets/hpatches_mch_dataset.py | """
HPatches image matching dataset.
"""
import os
import cv2
import numpy as np
import mxnet as mx
from mxnet.gluon.data import dataset
from mxnet.gluon.data.vision import transforms
from .dataset_metainfo import DatasetMetaInfo
class HPatches(dataset.Dataset):
"""
HPatches (full image sequences) image matching dataset.
Info URL: https://github.com/hpatches/hpatches-dataset
Data URL: http://icvl.ee.ic.ac.uk/vbalnt/hpatches/hpatches-sequences-release.tar.gz
Parameters:
----------
root : str, default '~/.mxnet/datasets/hpatches'
Path to the folder stored the dataset.
mode : str, default 'train'
'train', 'val', or 'test'.
alteration : str, default 'all'
'all', 'i' for illumination or 'v' for viewpoint.
transform : function, default None
A function that takes data and label and transforms them.
"""
def __init__(self,
root=os.path.join("~", ".mxnet", "datasets", "hpatches"),
mode="train",
alteration="all",
transform=None):
super(HPatches, self).__init__()
assert os.path.exists(root)
num_images = 5
image_file_ext = ".ppm"
self.mode = mode
self.image_paths = []
self.warped_image_paths = []
self.homographies = []
subdir_names = [name for name in os.listdir(root) if os.path.isdir(os.path.join(root, name))]
if alteration != "all":
subdir_names = [name for name in subdir_names if name[0] == alteration]
for subdir_name in subdir_names:
subdir_path = os.path.join(root, subdir_name)
for i in range(num_images):
k = i + 2
self.image_paths.append(os.path.join(subdir_path, "1" + image_file_ext))
self.warped_image_paths.append(os.path.join(subdir_path, str(k) + image_file_ext))
self.homographies.append(np.loadtxt(os.path.join(subdir_path, "H_1_" + str(k))))
self.transform = transform
def __getitem__(self, index):
# image = cv2.imread(self.image_paths[index], flags=cv2.IMREAD_GRAYSCALE)
# warped_image = cv2.imread(self.warped_image_paths[index], flags=cv2.IMREAD_GRAYSCALE)
# image = mx.image.imread(self.image_paths[index], flag=0)
# warped_image = mx.image.imread(self.warped_image_paths[index], flag=0)
print("Image file name: {}, index: {}".format(self.image_paths[index], index))
image = cv2.imread(self.image_paths[index], flags=0)
if image.shape[0] > 1500:
image = cv2.resize(
src=image,
dsize=None,
fx=0.5,
fy=0.5,
interpolation=cv2.INTER_AREA)
image = mx.nd.array(np.expand_dims(image, axis=2))
print("Image shape: {}".format(image.shape))
warped_image = cv2.imread(self.warped_image_paths[index], flags=0)
if warped_image.shape[0] > 1500:
warped_image = cv2.resize(
src=warped_image,
dsize=None,
fx=0.5,
fy=0.5,
interpolation=cv2.INTER_AREA)
warped_image = mx.nd.array(np.expand_dims(warped_image, axis=2))
print("W-Image shape: {}".format(warped_image.shape))
homography = mx.nd.array(self.homographies[index])
if self.transform is not None:
image = self.transform(image)
warped_image = self.transform(warped_image)
return image, warped_image, homography
def __len__(self):
return len(self.image_paths)
class HPatchesMetaInfo(DatasetMetaInfo):
def __init__(self):
super(HPatchesMetaInfo, self).__init__()
self.label = "hpatches"
self.short_label = "hpatches"
self.root_dir_name = "hpatches"
self.dataset_class = HPatches
self.ml_type = "imgmch"
self.do_transform = True
self.val_transform = hpatches_val_transform
self.test_transform = hpatches_val_transform
self.allow_hybridize = False
self.test_net_extra_kwargs = {"hybridizable": False, "in_size": None}
def hpatches_val_transform(ds_metainfo):
assert (ds_metainfo is not None)
return transforms.Compose([
transforms.ToTensor()
])
def _test():
dataset = HPatches(
root="../imgclsmob_data/hpatches",
mode="train",
alteration="i",
transform=None)
scale_factor = 0.5
for image, warped_image, _ in dataset:
cv2.imshow(
winname="image",
mat=cv2.resize(
src=image,
dsize=None,
fx=scale_factor,
fy=scale_factor,
interpolation=cv2.INTER_NEAREST))
cv2.imshow(
winname="warped_image",
mat=cv2.resize(
src=warped_image,
dsize=None,
fx=scale_factor,
fy=scale_factor,
interpolation=cv2.INTER_NEAREST))
cv2.waitKey(0)
assert (dataset is not None)
if __name__ == "__main__":
_test()
| 5,163 | 33.198675 | 101 | py |
imgclsmob | imgclsmob-master/pytorch/dataset_utils.py | """
Dataset routines.
"""
__all__ = ['get_dataset_metainfo', 'get_train_data_source', 'get_val_data_source', 'get_test_data_source']
from .datasets.imagenet1k_cls_dataset import ImageNet1KMetaInfo
from .datasets.cub200_2011_cls_dataset import CUB200MetaInfo
from .datasets.cifar10_cls_dataset import CIFAR10MetaInfo
from .datasets.cifar100_cls_dataset import CIFAR100MetaInfo
from .datasets.svhn_cls_dataset import SVHNMetaInfo
from .datasets.voc_seg_dataset import VOCMetaInfo
from .datasets.ade20k_seg_dataset import ADE20KMetaInfo
from .datasets.cityscapes_seg_dataset import CityscapesMetaInfo
from .datasets.coco_seg_dataset import CocoSegMetaInfo
from .datasets.coco_det_dataset import CocoDetMetaInfo
from .datasets.coco_hpe1_dataset import CocoHpe1MetaInfo
from .datasets.coco_hpe2_dataset import CocoHpe2MetaInfo
from .datasets.coco_hpe3_dataset import CocoHpe3MetaInfo
from .datasets.hpatches_mch_dataset import HPatchesMetaInfo
from .datasets.librispeech_asr_dataset import LibriSpeechMetaInfo
from .datasets.mcv_asr_dataset import McvMetaInfo
from torch.utils.data import DataLoader
from torch.utils.data.sampler import WeightedRandomSampler
def get_dataset_metainfo(dataset_name):
"""
Get dataset metainfo by name of dataset.
Parameters:
----------
dataset_name : str
Dataset name.
Returns:
-------
DatasetMetaInfo
Dataset metainfo.
"""
dataset_metainfo_map = {
"ImageNet1K": ImageNet1KMetaInfo,
"CUB200_2011": CUB200MetaInfo,
"CIFAR10": CIFAR10MetaInfo,
"CIFAR100": CIFAR100MetaInfo,
"SVHN": SVHNMetaInfo,
"VOC": VOCMetaInfo,
"ADE20K": ADE20KMetaInfo,
"Cityscapes": CityscapesMetaInfo,
"CocoSeg": CocoSegMetaInfo,
"CocoDet": CocoDetMetaInfo,
"CocoHpe1": CocoHpe1MetaInfo,
"CocoHpe2": CocoHpe2MetaInfo,
"CocoHpe3": CocoHpe3MetaInfo,
"HPatches": HPatchesMetaInfo,
"LibriSpeech": LibriSpeechMetaInfo,
"MCV": McvMetaInfo,
}
if dataset_name in dataset_metainfo_map.keys():
return dataset_metainfo_map[dataset_name]()
else:
raise Exception("Unrecognized dataset: {}".format(dataset_name))
def get_train_data_source(ds_metainfo,
batch_size,
num_workers):
"""
Get data source for training subset.
Parameters:
----------
ds_metainfo : DatasetMetaInfo
Dataset metainfo.
batch_size : int
Batch size.
num_workers : int
Number of background workers.
Returns:
-------
DataLoader
Data source.
"""
transform_train = ds_metainfo.train_transform(ds_metainfo=ds_metainfo)
kwargs = ds_metainfo.dataset_class_extra_kwargs if ds_metainfo.dataset_class_extra_kwargs is not None else {}
dataset = ds_metainfo.dataset_class(
root=ds_metainfo.root_dir_path,
mode="train",
transform=transform_train,
**kwargs)
ds_metainfo.update_from_dataset(dataset)
if not ds_metainfo.train_use_weighted_sampler:
return DataLoader(
dataset=dataset,
batch_size=batch_size,
shuffle=True,
num_workers=num_workers,
pin_memory=True)
else:
sampler = WeightedRandomSampler(
weights=dataset.sample_weights,
num_samples=len(dataset))
return DataLoader(
dataset=dataset,
batch_size=batch_size,
# shuffle=True,
sampler=sampler,
num_workers=num_workers,
pin_memory=True)
def get_val_data_source(ds_metainfo,
batch_size,
num_workers):
"""
Get data source for validation subset.
Parameters:
----------
ds_metainfo : DatasetMetaInfo
Dataset metainfo.
batch_size : int
Batch size.
num_workers : int
Number of background workers.
Returns:
-------
DataLoader
Data source.
"""
transform_val = ds_metainfo.val_transform(ds_metainfo=ds_metainfo)
kwargs = ds_metainfo.dataset_class_extra_kwargs if ds_metainfo.dataset_class_extra_kwargs is not None else {}
dataset = ds_metainfo.dataset_class(
root=ds_metainfo.root_dir_path,
mode="val",
transform=transform_val,
**kwargs)
ds_metainfo.update_from_dataset(dataset)
return DataLoader(
dataset=dataset,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=True)
def get_test_data_source(ds_metainfo,
batch_size,
num_workers):
"""
Get data source for testing subset.
Parameters:
----------
ds_metainfo : DatasetMetaInfo
Dataset metainfo.
batch_size : int
Batch size.
num_workers : int
Number of background workers.
Returns:
-------
DataLoader
Data source.
"""
transform_test = ds_metainfo.test_transform(ds_metainfo=ds_metainfo)
kwargs = ds_metainfo.dataset_class_extra_kwargs if ds_metainfo.dataset_class_extra_kwargs is not None else {}
dataset = ds_metainfo.dataset_class(
root=ds_metainfo.root_dir_path,
mode="test",
transform=transform_test,
**kwargs)
ds_metainfo.update_from_dataset(dataset)
return DataLoader(
dataset=dataset,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=True)
| 5,563 | 29.404372 | 113 | py |
imgclsmob | imgclsmob-master/pytorch/model_stats.py | """
Routines for model statistics calculation.
"""
import logging
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from .pytorchcv.models.common import ChannelShuffle, ChannelShuffle2, Identity, Flatten, Swish, HSigmoid, HSwish,\
InterpolationBlock, HeatmapMaxDetBlock
from .pytorchcv.models.fishnet import ChannelSqueeze
from .pytorchcv.models.irevnet import IRevDownscale, IRevSplitBlock, IRevMergeBlock
from .pytorchcv.models.rir_cifar import RiRFinalBlock
from .pytorchcv.models.proxylessnas import ProxylessUnit
from .pytorchcv.models.lwopenpose_cmupan import LwopDecoderFinalBlock
from .pytorchcv.models.centernet import CenterNetHeatmapMaxDet
from .pytorchcv.models.danet import ScaleBlock
from .pytorchcv.models.jasper import MaskConv1d, NemoMelSpecExtractor
__all__ = ['measure_model']
def calc_block_num_params2(net):
"""
Calculate number of trainable parameters in the block (not iterative).
Parameters:
----------
net : Module
Model/block.
Returns:
-------
int
Number of parameters.
"""
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def calc_block_num_params(module):
"""
Calculate number of trainable parameters in the block (iterative).
Parameters:
----------
module : Module
Model/block.
Returns:
-------
int
Number of parameters.
"""
assert isinstance(module, nn.Module)
net_params = filter(lambda p: isinstance(p[1], nn.parameter.Parameter) and p[1].requires_grad,
module._parameters.items())
weight_count = 0
for param in net_params:
weight_count += np.prod(param[1].size())
return weight_count
def measure_model(model,
in_shapes):
"""
Calculate model statistics.
Parameters:
----------
model : HybridBlock
Tested model.
in_shapes : list of tuple of ints
Shapes of the input tensors.
"""
global num_flops
global num_macs
global num_params
# global names
num_flops = 0
num_macs = 0
num_params = 0
# names = {}
def call_hook(module, x, y):
if not (isinstance(module, IRevSplitBlock) or isinstance(module, IRevMergeBlock) or
isinstance(module, RiRFinalBlock) or isinstance(module, InterpolationBlock) or
isinstance(module, MaskConv1d) or isinstance(module, NemoMelSpecExtractor)):
assert (len(x) == 1)
assert (len(module._modules) == 0)
if isinstance(module, nn.Linear):
batch = x[0].shape[0]
in_units = module.in_features
out_units = module.out_features
extra_num_macs = in_units * out_units
if module.bias is None:
extra_num_flops = (2 * in_units - 1) * out_units
else:
extra_num_flops = 2 * in_units * out_units
extra_num_flops *= batch
extra_num_macs *= batch
elif isinstance(module, nn.ReLU):
extra_num_flops = x[0].numel()
extra_num_macs = 0
elif isinstance(module, nn.ELU):
extra_num_flops = 3 * x[0].numel()
extra_num_macs = 0
elif isinstance(module, nn.Sigmoid):
extra_num_flops = 4 * x[0].numel()
extra_num_macs = 0
elif isinstance(module, nn.LeakyReLU):
extra_num_flops = 2 * x[0].numel()
extra_num_macs = 0
elif isinstance(module, nn.ReLU6):
extra_num_flops = x[0].numel()
extra_num_macs = 0
elif isinstance(module, nn.PReLU):
extra_num_flops = 3 * x[0].numel()
extra_num_macs = 0
elif isinstance(module, Swish):
extra_num_flops = 5 * x[0].numel()
extra_num_macs = 0
elif isinstance(module, HSigmoid):
extra_num_flops = x[0].numel()
extra_num_macs = 0
elif isinstance(module, HSwish):
extra_num_flops = 2 * x[0].numel()
extra_num_macs = 0
elif type(module) in [nn.ConvTranspose2d]:
extra_num_flops = 4 * x[0].numel()
extra_num_macs = 0
elif type(module) in [nn.Conv2d]:
batch = x[0].shape[0]
x_h = x[0].shape[2]
x_w = x[0].shape[3]
kernel_size = module.kernel_size
stride = module.stride
dilation = module.dilation
padding = module.padding
groups = module.groups
in_channels = module.in_channels
out_channels = module.out_channels
y_h = (x_h + 2 * padding[0] - dilation[0] * (kernel_size[0] - 1) - 1) // stride[0] + 1
y_w = (x_w + 2 * padding[1] - dilation[1] * (kernel_size[1] - 1) - 1) // stride[1] + 1
assert (out_channels == y.shape[1])
assert (y_h == y.shape[2])
assert (y_w == y.shape[3])
kernel_total_size = kernel_size[0] * kernel_size[1]
y_size = y_h * y_w
extra_num_macs = kernel_total_size * in_channels * y_size * out_channels // groups
if module.bias is None:
extra_num_flops = (2 * kernel_total_size * y_size - 1) * in_channels * out_channels // groups
else:
extra_num_flops = 2 * kernel_total_size * in_channels * y_size * out_channels // groups
extra_num_flops *= batch
extra_num_macs *= batch
elif isinstance(module, nn.BatchNorm2d):
extra_num_flops = 4 * x[0].numel()
extra_num_macs = 0
elif isinstance(module, nn.InstanceNorm2d):
extra_num_flops = 4 * x[0].numel()
extra_num_macs = 0
elif isinstance(module, nn.BatchNorm1d):
extra_num_flops = 4 * x[0].numel()
extra_num_macs = 0
elif type(module) in [nn.MaxPool2d, nn.AvgPool2d]:
assert (x[0].shape[1] == y.shape[1])
batch = x[0].shape[0]
kernel_size = module.kernel_size if isinstance(module.kernel_size, tuple) else\
(module.kernel_size, module.kernel_size)
y_h = y.shape[2]
y_w = y.shape[3]
channels = x[0].shape[1]
y_size = y_h * y_w
pool_total_size = kernel_size[0] * kernel_size[1]
extra_num_flops = channels * y_size * pool_total_size
extra_num_macs = 0
extra_num_flops *= batch
extra_num_macs *= batch
elif type(module) in [nn.AdaptiveAvgPool2d, nn.AdaptiveMaxPool2d]:
assert (x[0].shape[1] == y.shape[1])
batch = x[0].shape[0]
x_h = x[0].shape[2]
x_w = x[0].shape[3]
y_h = y.shape[2]
y_w = y.shape[3]
channels = x[0].shape[1]
y_size = y_h * y_w
pool_total_size = x_h * x_w
extra_num_flops = channels * y_size * pool_total_size
extra_num_macs = 0
extra_num_flops *= batch
extra_num_macs *= batch
elif isinstance(module, nn.Dropout):
extra_num_flops = 0
extra_num_macs = 0
elif isinstance(module, nn.Sequential):
assert (len(module._modules) == 0)
extra_num_flops = 0
extra_num_macs = 0
elif type(module) in [ChannelShuffle, ChannelShuffle2]:
extra_num_flops = x[0].numel()
extra_num_macs = 0
elif isinstance(module, nn.ZeroPad2d):
extra_num_flops = 0
extra_num_macs = 0
elif isinstance(module, Identity):
extra_num_flops = 0
extra_num_macs = 0
elif isinstance(module, nn.PixelShuffle):
extra_num_flops = x[0].numel()
extra_num_macs = 0
elif isinstance(module, Flatten):
extra_num_flops = 0
extra_num_macs = 0
elif isinstance(module, nn.Upsample):
extra_num_flops = 4 * x[0].numel()
extra_num_macs = 0
elif isinstance(module, ChannelSqueeze):
extra_num_flops = x[0].numel()
extra_num_macs = 0
elif isinstance(module, IRevDownscale):
extra_num_flops = 5 * x[0].numel()
extra_num_macs = 0
elif isinstance(module, IRevSplitBlock):
extra_num_flops = x[0].numel()
extra_num_macs = 0
elif isinstance(module, IRevMergeBlock):
extra_num_flops = x[0].numel()
extra_num_macs = 0
elif isinstance(module, RiRFinalBlock):
extra_num_flops = x[0].numel()
extra_num_macs = 0
elif isinstance(module, ProxylessUnit):
extra_num_flops = x[0].numel()
extra_num_macs = 0
elif type(module) in [nn.Softmax2d, nn.Softmax]:
extra_num_flops = 4 * x[0].numel()
extra_num_macs = 0
elif type(module) in [MaskConv1d, nn.Conv1d]:
if isinstance(y, tuple):
assert isinstance(module, MaskConv1d)
y = y[0]
batch = x[0].shape[0]
x_h = x[0].shape[2]
kernel_size = module.kernel_size
stride = module.stride
dilation = module.dilation
padding = module.padding
groups = module.groups
in_channels = module.in_channels
out_channels = module.out_channels
y_h = (x_h + 2 * padding[0] - dilation[0] * (kernel_size[0] - 1) - 1) // stride[0] + 1
assert (out_channels == y.shape[1])
assert (y_h == y.shape[2])
kernel_total_size = kernel_size[0]
y_size = y_h
extra_num_macs = kernel_total_size * in_channels * y_size * out_channels // groups
if module.bias is None:
extra_num_flops = (2 * kernel_total_size * y_size - 1) * in_channels * out_channels // groups
else:
extra_num_flops = 2 * kernel_total_size * in_channels * y_size * out_channels // groups
extra_num_flops *= batch
extra_num_macs *= batch
elif type(module) in [InterpolationBlock, HeatmapMaxDetBlock, CenterNetHeatmapMaxDet, ScaleBlock,
NemoMelSpecExtractor]:
extra_num_flops, extra_num_macs = module.calc_flops(x[0])
elif isinstance(module, LwopDecoderFinalBlock):
if not module.calc_3d_features:
extra_num_flops = 0
extra_num_macs = 0
else:
raise TypeError("LwopDecoderFinalBlock!")
else:
raise TypeError("Unknown layer type: {}".format(type(module)))
global num_flops
global num_macs
global num_params
# global names
num_flops += extra_num_flops
num_macs += extra_num_macs
# if module.name not in names:
# names[module.name] = 1
# num_params += calc_block_num_params(module)
num_params += calc_block_num_params(module)
def register_forward_hooks(a_module):
if len(a_module._modules) > 0:
assert (calc_block_num_params(a_module) == 0)
children_handles = []
for child_module in a_module._modules.values():
child_handles = register_forward_hooks(child_module)
children_handles += child_handles
return children_handles
else:
handle = a_module.register_forward_hook(call_hook)
return [handle]
hook_handles = register_forward_hooks(model)
model.eval()
if len(in_shapes) == 1:
x = Variable(torch.zeros(*in_shapes[0]))
model(x)
elif len(in_shapes) == 2:
x1 = Variable(torch.zeros(*in_shapes[0]))
x2 = Variable(torch.zeros(*in_shapes[1]))
model(x1, x2)
else:
raise NotImplementedError()
num_params1 = calc_block_num_params2(model)
if num_params != num_params1:
logging.warning(
"Calculated numbers of parameters are different: standard method: {},\tper-leaf method: {}".format(
num_params1, num_params))
[h.remove() for h in hook_handles]
return num_flops, num_macs, num_params1
| 12,391 | 37.01227 | 114 | py |
imgclsmob | imgclsmob-master/pytorch/setup.py | from setuptools import setup, find_packages
from os import path
from io import open
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='pytorchcv',
version='0.0.67',
description='Image classification and segmentation models for PyTorch',
license='MIT',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/osmr/imgclsmob',
author='Oleg Sémery',
author_email='osemery@gmail.com',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: Image Recognition',
],
keywords='machine-learning deep-learning neuralnetwork image-classification pytorch imagenet cifar svhn vgg resnet '
'pyramidnet diracnet densenet condensenet wrn drn dpn darknet fishnet espnetv2 xdensnet squeezenet '
'squeezenext shufflenet menet mobilenet igcv3 mnasnet darts xception inception polynet nasnet pnasnet ror '
'proxylessnas dianet efficientnet mixnet image-segmentation voc ade20k cityscapes coco pspnet deeplabv3 '
'fcn',
packages=find_packages(exclude=['datasets', 'metrics', 'others', '*.others', 'others.*', '*.others.*']),
include_package_data=True,
install_requires=['numpy', 'requests'],
)
| 1,571 | 42.666667 | 120 | py |
imgclsmob | imgclsmob-master/pytorch/utils.py | """
Main routines shared between training and evaluation scripts.
"""
import logging
import os
import numpy as np
import torch.utils.data
from .pytorchcv.model_provider import get_model
from .metrics.metric import EvalMetric, CompositeEvalMetric
from .metrics.cls_metrics import Top1Error, TopKError
from .metrics.seg_metrics import PixelAccuracyMetric, MeanIoUMetric
from .metrics.det_metrics import CocoDetMApMetric
from .metrics.hpe_metrics import CocoHpeOksApMetric
from .metrics.asr_metrics import WER
def prepare_pt_context(num_gpus,
batch_size):
"""
Correct batch size.
Parameters:
----------
num_gpus : int
Number of GPU.
batch_size : int
Batch size for each GPU.
Returns:
-------
bool
Whether to use CUDA.
int
Batch size for all GPUs.
"""
use_cuda = (num_gpus > 0)
batch_size *= max(1, num_gpus)
return use_cuda, batch_size
def prepare_model(model_name,
use_pretrained,
pretrained_model_file_path,
use_cuda,
use_data_parallel=True,
net_extra_kwargs=None,
load_ignore_extra=False,
num_classes=None,
in_channels=None,
remap_to_cpu=False,
remove_module=False):
"""
Create and initialize model by name.
Parameters:
----------
model_name : str
Model name.
use_pretrained : bool
Whether to use pretrained weights.
pretrained_model_file_path : str
Path to file with pretrained weights.
use_cuda : bool
Whether to use CUDA.
use_data_parallel : bool, default True
Whether to use parallelization.
net_extra_kwargs : dict, default None
Extra parameters for model.
load_ignore_extra : bool, default False
Whether to ignore extra layers in pretrained model.
num_classes : int, default None
Number of classes.
in_channels : int, default None
Number of input channels.
remap_to_cpu : bool, default False
Whether to remape model to CPU during loading.
remove_module : bool, default False
Whether to remove module from loaded model.
Returns:
-------
Module
Model.
"""
kwargs = {"pretrained": use_pretrained}
if num_classes is not None:
kwargs["num_classes"] = num_classes
if in_channels is not None:
kwargs["in_channels"] = in_channels
if net_extra_kwargs is not None:
kwargs.update(net_extra_kwargs)
net = get_model(model_name, **kwargs)
if pretrained_model_file_path:
assert (os.path.isfile(pretrained_model_file_path))
logging.info("Loading model: {}".format(pretrained_model_file_path))
checkpoint = torch.load(
pretrained_model_file_path,
map_location=(None if use_cuda and not remap_to_cpu else "cpu"))
if (type(checkpoint) == dict) and ("state_dict" in checkpoint):
checkpoint = checkpoint["state_dict"]
if load_ignore_extra:
pretrained_state = checkpoint
model_dict = net.state_dict()
pretrained_state = {k: v for k, v in pretrained_state.items() if k in model_dict}
net.load_state_dict(pretrained_state)
else:
if remove_module:
net_tmp = torch.nn.DataParallel(net)
net_tmp.load_state_dict(checkpoint)
net.load_state_dict(net_tmp.module.cpu().state_dict())
else:
net.load_state_dict(checkpoint)
if use_data_parallel and use_cuda:
net = torch.nn.DataParallel(net)
if use_cuda:
net = net.cuda()
return net
def calc_net_weight_count(net):
"""
Calculate number of model trainable parameters.
Parameters:
----------
net : Module
Model.
Returns:
-------
int
Number of parameters.
"""
net.train()
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def validate(metric,
net,
val_data,
use_cuda):
"""
Core validation/testing routine.
Parameters:
----------
metric : EvalMetric
Metric object instance.
net : Module
Model.
val_data : DataLoader
Data loader.
use_cuda : bool
Whether to use CUDA.
Returns:
-------
EvalMetric
Metric object instance.
"""
net.eval()
metric.reset()
with torch.no_grad():
for data, target in val_data:
if use_cuda:
target = target.cuda(non_blocking=True)
output = net(data)
metric.update(target, output)
return metric
def report_accuracy(metric,
extended_log=False):
"""
Make report string for composite metric.
Parameters:
----------
metric : EvalMetric
Metric object instance.
extended_log : bool, default False
Whether to log more precise accuracy values.
Returns:
-------
str
Report string.
"""
def create_msg(name, value):
if type(value) in [list, tuple]:
if extended_log:
return "{}={} ({})".format("{}", "/".join(["{:.4f}"] * len(value)), "/".join(["{}"] * len(value))).\
format(name, *(value + value))
else:
return "{}={}".format("{}", "/".join(["{:.4f}"] * len(value))).format(name, *value)
else:
if extended_log:
return "{name}={value:.4f} ({value})".format(name=name, value=value)
else:
return "{name}={value:.4f}".format(name=name, value=value)
metric_info = metric.get()
if isinstance(metric, CompositeEvalMetric):
msg = ", ".join([create_msg(name=m[0], value=m[1]) for m in zip(*metric_info)])
elif isinstance(metric, EvalMetric):
msg = create_msg(name=metric_info[0], value=metric_info[1])
else:
raise Exception("Wrong metric type: {}".format(type(metric)))
return msg
def get_metric(metric_name, metric_extra_kwargs):
"""
Get metric by name.
Parameters:
----------
metric_name : str
Metric name.
metric_extra_kwargs : dict
Metric extra parameters.
EvalMetric
-------
EvalMetric
Metric object instance.
"""
if metric_name == "Top1Error":
return Top1Error(**metric_extra_kwargs)
elif metric_name == "TopKError":
return TopKError(**metric_extra_kwargs)
elif metric_name == "PixelAccuracyMetric":
return PixelAccuracyMetric(**metric_extra_kwargs)
elif metric_name == "MeanIoUMetric":
return MeanIoUMetric(**metric_extra_kwargs)
elif metric_name == "CocoDetMApMetric":
return CocoDetMApMetric(**metric_extra_kwargs)
elif metric_name == "CocoHpeOksApMetric":
return CocoHpeOksApMetric(**metric_extra_kwargs)
elif metric_name == "WER":
return WER(**metric_extra_kwargs)
else:
raise Exception("Wrong metric name: {}".format(metric_name))
def get_composite_metric(metric_names, metric_extra_kwargs):
"""
Get composite metric by list of metric names.
Parameters:
----------
metric_names : list of str
Metric name list.
metric_extra_kwargs : list of dict
Metric extra parameters list.
Returns:
-------
CompositeEvalMetric
Metric object instance.
"""
if len(metric_names) == 1:
metric = get_metric(metric_names[0], metric_extra_kwargs[0])
else:
metric = CompositeEvalMetric()
for name, extra_kwargs in zip(metric_names, metric_extra_kwargs):
metric.add(get_metric(name, extra_kwargs))
return metric
def get_metric_name(metric, index):
"""
Get metric name by index in the composite metric.
Parameters:
----------
metric : CompositeEvalMetric or EvalMetric
Metric object instance.
index : int
Index.
Returns:
-------
str
Metric name.
"""
if isinstance(metric, CompositeEvalMetric):
return metric.metrics[index].name
elif isinstance(metric, EvalMetric):
assert (index == 0)
return metric.name
else:
raise Exception("Wrong metric type: {}".format(type(metric)))
| 8,538 | 26.996721 | 116 | py |
imgclsmob | imgclsmob-master/pytorch/metrics/seg_metrics.py | """
Evaluation Metrics for Semantic Segmentation.
"""
import numpy as np
import torch
from .metric import EvalMetric, check_label_shapes
from .seg_metrics_np import seg_pixel_accuracy_np, seg_mean_iou_imasks_np
__all__ = ['PixelAccuracyMetric', 'MeanIoUMetric']
class PixelAccuracyMetric(EvalMetric):
"""
Computes the pixel-wise accuracy.
Parameters:
----------
axis : int, default 1
The axis that represents classes.
name : str, default 'pix_acc'
Name of this metric instance for display.
output_names : list of str, or None, default None
Name of predictions that should be used when updating with update_dict.
By default include all predictions.
label_names : list of str, or None, default None
Name of labels that should be used when updating with update_dict.
By default include all labels.
on_cpu : bool, default True
Calculate on CPU.
sparse_label : bool, default True
Whether label is an integer array instead of probability distribution.
vague_idx : int, default -1
Index of masked pixels.
use_vague : bool, default False
Whether to use pixel masking.
macro_average : bool, default True
Whether to use micro or macro averaging.
"""
def __init__(self,
axis=1,
name="pix_acc",
output_names=None,
label_names=None,
on_cpu=True,
sparse_label=True,
vague_idx=-1,
use_vague=False,
macro_average=True):
self.macro_average = macro_average
super(PixelAccuracyMetric, self).__init__(
name,
axis=axis,
output_names=output_names,
label_names=label_names)
self.axis = axis
self.on_cpu = on_cpu
self.sparse_label = sparse_label
self.vague_idx = vague_idx
self.use_vague = use_vague
def update(self, labels, preds):
"""
Updates the internal evaluation result.
Parameters:
----------
labels : torch.Tensor
The labels of the data.
preds : torch.Tensor
Predicted values.
"""
with torch.no_grad():
check_label_shapes(labels, preds)
if self.on_cpu:
if self.sparse_label:
label_imask = labels.cpu().numpy().astype(np.int32)
else:
label_imask = torch.argmax(labels, dim=self.axis).cpu().numpy().astype(np.int32)
pred_imask = torch.argmax(preds, dim=self.axis).cpu().numpy().astype(np.int32)
acc = seg_pixel_accuracy_np(
label_imask=label_imask,
pred_imask=pred_imask,
vague_idx=self.vague_idx,
use_vague=self.use_vague,
macro_average=self.macro_average)
if self.macro_average:
self.sum_metric += acc
self.num_inst += 1
else:
self.sum_metric += acc[0]
self.num_inst += acc[1]
else:
assert False
def reset(self):
"""
Resets the internal evaluation result to initial state.
"""
if self.macro_average:
self.num_inst = 0
self.sum_metric = 0.0
else:
self.num_inst = 0
self.sum_metric = 0
def get(self):
"""
Gets the current evaluation result.
Returns:
-------
names : list of str
Name of the metrics.
values : list of float
Value of the evaluations.
"""
if self.macro_average:
if self.num_inst == 0:
return self.name, float("nan")
else:
return self.name, self.sum_metric / self.num_inst
else:
if self.num_inst == 0:
return self.name, float("nan")
else:
return self.name, float(self.sum_metric) / self.num_inst
class MeanIoUMetric(EvalMetric):
"""
Computes the mean intersection over union.
Parameters:
----------
axis : int, default 1
The axis that represents classes
name : str, default 'mean_iou'
Name of this metric instance for display.
output_names : list of str, or None, default None
Name of predictions that should be used when updating with update_dict.
By default include all predictions.
label_names : list of str, or None, default None
Name of labels that should be used when updating with update_dict.
By default include all labels.
on_cpu : bool, default True
Calculate on CPU.
sparse_label : bool, default True
Whether label is an integer array instead of probability distribution.
num_classes : int
Number of classes
vague_idx : int, default -1
Index of masked pixels.
use_vague : bool, default False
Whether to use pixel masking.
bg_idx : int, default -1
Index of background class.
ignore_bg : bool, default False
Whether to ignore background class.
macro_average : bool, default True
Whether to use micro or macro averaging.
"""
def __init__(self,
axis=1,
name="mean_iou",
output_names=None,
label_names=None,
on_cpu=True,
sparse_label=True,
num_classes=None,
vague_idx=-1,
use_vague=False,
bg_idx=-1,
ignore_bg=False,
macro_average=True):
self.macro_average = macro_average
self.num_classes = num_classes
self.ignore_bg = ignore_bg
super(MeanIoUMetric, self).__init__(
name,
axis=axis,
output_names=output_names,
label_names=label_names)
assert ((not ignore_bg) or (bg_idx in (0, num_classes - 1)))
self.axis = axis
self.on_cpu = on_cpu
self.sparse_label = sparse_label
self.vague_idx = vague_idx
self.use_vague = use_vague
self.bg_idx = bg_idx
assert (on_cpu and sparse_label)
def update(self, labels, preds):
"""
Updates the internal evaluation result.
Parameters:
----------
labels : torch.Tensor
The labels of the data.
preds : torch.Tensor
Predicted values.
"""
assert (len(labels) == len(preds))
with torch.no_grad():
if self.on_cpu:
if self.sparse_label:
label_imask = labels.cpu().numpy().astype(np.int32)
else:
assert False
pred_imask = torch.argmax(preds, dim=self.axis).cpu().numpy().astype(np.int32)
batch_size = labels.shape[0]
for k in range(batch_size):
if self.sparse_label:
acc = seg_mean_iou_imasks_np(
label_imask=label_imask[k, :, :],
pred_imask=pred_imask[k, :, :],
num_classes=self.num_classes,
vague_idx=self.vague_idx,
use_vague=self.use_vague,
bg_idx=self.bg_idx,
ignore_bg=self.ignore_bg,
macro_average=self.macro_average)
else:
assert False
if self.macro_average:
self.sum_metric += acc
self.num_inst += 1
else:
self.area_inter += acc[0]
self.area_union += acc[1]
else:
assert False
def reset(self):
"""
Resets the internal evaluation result to initial state.
"""
if self.macro_average:
self.num_inst = 0
self.sum_metric = 0.0
else:
class_count = self.num_classes - 1 if self.ignore_bg else self.num_classes
self.area_inter = np.zeros((class_count,), np.uint64)
self.area_union = np.zeros((class_count,), np.uint64)
def get(self):
"""
Gets the current evaluation result.
Returns:
-------
names : list of str
Name of the metrics.
values : list of float
Value of the evaluations.
"""
if self.macro_average:
if self.num_inst == 0:
return self.name, float("nan")
else:
return self.name, self.sum_metric / self.num_inst
else:
class_count = (self.area_union > 0).sum()
if class_count == 0:
return self.name, float("nan")
eps = np.finfo(np.float32).eps
area_union_eps = self.area_union + eps
mean_iou = (self.area_inter / area_union_eps).sum() / class_count
return self.name, mean_iou
| 9,276 | 33.106618 | 100 | py |
imgclsmob | imgclsmob-master/pytorch/metrics/ret_metrics.py | """
Evaluation Metrics for Image Retrieval.
"""
import numpy as np
import torch
from .metric import EvalMetric
__all__ = ['PointDetectionMatchRatio', 'PointDescriptionMatchRatio']
class PointDetectionMatchRatio(EvalMetric):
"""
Computes point detection match ratio (with mean residual).
Parameters:
----------
pts_max_count : int
Maximal count of points.
axis : int, default 1
The axis that represents classes
name : str, default 'accuracy'
Name of this metric instance for display.
output_names : list of str, or None, default None
Name of predictions that should be used when updating with update_dict.
By default include all predictions.
label_names : list of str, or None, default None
Name of labels that should be used when updating with update_dict.
By default include all labels.
"""
def __init__(self,
pts_max_count,
axis=1,
name="pt_det_ratio",
output_names=None,
label_names=None):
super(PointDetectionMatchRatio, self).__init__(
name,
axis=axis,
output_names=output_names,
label_names=label_names,
has_global_stats=True)
self.axis = axis
self.pts_max_count = pts_max_count
self.resudual_sum = 0.0
self.resudual_count = 0
def update_alt(self,
homography,
src_pts,
dst_pts,
src_confs,
dst_confs,
src_img_size,
dst_img_size):
"""
Updates the internal evaluation result.
Parameters:
----------
homography : torch.Tensor
Homography (from source image to destination one).
src_pts : torch.Tensor
Detected points for the first (source) image.
dst_pts : torch.Tensor
Detected points for the second (destination) image.
src_confs : torch.Tensor
Confidences for detected points on the source image.
dst_confs : torch.Tensor
Confidences for detected points on the destination image.
src_img_size : tuple of 2 int
Size (H, W) of the source image.
dst_img_size : tuple of 2 int
Size (H, W) of the destination image.
"""
assert (src_confs.argsort(descending=True).cpu().detach().numpy() == np.arange(src_confs.shape[0])).all()
assert (dst_confs.argsort(descending=True).cpu().detach().numpy() == np.arange(dst_confs.shape[0])).all()
max_dist_sat_value = 1e5
eps = 1e-5
# print("src_img_size={}".format(src_img_size))
# print("dst_img_size={}".format(dst_img_size))
homography = homography.to(src_pts.device)
self.normalize_homography(homography)
homography_inv = self.calc_homography_inv(homography)
# print("homography={}".format(homography))
# print("homography_inv={}".format(homography_inv))
# print("src_pts={}".format(src_pts[:10, :].int()))
src_pts = src_pts.flip(dims=(1,))
dst_pts = dst_pts.flip(dims=(1,))
# print("src_pts={}".format(src_pts[:10, :].int()))
# print("src_pts.shape={}".format(src_pts.shape))
# print("dst_pts.shape={}".format(dst_pts.shape))
# print("src_pts={}".format(src_pts[:10, :].int()))
# print("dst_pts={}".format(dst_pts[:10, :].int()))
# with torch.no_grad():
src_hmg_pts = self.calc_homogeneous_coords(src_pts.float())
dst_hmg_pts = self.calc_homogeneous_coords(dst_pts.float())
# print("src_hmg_pts={}".format(src_hmg_pts[:10, :].int()))
# print("dst_hmg_pts={}".format(dst_hmg_pts[:10, :].int()))
src_hmg_pts, src_confs = self.filter_inside_points(
src_hmg_pts,
src_confs,
homography,
dst_img_size)
dst_hmg_pts, dst_confs = self.filter_inside_points(
dst_hmg_pts,
dst_confs,
homography_inv,
src_img_size)
# print("src_hmg_pts.shape={}".format(src_hmg_pts.shape))
# print("dst_hmg_pts.shape={}".format(dst_hmg_pts.shape))
#
# print("src_hmg_pts={}".format(src_hmg_pts[:10, :].int()))
# print("dst_hmg_pts={}".format(dst_hmg_pts[:10, :].int()))
src_pts_count = src_hmg_pts.shape[0]
dst_pts_count = dst_hmg_pts.shape[0]
src_pts_count2 = min(src_pts_count, self.pts_max_count)
src_hmg_pts, conf_thr = self.filter_best_points(
hmg_pts=src_hmg_pts,
confs=src_confs,
max_count=src_pts_count2,
min_conf=None)
dst_pts_count2 = min(dst_pts_count, self.pts_max_count)
dst_hmg_pts, _ = self.filter_best_points(
hmg_pts=dst_hmg_pts,
confs=dst_confs,
max_count=dst_pts_count2,
min_conf=conf_thr)
# print("src_hmg_pts.shape={}".format(src_hmg_pts.shape))
# print("dst_hmg_pts.shape={}".format(dst_hmg_pts.shape))
# print("src_hmg_pts={}".format(src_hmg_pts[:10, :].int()))
# print("dst_hmg_pts={}".format(dst_hmg_pts[:10, :].int()))
preds_dst_hmg_pts = self.transform_points(
src_hmg_pts,
homography)
# print("preds_dst_hmg_pts={}".format(preds_dst_hmg_pts[:10, :].int()))
cost = self.calc_pairwise_distances(x=preds_dst_hmg_pts, y=dst_hmg_pts).cpu().detach().numpy()
self.saturate_distance_matrix(
dist_mat=cost,
max_dist_thr=8.0,
max_dist_sat=max_dist_sat_value)
# print("cost.shape={}".format(cost.shape))
from scipy.optimize import linear_sum_assignment
row_ind, col_ind = linear_sum_assignment(cost)
# print("row_ind.shape={}".format(row_ind.shape))
# print("col_ind.shape={}".format(col_ind.shape))
resuduals = cost[row_ind, col_ind]
resuduals = resuduals[resuduals < (max_dist_sat_value - eps)]
resudual_count = len(resuduals)
self.sum_metric += resudual_count
self.global_sum_metric += resudual_count
self.num_inst += src_pts_count2
self.global_num_inst += src_pts_count2
print("ratio_resudual={}".format(float(resudual_count) / src_pts_count2))
if resudual_count != 0:
self.resudual_sum += resuduals.sum()
self.resudual_count += resudual_count
@staticmethod
def normalize_homography(homography):
homography /= homography[2, 2]
@staticmethod
def calc_homography_inv(homography):
homography_inv = homography.inverse()
PointDetectionMatchRatio.normalize_homography(homography_inv)
return homography_inv
@staticmethod
def calc_homogeneous_coords(pts):
hmg_pts = torch.cat((pts, torch.ones((pts.shape[0], 1), dtype=pts.dtype, device=pts.device)), dim=1)
return hmg_pts
@staticmethod
def calc_cartesian_coords(hmg_pts):
pts = hmg_pts[:, :2]
return pts
@staticmethod
def transform_points(src_hmg_pts,
homography):
# print("transform_points -> src_hmg_pts.shape={}".format(src_hmg_pts.shape))
# print("transform_points -> homography.shape={}".format(homography.shape))
# print("homography={}".format(homography))
# print("transform_points -> src_hmg_pts={}".format(src_hmg_pts[:10, :].int()))
dst_hmg_pts = torch.matmul(src_hmg_pts, homography.t())
# print("transform_points -> dst_hmg_pts={}".format(dst_hmg_pts[:10, :].int()))
# print("transform_points -> dst_hmg_pts.shape={}".format(dst_hmg_pts.shape))
dst_hmg_pts /= dst_hmg_pts[:, 2:]
return dst_hmg_pts
@staticmethod
def calc_inside_pts_mask(pts,
img_size):
eps = 1e-3
border_size = 1.0
border = border_size - eps
mask = (pts[:, 0] >= border) & (pts[:, 0] < img_size[0] - border) &\
(pts[:, 1] >= border) & (pts[:, 1] < img_size[1] - border)
return mask
@staticmethod
def filter_inside_points(src_hmg_pts,
src_confs,
homography,
dst_img_size):
# print("fip->src_hmg_pts.shape={}".format(src_hmg_pts.shape))
# print("fip->src_hmg_pts={}".format(src_hmg_pts[:10, :].int()))
# print("fip->src_confs.shape={}".format(src_confs.shape))
# print("fip->src_confs={}".format(src_confs[:10]))
# print("homography_inv={}".format(homography))
dst_hmg_pts = PointDetectionMatchRatio.transform_points(src_hmg_pts, homography)
# print("fip->dst_hmg_pts.shape={}".format(dst_hmg_pts.shape))
# print("fip->dst_hmg_pts={}".format(dst_hmg_pts[:10, :]))
mask = PointDetectionMatchRatio.calc_inside_pts_mask(dst_hmg_pts, dst_img_size)
# print("fip->mask={}".format(mask[:10]))
# print("fip->mask.sum()={}".format(mask.sum()))
return src_hmg_pts[mask], src_confs[mask]
@staticmethod
def filter_best_points(hmg_pts,
confs,
max_count,
min_conf=None):
if min_conf is not None:
max_ind = (confs < min_conf).nonzero()[0, 0].item()
max_count = max(max_count, max_ind)
inds = confs.argsort(descending=True)[:max_count]
return hmg_pts[inds], confs[inds][-1]
@staticmethod
def calc_pairwise_distances(x, y):
diff = x.unsqueeze(1) - y.unsqueeze(0)
return torch.sum(diff * diff, dim=-1).sqrt()
@staticmethod
def saturate_distance_matrix(dist_mat,
max_dist_thr,
max_dist_sat):
dist_mat[dist_mat > max_dist_thr] = max_dist_sat
class PointDescriptionMatchRatio(EvalMetric):
"""
Computes point description match ratio.
Parameters:
----------
pts_max_count : int
Maximal count of points.
dist_ratio_thr : float, default 0.9
Distance ratio threshold for point filtering.
axis : int, default 1
The axis that represents classes
name : str, default 'accuracy'
Name of this metric instance for display.
output_names : list of str, or None, default None
Name of predictions that should be used when updating with update_dict.
By default include all predictions.
label_names : list of str, or None, default None
Name of labels that should be used when updating with update_dict.
By default include all labels.
"""
def __init__(self,
pts_max_count,
dist_ratio_thr=0.95,
axis=1,
name="pt_desc_ratio",
output_names=None,
label_names=None):
super(PointDescriptionMatchRatio, self).__init__(
name,
axis=axis,
output_names=output_names,
label_names=label_names,
has_global_stats=True)
self.axis = axis
self.pts_max_count = pts_max_count
self.dist_ratio_thr = dist_ratio_thr
self.resudual_sum = 0.0
self.resudual_count = 0
def update_alt(self,
homography,
src_pts,
dst_pts,
src_descs,
dst_descs,
src_img_size,
dst_img_size):
"""
Updates the internal evaluation result.
Parameters:
----------
homography : torch.Tensor
Homography (from source image to destination one).
src_pts : torch.Tensor
Detected points for the first (source) image.
dst_pts : torch.Tensor
Detected points for the second (destination) image.
src_descs : torch.Tensor
Descriptors for detected points on the source image.
dst_descs : torch.Tensor
Descriptors for detected points on the destination image.
src_img_size : tuple of 2 int
Size (H, W) of the source image.
dst_img_size : tuple of 2 int
Size (H, W) of the destination image.
"""
# max_dist_sat_value = 1e5
# eps = 1e-5
homography = homography.to(src_pts.device)
self.normalize_homography(homography)
homography_inv = self.calc_homography_inv(homography)
src_pts = src_pts.flip(dims=(1,))
dst_pts = dst_pts.flip(dims=(1,))
src_hmg_pts = self.calc_homogeneous_coords(src_pts.float())
dst_hmg_pts = self.calc_homogeneous_coords(dst_pts.float())
src_hmg_pts = self.filter_inside_points(
src_hmg_pts,
homography,
dst_img_size)
dst_hmg_pts = self.filter_inside_points(
dst_hmg_pts,
homography_inv,
src_img_size)
src_pts_count = src_hmg_pts.shape[0]
dst_pts_count = dst_hmg_pts.shape[0]
src_pts_count2 = min(src_pts_count, self.pts_max_count * 10)
src_hmg_pts, src_descs = self.filter_best_points(
hmg_pts=src_hmg_pts,
descs=src_descs,
max_count=src_pts_count2)
dst_pts_count2 = min(dst_pts_count, self.pts_max_count * 10)
dst_hmg_pts, dst_descs = self.filter_best_points(
hmg_pts=dst_hmg_pts,
descs=dst_descs,
max_count=dst_pts_count2)
dist_mat = self.calc_pairwise_distances(x=src_descs, y=dst_descs)
vals, inds = dist_mat.topk(k=2, dim=1, largest=True, sorted=True)
inds = inds[:, 0][(vals[:, 1] / vals[:, 0]) < 0.95]
src_hmg_pts = src_hmg_pts[inds]
preds_dst_hmg_pts = self.transform_points(
src_hmg_pts,
homography)
print(preds_dst_hmg_pts)
# self.saturate_distance_matrix(
# dist_mat=cost,
# max_dist_thr=8.0,
# max_dist_sat=max_dist_sat_value)
#
# # print("cost.shape={}".format(cost.shape))
#
# from scipy.optimize import linear_sum_assignment
# row_ind, col_ind = linear_sum_assignment(cost)
#
# # print("row_ind.shape={}".format(row_ind.shape))
# # print("col_ind.shape={}".format(col_ind.shape))
#
# resuduals = cost[row_ind, col_ind]
# resuduals = resuduals[resuduals < (max_dist_sat_value - eps)]
# resudual_count = len(resuduals)
resudual_count = 1
self.sum_metric += resudual_count
self.global_sum_metric += resudual_count
self.num_inst += src_pts_count2
self.global_num_inst += src_pts_count2
print("ratio_resudual={}".format(float(resudual_count) / src_pts_count2))
@staticmethod
def normalize_homography(homography):
homography /= homography[2, 2]
@staticmethod
def calc_homography_inv(homography):
homography_inv = homography.inverse()
PointDetectionMatchRatio.normalize_homography(homography_inv)
return homography_inv
@staticmethod
def calc_homogeneous_coords(pts):
hmg_pts = torch.cat((pts, torch.ones((pts.shape[0], 1), dtype=pts.dtype, device=pts.device)), dim=1)
return hmg_pts
@staticmethod
def calc_cartesian_coords(hmg_pts):
pts = hmg_pts[:, :2]
return pts
@staticmethod
def transform_points(src_hmg_pts,
homography):
# print("transform_points -> src_hmg_pts.shape={}".format(src_hmg_pts.shape))
# print("transform_points -> homography.shape={}".format(homography.shape))
# print("homography={}".format(homography))
# print("transform_points -> src_hmg_pts={}".format(src_hmg_pts[:10, :].int()))
dst_hmg_pts = torch.matmul(src_hmg_pts, homography.t())
# print("transform_points -> dst_hmg_pts={}".format(dst_hmg_pts[:10, :].int()))
# print("transform_points -> dst_hmg_pts.shape={}".format(dst_hmg_pts.shape))
dst_hmg_pts /= dst_hmg_pts[:, 2:]
return dst_hmg_pts
@staticmethod
def calc_inside_pts_mask(pts,
img_size):
eps = 1e-3
border_size = 1.0
border = border_size - eps
mask = (pts[:, 0] >= border) & (pts[:, 0] < img_size[0] - border) &\
(pts[:, 1] >= border) & (pts[:, 1] < img_size[1] - border)
return mask
@staticmethod
def filter_inside_points(src_hmg_pts,
homography,
dst_img_size):
dst_hmg_pts = PointDetectionMatchRatio.transform_points(src_hmg_pts, homography)
mask = PointDetectionMatchRatio.calc_inside_pts_mask(dst_hmg_pts, dst_img_size)
return src_hmg_pts[mask]
@staticmethod
def filter_best_points(hmg_pts,
descs,
max_count):
return hmg_pts[:max_count], descs[:max_count]
@staticmethod
def calc_pairwise_distances(x, y):
diff = x.unsqueeze(1) - y.unsqueeze(0)
return torch.sum(diff * diff, dim=-1).sqrt()
@staticmethod
def saturate_distance_matrix(dist_mat,
max_dist_thr,
max_dist_sat):
dist_mat[dist_mat > max_dist_thr] = max_dist_sat
| 17,535 | 34.56998 | 113 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.