repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
imgclsmob
imgclsmob-master/chainer_/chainercv2/models/spnasnet.py
""" Single-Path NASNet for ImageNet-1K, implemented in Chainer. 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 import chainer.functions as F import chainer.links as L from chainer import Chain from functools import partial from chainer.serializers import load_npz from .common import conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv5x5_block, SimpleSequential class SPNASUnit(Chain): """ Single-Path NASNet unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int Stride 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. activation : str, default 'relu' Activation function or name of activation function. """ def __init__(self, in_channels, out_channels, stride, use_kernel3, exp_factor, use_skip=True, activation="relu"): super(SPNASUnit, self).__init__() assert (exp_factor >= 1) self.residual = (in_channels == out_channels) and (stride == 1) and use_skip self.use_exp_conv = exp_factor > 1 mid_channels = exp_factor * in_channels with self.init_scope(): if self.use_exp_conv: self.exp_conv = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, activation=activation) if use_kernel3: self.conv1 = dwconv3x3_block( in_channels=mid_channels, out_channels=mid_channels, stride=stride, activation=activation) else: self.conv1 = dwconv5x5_block( in_channels=mid_channels, out_channels=mid_channels, stride=stride, activation=activation) self.conv2 = conv1x1_block( in_channels=mid_channels, out_channels=out_channels, activation=None) def __call__(self, 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(Chain): """ 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. """ def __init__(self, in_channels, out_channels, mid_channels): super(SPNASInitBlock, self).__init__() with self.init_scope(): self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels, stride=2) self.conv2 = SPNASUnit( in_channels=mid_channels, out_channels=out_channels, stride=1, use_kernel3=True, exp_factor=1, use_skip=False) def __call__(self, x): x = self.conv1(x) x = self.conv2(x) return x class SPNASFinalBlock(Chain): """ 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. """ def __init__(self, in_channels, out_channels, mid_channels): super(SPNASFinalBlock, self).__init__() with self.init_scope(): self.conv1 = SPNASUnit( in_channels=in_channels, out_channels=mid_channels, stride=1, use_kernel3=True, exp_factor=6, use_skip=False) self.conv2 = conv1x1_block( in_channels=mid_channels, out_channels=out_channels) def __call__(self, x): x = self.conv1(x) x = self.conv2(x) return x class SPNASNet(Chain): """ 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. 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, in_channels=3, in_size=(224, 224), classes=1000): super(SPNASNet, self).__init__() self.in_size = in_size self.classes = classes with self.init_scope(): self.features = SimpleSequential() with self.features.init_scope(): setattr(self.features, "init_block", SPNASInitBlock( in_channels=in_channels, out_channels=init_block_channels[1], mid_channels=init_block_channels[0])) in_channels = init_block_channels[1] for i, channels_per_stage in enumerate(channels): stage = SimpleSequential() with stage.init_scope(): for j, out_channels in enumerate(channels_per_stage): stride = 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] setattr(stage, "unit{}".format(j + 1), SPNASUnit( in_channels=in_channels, out_channels=out_channels, stride=stride, use_kernel3=use_kernel3, exp_factor=exp_factor)) in_channels = out_channels setattr(self.features, "stage{}".format(i + 1), stage) setattr(self.features, "final_block", SPNASFinalBlock( in_channels=in_channels, out_channels=final_block_channels[1], mid_channels=final_block_channels[0])) in_channels = final_block_channels[1] setattr(self.features, "final_pool", partial( F.average_pooling_2d, ksize=7, stride=1)) self.output = SimpleSequential() with self.output.init_scope(): setattr(self.output, "flatten", partial( F.reshape, shape=(-1, in_channels))) setattr(self.output, "fc", L.Linear( in_size=in_channels, out_size=classes)) def __call__(self, x): x = self.features(x) x = self.output(x) return x def get_spnasnet(model_name=None, pretrained=False, root=os.path.join("~", ".chainer", "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. root : str, default '~/.chainer/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 load_npz( file=get_model_file( model_name=model_name, local_model_store_dir_path=root), obj=net) 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. root : str, default '~/.chainer/models' Location for keeping the model parameters. """ return get_spnasnet(model_name="spnasnet", **kwargs) def _test(): import numpy as np import chainer chainer.global_config.train = False pretrained = False models = [ spnasnet, ] for model in models: net = model(pretrained=pretrained) weight_count = net.count_params() print("m={}, {}".format(model.__name__, weight_count)) assert (model != spnasnet or weight_count == 4421616) x = np.zeros((1, 3, 224, 224), np.float32) y = net(x) assert (y.shape == (1, 1000)) if __name__ == "__main__": _test()
10,918
31.987915
115
py
imgclsmob
imgclsmob-master/chainer_/chainercv2/models/fastscnn.py
""" Fast-SCNN for image segmentation, implemented in Chainer. Original paper: 'Fast-SCNN: Fast Semantic Segmentation Network,' https://arxiv.org/abs/1902.04502. """ __all__ = ['FastSCNN', 'fastscnn_cityscapes'] import os import chainer.functions as F from chainer import Chain from functools import partial from chainer.serializers import load_npz from .common import conv1x1, conv1x1_block, conv3x3_block, dwconv3x3_block, dwsconv3x3_block, Concurrent,\ InterpolationBlock, SimpleSequential class Stem(Chain): """ Fast-SCNN specific stem block. Parameters: ---------- in_channels : int Number of input channels. channels : tuple/list of 3 int Number of output channels. """ def __init__(self, in_channels, channels, **kwargs): super(Stem, self).__init__(**kwargs) assert (len(channels) == 3) with self.init_scope(): self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=channels[0], stride=2, pad=0) self.conv2 = dwsconv3x3_block( in_channels=channels[0], out_channels=channels[1], stride=2) self.conv3 = dwsconv3x3_block( in_channels=channels[1], out_channels=channels[2], stride=2) def __call__(self, x): x = self.conv1(x) x = self.conv2(x) x = self.conv3(x) return x class LinearBottleneck(Chain): """ Fast-SCNN specific Linear Bottleneck layer from MobileNetV2. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int Stride of the second convolution layer. """ def __init__(self, in_channels, out_channels, stride, **kwargs): super(LinearBottleneck, self).__init__(**kwargs) self.residual = (in_channels == out_channels) and (stride == 1) mid_channels = in_channels * 6 with self.init_scope(): self.conv1 = conv1x1_block( in_channels=in_channels, out_channels=mid_channels) self.conv2 = dwconv3x3_block( in_channels=mid_channels, out_channels=mid_channels, stride=stride) self.conv3 = conv1x1_block( in_channels=mid_channels, out_channels=out_channels, activation=None) def __call__(self, 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(Chain): """ 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. """ def __init__(self, in_channels, channels, **kwargs): super(FeatureExtractor, self).__init__(**kwargs) with self.init_scope(): self.features = SimpleSequential() with self.features.init_scope(): for i, channels_per_stage in enumerate(channels): stage = SimpleSequential() with stage.init_scope(): for j, out_channels in enumerate(channels_per_stage): stride = 2 if (j == 0) and (i != len(channels) - 1) else 1 setattr(stage, "unit{}".format(j + 1), LinearBottleneck( in_channels=in_channels, out_channels=out_channels, stride=stride)) in_channels = out_channels setattr(self.features, "stage{}".format(i + 1), stage) def __call__(self, x): x = self.features(x) return x class PoolingBranch(Chain): """ 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. """ def __init__(self, in_channels, out_channels, in_size, down_size, **kwargs): super(PoolingBranch, self).__init__(**kwargs) self.in_size = in_size self.down_size = down_size with self.init_scope(): self.conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels) self.up = InterpolationBlock( scale_factor=None, out_size=in_size) def __call__(self, x): in_size = self.in_size if self.in_size is not None else x.shape[2:] x = F.average_pooling_2d(x, ksize=(in_size[0] // self.down_size, in_size[1] // self.down_size)) x = self.conv(x) x = self.up(x, in_size) return x class FastPyramidPooling(Chain): """ 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. """ def __init__(self, in_channels, out_channels, in_size, **kwargs): super(FastPyramidPooling, self).__init__(**kwargs) down_sizes = [1, 2, 3, 6] mid_channels = in_channels // 4 with self.init_scope(): self.branches = Concurrent() with self.branches.init_scope(): setattr(self.branches, "branch1", F.identity) for i, down_size in enumerate(down_sizes): setattr(self.branches, "branch{}".format(i + 2), PoolingBranch( in_channels=in_channels, out_channels=mid_channels, in_size=in_size, down_size=down_size)) self.conv = conv1x1_block( in_channels=(in_channels * 2), out_channels=out_channels) def __call__(self, x): x = self.branches(x) x = self.conv(x) return x class FeatureFusion(Chain): """ 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. """ def __init__(self, x_in_channels, y_in_channels, out_channels, x_in_size, **kwargs): super(FeatureFusion, self).__init__(**kwargs) self.x_in_size = x_in_size with self.init_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) self.low_pw_conv = conv1x1_block( in_channels=out_channels, out_channels=out_channels, use_bias=True, activation=None) self.high_conv = conv1x1_block( in_channels=x_in_channels, out_channels=out_channels, use_bias=True, activation=None) self.activ = F.relu def __call__(self, 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(Chain): """ Fast-SCNN head (classifier) block. Parameters: ---------- in_channels : int Number of input channels. classes : int Number of classification classes. """ def __init__(self, in_channels, classes): super(Head, self).__init__() with self.init_scope(): self.conv1 = dwsconv3x3_block( in_channels=in_channels, out_channels=in_channels) self.conv2 = dwsconv3x3_block( in_channels=in_channels, out_channels=in_channels) self.dropout = partial( F.dropout, ratio=0.1) self.conv3 = conv1x1( in_channels=in_channels, out_channels=classes, use_bias=True) def __call__(self, x): x = self.conv1(x) x = self.conv2(x) x = self.dropout(x) x = self.conv3(x) return x class AuxHead(Chain): """ 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. """ def __init__(self, in_channels, mid_channels, classes): super(AuxHead, self).__init__() with self.init_scope(): self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels) self.dropout = partial( F.dropout, ratio=0.1) self.conv2 = conv1x1( in_channels=mid_channels, out_channels=classes, use_bias=True) def __call__(self, x): x = self.conv1(x) x = self.dropout(x) x = self.conv2(x) return x class FastSCNN(Chain): """ 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. 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, 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.init_scope(): steam_channels = [32, 48, 64] self.stem = Stem( in_channels=in_channels, channels=steam_channels) 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) 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) 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) self.head = Head( in_channels=fusion_out_channels, classes=classes) 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) def __call__(self, 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, root=os.path.join("~", ".chainer", "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. root : str, default '~/.chainer/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 load_npz( file=get_model_file( model_name=model_name, local_model_store_dir_path=root), obj=net) 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. root : str, default '~/.chainer/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 chainer chainer.global_config.train = False in_size = (1024, 2048) aux = True fixed_size = False pretrained = False models = [ (fastscnn_cityscapes, 19), ] for model, classes in models: net = model(pretrained=pretrained, in_size=in_size, fixed_size=fixed_size, aux=aux) weight_count = net.count_params() 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 = np.zeros((1, 3, in_size[0], in_size[1]), np.float32) 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()
16,053
29.992278
115
py
imgclsmob
imgclsmob-master/chainer_/chainercv2/models/darknet.py
""" DarkNet for ImageNet-1K, implemented in Chainer. Original source: 'Darknet: Open source neural networks in c,' https://github.com/pjreddie/darknet. """ __all__ = ['DarkNet', 'darknet_ref', 'darknet_tiny', 'darknet19'] import os import chainer.functions as F import chainer.links as L from chainer import Chain from functools import partial from chainer.serializers import load_npz from .common import conv1x1_block, conv3x3_block, SimpleSequential def dark_convYxY(in_channels, out_channels, alpha, pointwise): """ DarkNet unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. 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, activation=partial( F.leaky_relu, slope=alpha)) else: return conv3x3_block( in_channels=in_channels, out_channels=out_channels, activation=partial( F.leaky_relu, slope=alpha)) class DarkNet(Chain): """ 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. 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, in_channels=3, in_size=(224, 224), classes=1000): super(DarkNet, self).__init__() self.in_size = in_size self.classes = classes with self.init_scope(): self.features = SimpleSequential() with self.features.init_scope(): for i, channels_per_stage in enumerate(channels): stage = SimpleSequential() with stage.init_scope(): for j, out_channels in enumerate(channels_per_stage): setattr(stage, "unit{}".format(j + 1), dark_convYxY( in_channels=in_channels, out_channels=out_channels, 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: setattr(stage, "pool{}".format(i + 1), partial( F.max_pooling_2d, ksize=2, stride=2, cover_all=False)) setattr(self.features, "stage{}".format(i + 1), stage) self.output = SimpleSequential() with self.output.init_scope(): setattr(self.output, "final_conv", L.Convolution2D( in_channels=in_channels, out_channels=classes, ksize=1)) if cls_activ: setattr(self.output, "final_activ", partial( F.leaky_relu, slope=alpha)) setattr(self.output, "final_pool", partial( F.average_pooling_2d, ksize=avg_pool_size, stride=1)) setattr(self.output, "final_flatten", partial( F.reshape, shape=(-1, classes))) def __call__(self, x): x = self.features(x) x = self.output(x) return x def get_darknet(version, model_name=None, pretrained=False, root=os.path.join("~", ".chainer", "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. root : str, default '~/.chainer/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 load_npz( file=get_model_file( model_name=model_name, local_model_store_dir_path=root), obj=net) 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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/models' Location for keeping the model parameters. """ return get_darknet(version="19", model_name="darknet19", **kwargs) def _test(): import numpy as np import chainer chainer.global_config.train = False pretrained = False models = [ darknet_ref, darknet_tiny, darknet19, ] for model in models: net = model(pretrained=pretrained) weight_count = net.count_params() 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 = np.zeros((1, 3, 224, 224), np.float32) y = net(x) assert (y.shape == (1, 1000)) if __name__ == "__main__": _test()
8,597
31.692015
117
py
imgclsmob
imgclsmob-master/chainer_/chainercv2/models/ror_cifar.py
""" RoR-3 for CIFAR/SVHN, implemented in Chainer. 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 import chainer.functions as F import chainer.links as L from chainer import Chain from functools import partial from chainer.serializers import load_npz from .common import conv1x1_block, conv3x3_block, SimpleSequential class RoRBlock(Chain): """ RoR-3 block for residual path in residual unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. dropout_rate : float Parameter of Dropout layer. Faction of the input units to drop. """ def __init__(self, in_channels, out_channels, dropout_rate): super(RoRBlock, self).__init__() self.use_dropout = (dropout_rate != 0.0) with self.init_scope(): self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=out_channels) self.conv2 = conv3x3_block( in_channels=out_channels, out_channels=out_channels, activation=None) if self.use_dropout: self.dropout = partial( F.dropout, ratio=dropout_rate) def __call__(self, x): x = self.conv1(x) if self.use_dropout: x = self.dropout(x) x = self.conv2(x) return x class RoRResUnit(Chain): """ RoR-3 residual unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. 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, dropout_rate, last_activate=True): super(RoRResUnit, self).__init__() self.last_activate = last_activate self.resize_identity = (in_channels != out_channels) with self.init_scope(): self.body = RoRBlock( in_channels=in_channels, out_channels=out_channels, dropout_rate=dropout_rate) if self.resize_identity: self.identity_conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, activation=None) self.activ = F.relu def __call__(self, 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(Chain): """ 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. 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, dropout_rate, downsample=True): super(RoRResStage, self).__init__() self.downsample = downsample with self.init_scope(): self.shortcut = conv1x1_block( in_channels=in_channels, out_channels=out_channels_list[-1], activation=None) self.units = SimpleSequential() with self.units.init_scope(): for i, out_channels in enumerate(out_channels_list): last_activate = (i != len(out_channels_list) - 1) setattr(self.units, "unit{}".format(i + 1), RoRResUnit( in_channels=in_channels, out_channels=out_channels, dropout_rate=dropout_rate, last_activate=last_activate)) in_channels = out_channels if self.downsample: self.activ = F.relu self.pool = partial( F.max_pooling_2d, ksize=2, stride=2, pad=0) def __call__(self, 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(Chain): """ 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. dropout_rate : float Parameter of Dropout layer. Faction of the input units to drop. """ def __init__(self, in_channels, out_channels_lists, dropout_rate): super(RoRResBody, self).__init__() with self.init_scope(): self.shortcut = conv1x1_block( in_channels=in_channels, out_channels=out_channels_lists[-1][-1], stride=4, activation=None) self.stages = SimpleSequential() with self.stages.init_scope(): for i, channels_per_stage in enumerate(out_channels_lists): downsample = (i != len(out_channels_lists) - 1) setattr(self.stages, "stage{}".format(i + 1), RoRResStage( in_channels=in_channels, out_channels_list=channels_per_stage, dropout_rate=dropout_rate, downsample=downsample)) in_channels = channels_per_stage[-1] self.activ = F.relu def __call__(self, x): identity = self.shortcut(x) x = self.stages(x) x = x + identity x = self.activ(x) return x class CIFARRoR(Chain): """ 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. 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, dropout_rate=0.0, in_channels=3, in_size=(32, 32), classes=10): super(CIFARRoR, self).__init__() self.in_size = in_size self.classes = classes with self.init_scope(): self.features = SimpleSequential() with self.features.init_scope(): setattr(self.features, "init_block", conv3x3_block( in_channels=in_channels, out_channels=init_block_channels)) in_channels = init_block_channels setattr(self.features, "body", RoRResBody( in_channels=in_channels, out_channels_lists=channels, dropout_rate=dropout_rate)) in_channels = channels[-1][-1] setattr(self.features, "final_pool", partial( F.average_pooling_2d, ksize=8, stride=1)) self.output = SimpleSequential() with self.output.init_scope(): setattr(self.output, "flatten", partial( F.reshape, shape=(-1, in_channels))) setattr(self.output, "fc", L.Linear( in_size=in_channels, out_size=classes)) def __call__(self, x): x = self.features(x) x = self.output(x) return x def get_ror_cifar(classes, blocks, model_name=None, pretrained=False, root=os.path.join("~", ".chainer", "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. root : str, default '~/.chainer/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 load_npz( file=get_model_file( model_name=model_name, local_model_store_dir_path=root), obj=net) 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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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 chainer chainer.global_config.train = False 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) weight_count = net.count_params() 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 = np.zeros((1, 3, 32, 32), np.float32) y = net(x) assert (y.shape == (1, classes)) if __name__ == "__main__": _test()
17,097
32.071567
118
py
imgclsmob
imgclsmob-master/chainer_/chainercv2/models/dicenet.py
""" DiCENet for ImageNet-1K, implemented in Chainer. 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 import chainer.functions as F import chainer.links as L from chainer import Chain from functools import partial from chainer.serializers import load_npz from .common import conv1x1, conv3x3, conv1x1_block, conv3x3_block, NormActivation, ChannelShuffle, Concurrent,\ SimpleSequential class SpatialDiceBranch(Chain): """ 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. """ def __init__(self, sp_size, is_height, **kwargs): super(SpatialDiceBranch, self).__init__(**kwargs) self.is_height = is_height self.index = 2 if is_height else 3 self.base_sp_size = sp_size with self.init_scope(): self.conv = conv3x3( in_channels=self.base_sp_size, out_channels=self.base_sp_size, groups=self.base_sp_size) def __call__(self, x): 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.resize_images(x, output_shape=base_in_size, mode="bilinear", align_corners=True) else: # ksize = (real_in_size[0] // base_in_size[0], real_in_size[1] // base_in_size[1]) # x = F.average_pooling_2d(x, ksize=ksize) x = F.resize_images(x, output_shape=base_in_size, mode="bilinear", align_corners=True) x = F.swapaxes(x, axis1=1, axis2=self.index) x = self.conv(x) x = F.swapaxes(x, axis1=1, axis2=self.index) changed_sp_size = x.shape[self.index] if real_sp_size != changed_sp_size: if changed_sp_size < real_sp_size: x = F.resize_images(x, output_shape=real_in_size, mode="bilinear", align_corners=True) else: # ksize = (x.shape[2] // real_in_size[0], x.shape[3] // real_in_size[1]) # x = F.average_pooling_2d(x, ksize=ksize) x = F.resize_images(x, output_shape=real_in_size, mode="bilinear", align_corners=True) return x class DiceBaseBlock(Chain): """ 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. """ def __init__(self, channels, in_size, **kwargs): super(DiceBaseBlock, self).__init__(**kwargs) mid_channels = 3 * channels with self.init_scope(): self.convs = Concurrent() with self.convs.init_scope(): setattr(self.convs, "ch_conv", conv3x3( in_channels=channels, out_channels=channels, groups=channels)) setattr(self.convs, "h_conv", SpatialDiceBranch( sp_size=in_size[0], is_height=True)) setattr(self.convs, "w_conv", SpatialDiceBranch( sp_size=in_size[1], is_height=False)) self.norm_activ = NormActivation( in_channels=mid_channels, activation=(lambda: L.PReLU(shape=(mid_channels,)))) self.shuffle = ChannelShuffle( channels=mid_channels, groups=3) self.squeeze_conv = conv1x1_block( in_channels=mid_channels, out_channels=channels, groups=channels, activation=(lambda: L.PReLU(shape=(channels,)))) def __call__(self, x): x = self.convs(x) x = self.norm_activ(x) x = self.shuffle(x) x = self.squeeze_conv(x) return x class DiceAttBlock(Chain): """ 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.init_scope(): self.conv1 = conv1x1( in_channels=in_channels, out_channels=mid_channels, use_bias=False) self.activ = F.relu self.conv2 = conv1x1( in_channels=mid_channels, out_channels=out_channels, use_bias=False) self.sigmoid = F.sigmoid def __call__(self, x): w = F.average_pooling_2d(x, ksize=x.shape[2:]) w = self.conv1(w) w = self.activ(w) w = self.conv2(w) w = self.sigmoid(w) return w class DiceBlock(Chain): """ 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. """ def __init__(self, in_channels, out_channels, in_size, **kwargs): super(DiceBlock, self).__init__(**kwargs) proj_groups = math.gcd(in_channels, out_channels) with self.init_scope(): self.base_block = DiceBaseBlock( channels=in_channels, in_size=in_size) self.att = DiceAttBlock( in_channels=in_channels, out_channels=out_channels) self.proj_conv = conv3x3_block( in_channels=in_channels, out_channels=out_channels, groups=proj_groups, activation=(lambda: L.PReLU(shape=(out_channels,)))) def __call__(self, x): x = self.base_block(x) w = self.att(x) x = self.proj_conv(x) x = x * w return x class StridedDiceLeftBranch(Chain): """ Left branch of the strided DiCE block. Parameters: ---------- channels : int Number of input/output channels. """ def __init__(self, channels, **kwargs): super(StridedDiceLeftBranch, self).__init__(**kwargs) with self.init_scope(): self.conv1 = conv3x3_block( in_channels=channels, out_channels=channels, stride=2, groups=channels, activation=(lambda: L.PReLU(shape=(channels,)))) self.conv2 = conv1x1_block( in_channels=channels, out_channels=channels, activation=(lambda: L.PReLU(shape=(channels,)))) def __call__(self, x): x = self.conv1(x) x = self.conv2(x) return x class StridedDiceRightBranch(Chain): """ 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. """ def __init__(self, channels, in_size, **kwargs): super(StridedDiceRightBranch, self).__init__(**kwargs) with self.init_scope(): self.pool = partial( F.average_pooling_nd, ksize=3, stride=2, pad=1) self.dice = DiceBlock( in_channels=channels, out_channels=channels, in_size=(in_size[0] // 2, in_size[1] // 2)) self.conv = conv1x1_block( in_channels=channels, out_channels=channels, activation=(lambda: L.PReLU(shape=(channels,)))) def __call__(self, x): x = self.pool(x) x = self.dice(x) x = self.conv(x) return x class StridedDiceBlock(Chain): """ 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. """ def __init__(self, in_channels, out_channels, in_size, **kwargs): super(StridedDiceBlock, self).__init__(**kwargs) assert (out_channels == 2 * in_channels) with self.init_scope(): self.branches = Concurrent() with self.branches.init_scope(): setattr(self.branches, "left_branch", StridedDiceLeftBranch(channels=in_channels)) setattr(self.branches, "right_branch", StridedDiceRightBranch( channels=in_channels, in_size=in_size)) self.shuffle = ChannelShuffle( channels=out_channels, groups=2) def __call__(self, x): x = self.branches(x) x = self.shuffle(x) return x class ShuffledDiceRightBranch(Chain): """ 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. """ def __init__(self, in_channels, out_channels, in_size, **kwargs): super(ShuffledDiceRightBranch, self).__init__(**kwargs) with self.init_scope(): self.conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, activation=(lambda: L.PReLU(shape=(out_channels,)))) self.dice = DiceBlock( in_channels=out_channels, out_channels=out_channels, in_size=in_size) def __call__(self, x): x = self.conv(x) x = self.dice(x) return x class ShuffledDiceBlock(Chain): """ 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. """ def __init__(self, in_channels, out_channels, in_size, **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.init_scope(): self.right_branch = ShuffledDiceRightBranch( in_channels=right_in_channels, out_channels=right_out_channels, in_size=in_size) self.shuffle = ChannelShuffle( channels=(2 * right_out_channels), groups=2) def __call__(self, x): x1, x2 = F.split_axis(x, indices_or_sections=2, axis=1) x2 = self.right_branch(x2) x = F.concat((x1, x2), axis=1) x = self.shuffle(x) return x class DiceInitBlock(Chain): """ DiceNet 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(DiceInitBlock, self).__init__(**kwargs) with self.init_scope(): self.conv = conv3x3_block( in_channels=in_channels, out_channels=out_channels, stride=2, activation=(lambda: L.PReLU(shape=(out_channels,)))) self.pool = partial( F.max_pooling_2d, ksize=3, stride=2, pad=1, cover_all=False) def __call__(self, x): x = self.conv(x) x = self.pool(x) return x class DiceClassifier(Chain): """ 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.init_scope(): self.conv1 = conv1x1( in_channels=in_channels, out_channels=mid_channels, groups=4) self.dropout = partial( F.dropout, ratio=dropout_rate) self.conv2 = conv1x1( in_channels=mid_channels, out_channels=classes, use_bias=True) def __call__(self, x): x = self.conv1(x) x = self.dropout(x) x = self.conv2(x) return x class DiceNet(Chain): """ 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. 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, 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.init_scope(): self.features = SimpleSequential() with self.features.init_scope(): setattr(self.features, "init_block", DiceInitBlock( in_channels=in_channels, out_channels=init_block_channels)) in_channels = init_block_channels in_size = (in_size[0] // 4, in_size[1] // 4) for i, channels_per_stage in enumerate(channels): stage = SimpleSequential() with stage.init_scope(): for j, out_channels in enumerate(channels_per_stage): unit_class = StridedDiceBlock if j == 0 else ShuffledDiceBlock setattr(stage, "unit{}".format(j + 1), unit_class( in_channels=in_channels, out_channels=out_channels, in_size=in_size)) in_channels = out_channels in_size = (in_size[0] // 2, in_size[1] // 2) if j == 0 else in_size setattr(self.features, "stage{}".format(i + 1), stage) setattr(self.features, "final_pool", partial( F.average_pooling_2d, ksize=in_size)) self.output = SimpleSequential() with self.output.init_scope(): setattr(self.output, "classifier", DiceClassifier( in_channels=in_channels, mid_channels=classifier_mid_channels, classes=classes, dropout_rate=dropout_rate)) setattr(self.output, "final_flatten", partial( F.reshape, shape=(-1, classes))) def __call__(self, x): x = self.features(x) x = self.output(x) return x def get_dicenet(width_scale, model_name=None, pretrained=False, root=os.path.join("~", ".chainer", "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. root : str, default '~/.chainer/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 load_npz( file=get_model_file( model_name=model_name, local_model_store_dir_path=root), obj=net) 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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/models' Location for keeping the model parameters. """ return get_dicenet(width_scale=2.0, model_name="dicenet_w2", **kwargs) def _test(): import numpy as np import chainer chainer.global_config.train = False pretrained = False 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) weight_count = net.count_params() 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 = np.zeros((1, 3, 224, 224), np.float32) y = net(x) assert (y.shape == (1, 1000)) if __name__ == "__main__": _test()
24,993
30.678074
119
py
imgclsmob
imgclsmob-master/chainer_/chainercv2/models/nvpattexp.py
""" Neural Voice Puppetry Audio-to-Expression net for speech-driven facial animation, implemented in Chainer. Original paper: 'Neural Voice Puppetry: Audio-driven Facial Reenactment,' https://arxiv.org/abs/1912.05566. """ __all__ = ['NvpAttExp', 'nvpattexp116bazel76'] import os from functools import partial import chainer.functions as F from chainer import Chain from chainer.serializers import load_npz from .common import DenseBlock, ConvBlock, ConvBlock1d, SelectableDense, SimpleSequential class NvpAttExpEncoder(Chain): """ 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.init_scope(): in_channels = audio_features self.conv_branch = SimpleSequential() with self.conv_branch.init_scope(): for i, (out_channels, slope) in enumerate(zip(conv_channels, conv_slopes)): setattr(self.conv_branch, "conv{}".format(i + 1), ConvBlock( in_channels=in_channels, out_channels=out_channels, ksize=(3, 1), stride=(2, 1), pad=(1, 0), use_bias=True, use_bn=False, activation=partial(F.leaky_relu, slope=slope))) in_channels = out_channels self.fc_branch = SimpleSequential() with self.fc_branch.init_scope(): for i, (out_channels, slope) in enumerate(zip(fc_channels, fc_slopes)): activation = partial(F.leaky_relu, slope=slope) if slope is not None else partial(F.tanh) setattr(self.fc_branch, "fc{}".format(i + 1), 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 = SimpleSequential() with self.att_conv_branch.init_scope(): for i, out_channels, in enumerate(att_conv_channels): setattr(self.att_conv_branch, "att_conv{}".format(i + 1), ConvBlock1d( in_channels=in_channels, out_channels=out_channels, ksize=3, stride=1, pad=1, use_bias=True, use_bn=False, activation=partial(F.leaky_relu, slope=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=partial(F.softmax, axis=1)) def __call__(self, x): batch = x.shape[0] batch_seq_len = batch * self.seq_len x = F.reshape(x, shape=(batch_seq_len, 1, self.audio_window_size, self.audio_features)) x = F.swapaxes(x, axis1=1, axis2=3) x = self.conv_branch(x) x = F.reshape(x, shape=(batch_seq_len, 1, -1)) x = self.fc_branch(x) x = F.reshape(x, shape=(batch, self.seq_len, -1)) x = F.swapaxes(x, axis1=1, axis2=2) y = x[:, :, (self.seq_len // 2)] w = self.att_conv_branch(x) w = F.reshape(w, shape=(batch, self.seq_len)) w = self.att_fc(w) w = F.expand_dims(w, axis=-1) x = F.batch_matmul(x, w) x = F.squeeze(x, axis=-1) return x, y class NvpAttExp(Chain): """ 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.init_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 __call__(self, 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, root=os.path.join("~", ".chainer", "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. root : str, default '~/.chainer/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 load_npz( file=get_model_file( model_name=model_name, local_model_store_dir_path=root), obj=net) 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. root : str, default '~/.chainer/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 chainer chainer.global_config.train = False pretrained = False models = [ nvpattexp116bazel76, ] for model in models: net = model(pretrained=pretrained) weight_count = net.count_params() 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 = np.random.rand(batch, seq_len, audio_window_size, audio_features).astype(np.float32) pid = np.full(shape=(batch,), fill_value=3, dtype=np.int64) y1, y2 = net(x, pid) assert (y1.shape == y2.shape == (batch, blendshapes)) if __name__ == "__main__": _test()
9,004
33.76834
116
py
imgclsmob
imgclsmob-master/chainer_/chainercv2/models/octresnet.py
""" Oct-ResNet for ImageNet-1K, implemented in Chainer. 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 import chainer.functions as F import chainer.links as L from chainer import Chain from functools import partial from chainer.serializers import load_npz from .common import ReLU6, DualPathSequential, SimpleSequential from .resnet import ResInitBlock class OctConvolution2D(L.Convolution2D): """ Octave convolution layer. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. ksize : int or tuple/list of 2 int Convolution window size. stride : int or tuple/list of 2 int Stride of the convolution. pad : int or tuple/list of 2 int, default 1 Padding value for convolution layer. dilate : 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, ksize, stride, pad=1, dilate=1, groups=1, use_bias=False, oct_alpha=0.0, oct_mode="std", oct_value=2): if isinstance(stride, int): stride = (stride, stride) self.downsample = (stride[0] > 1) or (stride[1] > 1) assert (stride[0] in [1, oct_value]) and (stride[1] in [1, oct_value]) stride = (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(OctConvolution2D, self).__init__( in_channels=in_channels, out_channels=out_channels, ksize=ksize, stride=stride, pad=pad, dilate=dilate, groups=groups, nobias=(not use_bias)) self.conv_kwargs = { "stride": stride, "pad": pad, "dilate": dilate, "groups": groups} def forward(self, hx, lx=None): if self.oct_mode == "std": return F.convolution_2d( x=hx, W=self.W, b=self.b, **self.conv_kwargs), None if self.downsample: hx = F.average_pooling_2d( x=hx, ksize=(self.oct_value, self.oct_value), stride=(self.oct_value, self.oct_value)) hhy = F.convolution_2d( x=hx, W=self.W[0:self.h_out_channels, 0:self.h_in_channels, :, :], b=self.b[0:self.h_out_channels] if self.b is not None else None, **self.conv_kwargs) if self.oct_mode != "first": hlx = F.convolution_2d( x=lx, W=self.W[0:self.h_out_channels, self.h_in_channels:, :, :], b=self.b[0:self.h_out_channels] if self.b is not None else None, **self.conv_kwargs) if self.oct_mode == "last": hy = hhy + hlx ly = None return hy, ly lhx = F.average_pooling_2d( x=hx, ksize=(self.oct_value, self.oct_value), stride=(self.oct_value, self.oct_value)) lhy = F.convolution_2d( x=lhx, W=self.W[self.h_out_channels:, 0:self.h_in_channels, :, :], b=self.b[self.h_out_channels:] if self.b is not None else None, **self.conv_kwargs) if self.oct_mode == "first": hy = hhy ly = lhy return hy, ly if self.downsample: hly = hlx llx = F.average_pooling_2d( x=lx, ksize=(self.oct_value, self.oct_value), stride=(self.oct_value, self.oct_value)) else: hly = F.unpooling_2d( x=hlx, ksize=self.oct_value, cover_all=False) llx = lx lly = F.convolution_2d( x=llx, W=self.W[self.h_out_channels:, self.h_in_channels:, :, :], b=self.b[self.h_out_channels:] if self.b is not None else None, **self.conv_kwargs) hy = hhy + hly ly = lhy + lly return hy, ly class OctConvBlock(Chain): """ 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. ksize : int or tuple/list of 2 int Convolution window size. stride : int or tuple/list of 2 int Stride of the convolution. pad : int or tuple/list of 2 int Padding value for convolution layer. dilate : 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_eps : float, default 1e-5 Small float added to variance in Batch norm. activation : function or str or None, default F.activate Activation function or name of activation function. activate : bool, default True Whether activate the convolution block. """ def __init__(self, in_channels, out_channels, ksize, stride, pad, dilate=1, groups=1, use_bias=False, oct_alpha=0.0, oct_mode="std", bn_eps=1e-5, activation=(lambda: F.relu), activate=True): super(OctConvBlock, self).__init__() 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.init_scope(): self.conv = OctConvolution2D( in_channels=in_channels, out_channels=out_channels, ksize=ksize, stride=stride, pad=pad, dilate=dilate, groups=groups, use_bias=use_bias, oct_alpha=oct_alpha, oct_mode=oct_mode) self.h_bn = L.BatchNormalization( size=h_out_channels, eps=bn_eps) if not self.last: self.l_bn = L.BatchNormalization( size=l_out_channels, eps=bn_eps) if self.activate: assert (activation is not None) if isfunction(activation): self.activ = activation() elif isinstance(activation, str): if activation == "relu": self.activ = F.relu elif activation == "relu6": self.activ = ReLU6() else: raise NotImplementedError() else: self.activ = activation def __call__(self, 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, stride=1, groups=1, use_bias=False, oct_alpha=0.0, oct_mode="std", bn_eps=1e-5, activation=(lambda: F.relu), activate=True): """ 1x1 version of the octave convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int, default 1 Stride 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_eps : float, default 1e-5 Small float added to variance in Batch norm. activation : function or str or None, default F.activate 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, ksize=1, stride=stride, pad=0, groups=groups, use_bias=use_bias, oct_alpha=oct_alpha, oct_mode=oct_mode, bn_eps=bn_eps, activation=activation, activate=activate) def oct_conv3x3_block(in_channels, out_channels, stride=1, padding=1, dilation=1, groups=1, use_bias=False, oct_alpha=0.0, oct_mode="std", bn_eps=1e-5, activation=(lambda: F.relu), activate=True): """ 3x3 version of the octave convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int, default 1 Stride 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_eps : float, default 1e-5 Small float added to variance in Batch norm. activation : function or str or None, default F.activate 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, ksize=3, stride=stride, pad=padding, dilate=dilation, groups=groups, use_bias=use_bias, oct_alpha=oct_alpha, oct_mode=oct_mode, bn_eps=bn_eps, activation=activation, activate=activate) class OctResBlock(Chain): """ 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. stride : int or tuple/list of 2 int Stride 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'. """ def __init__(self, in_channels, out_channels, stride, oct_alpha=0.0, oct_mode="std"): super(OctResBlock, self).__init__() with self.init_scope(): self.conv1 = oct_conv3x3_block( in_channels=in_channels, out_channels=out_channels, stride=stride, oct_alpha=oct_alpha, oct_mode=oct_mode) 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")), activation=None, activate=False) def __call__(self, hx, lx=None): hx, lx = self.conv1(hx, lx) hx, lx = self.conv2(hx, lx) return hx, lx class OctResBottleneck(Chain): """ 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. stride : int or tuple/list of 2 int Stride 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'. 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, stride, padding=1, dilation=1, oct_alpha=0.0, oct_mode="std", conv1_stride=False, bottleneck_factor=4): super(OctResBottleneck, self).__init__() mid_channels = out_channels // bottleneck_factor with self.init_scope(): self.conv1 = oct_conv1x1_block( in_channels=in_channels, out_channels=mid_channels, stride=(stride if conv1_stride else 1), oct_alpha=oct_alpha, oct_mode=(oct_mode if oct_mode != "last" else "norm")) self.conv2 = oct_conv3x3_block( in_channels=mid_channels, out_channels=mid_channels, stride=(1 if conv1_stride else stride), padding=padding, dilation=dilation, oct_alpha=oct_alpha, oct_mode=(oct_mode if oct_mode != "first" else "norm")) 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")), activation=None, activate=False) def __call__(self, 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(Chain): """ Oct-ResNet unit with residual connection. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int Stride 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'. 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, stride, padding=1, dilation=1, oct_alpha=0.0, oct_mode="std", bottleneck=True, conv1_stride=False): super(OctResUnit, self).__init__() self.resize_identity = (in_channels != out_channels) or (stride != 1) or \ ((oct_mode == "first") and (oct_alpha != 0.0)) with self.init_scope(): if bottleneck: self.body = OctResBottleneck( in_channels=in_channels, out_channels=out_channels, stride=stride, padding=padding, dilation=dilation, oct_alpha=oct_alpha, oct_mode=oct_mode, conv1_stride=conv1_stride) else: self.body = OctResBlock( in_channels=in_channels, out_channels=out_channels, stride=stride, oct_alpha=oct_alpha, oct_mode=oct_mode) if self.resize_identity: self.identity_conv = oct_conv1x1_block( in_channels=in_channels, out_channels=out_channels, stride=stride, oct_alpha=oct_alpha, oct_mode=oct_mode, activation=None, activate=False) self.activ = F.relu def __call__(self, 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(Chain): """ 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. 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, in_channels=3, in_size=(224, 224), classes=1000): super(OctResNet, self).__init__() self.in_size = in_size self.classes = classes with self.init_scope(): self.features = DualPathSequential( return_two=False, first_ordinals=1, last_ordinals=1) with self.features.init_scope(): setattr(self.features, "init_block", ResInitBlock( in_channels=in_channels, out_channels=init_block_channels)) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = DualPathSequential() with stage.init_scope(): for j, out_channels in enumerate(channels_per_stage): stride = 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" setattr(stage, "unit{}".format(j + 1), OctResUnit( in_channels=in_channels, out_channels=out_channels, stride=stride, oct_alpha=oct_alpha, oct_mode=oct_mode, bottleneck=bottleneck, conv1_stride=conv1_stride)) in_channels = out_channels setattr(self.features, "stage{}".format(i + 1), stage) setattr(self.features, "final_pool", partial( F.average_pooling_2d, ksize=7, stride=1)) self.output = SimpleSequential() with self.output.init_scope(): setattr(self.output, "flatten", partial( F.reshape, shape=(-1, in_channels))) setattr(self.output, "fc", L.Linear( in_size=in_channels, out_size=classes)) def __call__(self, 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, root=os.path.join("~", ".chainer", "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. root : str, default '~/.chainer/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 load_npz( file=get_model_file( model_name=model_name, local_model_store_dir_path=root), obj=net) 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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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 chainer chainer.global_config.train = False pretrained = False models = [ octresnet10_ad2, octresnet50b_ad2, ] for model in models: net = model(pretrained=pretrained) weight_count = net.count_params() print("m={}, {}".format(model.__name__, weight_count)) assert (model != octresnet10_ad2 or weight_count == 5423016) assert (model != octresnet50b_ad2 or weight_count == 25557032) x = np.zeros((14, 3, 224, 224), np.float32) y = net(x) assert (y.shape == (14, 1000)) if __name__ == "__main__": _test()
28,431
33.379686
119
py
imgclsmob
imgclsmob-master/chainer_/chainercv2/models/alexnet.py
""" AlexNet for ImageNet-1K, implemented in Chainer. Original paper: 'One weird trick for parallelizing convolutional neural networks,' https://arxiv.org/abs/1404.5997. """ __all__ = ['AlexNet', 'alexnet', 'alexnetb'] import os import chainer.functions as F import chainer.links as L from chainer import Chain from functools import partial from chainer.serializers import load_npz from .common import ConvBlock, SimpleSequential class AlexConv(ConvBlock): """ AlexNet specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. ksize : int or tuple/list of 2 int Convolution window size. stride : int or tuple/list of 2 int Stride of the convolution. pad : 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, ksize, stride, pad, use_lrn): super(AlexConv, self).__init__( in_channels=in_channels, out_channels=out_channels, ksize=ksize, stride=stride, pad=pad, use_bias=True, use_bn=False) self.use_lrn = use_lrn def __call__(self, x): x = super(AlexConv, self).__call__(x) if self.use_lrn: x = F.local_response_normalization(x) return x class AlexDense(Chain): """ 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): super(AlexDense, self).__init__() with self.init_scope(): self.fc = L.Linear( in_size=in_channels, out_size=out_channels) self.activ = F.relu self.dropout = partial( F.dropout, ratio=0.5) def __call__(self, x): x = self.fc(x) x = self.activ(x) x = self.dropout(x) return x class AlexOutputBlock(Chain): """ AlexNet specific output block. Parameters: ---------- in_channels : int Number of input channels. classes : int Number of classification classes. """ def __init__(self, in_channels, classes): super(AlexOutputBlock, self).__init__() mid_channels = 4096 with self.init_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 = L.Linear( in_size=mid_channels, out_size=classes) def __call__(self, x): x = self.fc1(x) x = self.fc2(x) x = self.fc3(x) return x class AlexNet(Chain): """ 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. ksizes : 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. pads : 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, ksizes, strides, pads, use_lrn, in_channels=3, in_size=(224, 224), classes=1000): super(AlexNet, self).__init__() self.in_size = in_size self.classes = classes with self.init_scope(): self.features = SimpleSequential() with self.features.init_scope(): for i, channels_per_stage in enumerate(channels): use_lrn_i = use_lrn and (i in [0, 1]) stage = SimpleSequential() with stage.init_scope(): for j, out_channels in enumerate(channels_per_stage): setattr(stage, "unit{}".format(j + 1), AlexConv( in_channels=in_channels, out_channels=out_channels, ksize=ksizes[i][j], stride=strides[i][j], pad=pads[i][j], use_lrn=use_lrn_i)) in_channels = out_channels setattr(stage, "pool{}".format(i + 1), partial( F.max_pooling_2d, ksize=3, stride=2, pad=0)) setattr(self.features, "stage{}".format(i + 1), stage) in_channels = in_channels * 6 * 6 self.output = SimpleSequential() with self.output.init_scope(): setattr(self.output, "flatten", partial( F.reshape, shape=(-1, in_channels))) setattr(self.output, "classifier", AlexOutputBlock( in_channels=in_channels, classes=classes)) def __call__(self, x): x = self.features(x) x = self.output(x) return x def get_alexnet(version="a", model_name=None, pretrained=False, root=os.path.join("~", ".chainer", "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. root : str, default '~/.chainer/models' Location for keeping the model parameters. """ if version == "a": channels = [[96], [256], [384, 384, 256]] ksizes = [[11], [5], [3, 3, 3]] strides = [[4], [1], [1, 1, 1]] pads = [[0], [2], [1, 1, 1]] use_lrn = True elif version == "b": channels = [[64], [192], [384, 256, 256]] ksizes = [[11], [5], [3, 3, 3]] strides = [[4], [1], [1, 1, 1]] pads = [[2], [2], [1, 1, 1]] use_lrn = False else: raise ValueError("Unsupported AlexNet version {}".format(version)) net = AlexNet( channels=channels, ksizes=ksizes, strides=strides, pads=pads, 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 load_npz( file=get_model_file( model_name=model_name, local_model_store_dir_path=root), obj=net) 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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/models' Location for keeping the model parameters. """ return get_alexnet(version="b", model_name="alexnetb", **kwargs) def _test(): import numpy as np import chainer chainer.global_config.train = False pretrained = False models = [ alexnet, alexnetb, ] for model in models: net = model(pretrained=pretrained) weight_count = net.count_params() print("m={}, {}".format(model.__name__, weight_count)) assert (model != alexnet or weight_count == 62378344) assert (model != alexnetb or weight_count == 61100840) x = np.zeros((1, 3, 224, 224), np.float32) y = net(x) assert (y.shape == (1, 1000)) if __name__ == "__main__": _test()
9,402
28.850794
115
py
imgclsmob
imgclsmob-master/chainer_/chainercv2/models/mobilenet_cub.py
""" MobileNet & FD-MobileNet for CUB-200-2011, implemented in Chainer. 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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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 chainer chainer.global_config.train = False 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) weight_count = net.count_params() 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 = np.zeros((1, 3, 224, 224), np.float32) y = net(x) assert (y.shape == (1, 200)) if __name__ == "__main__": _test()
6,926
34.891192
120
py
imgclsmob
imgclsmob-master/chainer_/chainercv2/models/wrn.py
""" WRN for ImageNet-1K, implemented in Chainer. Original paper: 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146. """ __all__ = ['WRN', 'wrn50_2'] import os import chainer.functions as F import chainer.links as L from chainer import Chain from functools import partial from chainer.serializers import load_npz from .common import SimpleSequential class WRNConv(Chain): """ WRN specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. ksize : int or tuple/list of 2 int Convolution window size. stride : int or tuple/list of 2 int Stride of the convolution. pad : 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, ksize, stride, pad, activate): super(WRNConv, self).__init__() self.activate = activate with self.init_scope(): self.conv = L.Convolution2D( in_channels=in_channels, out_channels=out_channels, ksize=ksize, stride=stride, pad=pad, nobias=False) if self.activate: self.activ = F.relu def __call__(self, x): x = self.conv(x) if self.activate: x = self.activ(x) return x def wrn_conv1x1(in_channels, out_channels, stride, activate): """ 1x1 version of the WRN specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int Stride of the convolution. activate : bool Whether activate the convolution block. """ return WRNConv( in_channels=in_channels, out_channels=out_channels, ksize=1, stride=stride, pad=0, activate=activate) def wrn_conv3x3(in_channels, out_channels, stride, activate): """ 3x3 version of the WRN specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int Stride of the convolution. activate : bool Whether activate the convolution block. """ return WRNConv( in_channels=in_channels, out_channels=out_channels, ksize=3, stride=stride, pad=1, activate=activate) class WRNBottleneck(Chain): """ WRN bottleneck block for residual path in WRN unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int Stride of the convolution. width_factor : float Wide scale factor for width of layers. """ def __init__(self, in_channels, out_channels, stride, width_factor): super(WRNBottleneck, self).__init__() mid_channels = int(round(out_channels // 4 * width_factor)) with self.init_scope(): self.conv1 = wrn_conv1x1( in_channels=in_channels, out_channels=mid_channels, stride=1, activate=True) self.conv2 = wrn_conv3x3( in_channels=mid_channels, out_channels=mid_channels, stride=stride, activate=True) self.conv3 = wrn_conv1x1( in_channels=mid_channels, out_channels=out_channels, stride=1, activate=False) def __call__(self, x): x = self.conv1(x) x = self.conv2(x) x = self.conv3(x) return x class WRNUnit(Chain): """ WRN unit with residual connection. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int Stride of the convolution. width_factor : float Wide scale factor for width of layers. """ def __init__(self, in_channels, out_channels, stride, width_factor): super(WRNUnit, self).__init__() self.resize_identity = (in_channels != out_channels) or (stride != 1) with self.init_scope(): self.body = WRNBottleneck( in_channels=in_channels, out_channels=out_channels, stride=stride, width_factor=width_factor) if self.resize_identity: self.identity_conv = wrn_conv1x1( in_channels=in_channels, out_channels=out_channels, stride=stride, activate=False) self.activ = F.relu def __call__(self, 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(Chain): """ 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): super(WRNInitBlock, self).__init__() with self.init_scope(): self.conv = WRNConv( in_channels=in_channels, out_channels=out_channels, ksize=7, stride=2, pad=3, activate=True) self.pool = partial( F.max_pooling_2d, ksize=3, stride=2, pad=1, cover_all=False) def __call__(self, x): x = self.conv(x) x = self.pool(x) return x class WRN(Chain): """ 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): super(WRN, self).__init__() self.in_size = in_size self.classes = classes with self.init_scope(): self.features = SimpleSequential() with self.features.init_scope(): setattr(self.features, "init_block", WRNInitBlock( in_channels=in_channels, out_channels=init_block_channels)) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential() with stage.init_scope(): for j, out_channels in enumerate(channels_per_stage): stride = 2 if (j == 0) and (i != 0) else 1 setattr(stage, "unit{}".format(j + 1), WRNUnit( in_channels=in_channels, out_channels=out_channels, stride=stride, width_factor=width_factor)) in_channels = out_channels setattr(self.features, "stage{}".format(i + 1), stage) setattr(self.features, "final_pool", partial( F.average_pooling_2d, ksize=7, stride=1)) self.output = SimpleSequential() with self.output.init_scope(): setattr(self.output, "flatten", partial( F.reshape, shape=(-1, in_channels))) setattr(self.output, "fc", L.Linear( in_size=in_channels, out_size=classes)) def __call__(self, x): x = self.features(x) x = self.output(x) return x def get_wrn(blocks, width_factor, model_name=None, pretrained=False, root=os.path.join("~", ".chainer", "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. root : str, default '~/.chainer/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 load_npz( file=get_model_file( model_name=model_name, local_model_store_dir_path=root), obj=net) 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. root : str, default '~/.chainer/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 chainer chainer.global_config.train = False pretrained = False models = [ wrn50_2, ] for model in models: net = model(pretrained=pretrained) weight_count = net.count_params() print("m={}, {}".format(model.__name__, weight_count)) assert (model != wrn50_2 or weight_count == 68849128) x = np.zeros((1, 3, 224, 224), np.float32) y = net(x) assert (y.shape == (1, 1000)) if __name__ == "__main__": _test()
11,832
27.444712
115
py
imgclsmob
imgclsmob-master/chainer_/chainercv2/models/inceptionv3.py
""" InceptionV3 for ImageNet-1K, implemented in Chainer. Original paper: 'Rethinking the Inception Architecture for Computer Vision,' https://arxiv.org/abs/1512.00567. """ __all__ = ['InceptionV3', 'inceptionv3', 'MaxPoolBranch', 'AvgPoolBranch', 'Conv1x1Branch', 'ConvSeqBranch'] import os import chainer.functions as F import chainer.links as L from chainer import Chain from functools import partial from chainer.serializers import load_npz from .common import ConvBlock, conv1x1_block, conv3x3_block, SimpleSequential, Concurrent class MaxPoolBranch(Chain): """ Inception specific max pooling branch block. """ def __init__(self): super(MaxPoolBranch, self).__init__() with self.init_scope(): self.pool = partial( F.max_pooling_2d, ksize=3, stride=2, pad=0, cover_all=False) def __call__(self, x): x = self.pool(x) return x class AvgPoolBranch(Chain): """ Inception specific average pooling branch block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. bn_eps : float Small float added to variance in Batch norm. count_include_pad : bool, default True Whether to include the zero-padding in the averaging calculation. """ def __init__(self, in_channels, out_channels, bn_eps, count_include_pad=True): super(AvgPoolBranch, self).__init__() with self.init_scope(): if count_include_pad: self.pool = partial( F.average_pooling_2d, ksize=3, stride=1, pad=1) else: self.pool = partial( F.average_pooling_nd, ksize=3, stride=1, pad=1, pad_value=None) self.conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, bn_eps=bn_eps) def __call__(self, x): x = self.pool(x) x = self.conv(x) return x class Conv1x1Branch(Chain): """ Inception specific convolutional 1x1 branch block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. bn_eps : float Small float added to variance in Batch norm. """ def __init__(self, in_channels, out_channels, bn_eps): super(Conv1x1Branch, self).__init__() with self.init_scope(): self.conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, bn_eps=bn_eps) def __call__(self, x): x = self.conv(x) return x class ConvSeqBranch(Chain): """ 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_eps : float Small float added to variance in Batch norm. """ def __init__(self, in_channels, out_channels_list, kernel_size_list, strides_list, padding_list, bn_eps): super(ConvSeqBranch, self).__init__() 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.init_scope(): self.conv_list = SimpleSequential() with self.conv_list.init_scope(): for i, (out_channels, kernel_size, strides, padding) in enumerate(zip( out_channels_list, kernel_size_list, strides_list, padding_list)): setattr(self.conv_list, "conv{}".format(i + 1), ConvBlock( in_channels=in_channels, out_channels=out_channels, ksize=kernel_size, stride=strides, pad=padding, bn_eps=bn_eps)) in_channels = out_channels def __call__(self, x): x = self.conv_list(x) return x class ConvSeq3x3Branch(Chain): """ 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_eps : float Small float added to variance in Batch norm. """ def __init__(self, in_channels, out_channels_list, kernel_size_list, strides_list, padding_list, bn_eps): super(ConvSeq3x3Branch, self).__init__() with self.init_scope(): self.conv_list = SimpleSequential() with self.conv_list.init_scope(): for i, (out_channels, kernel_size, strides, padding) in enumerate(zip( out_channels_list, kernel_size_list, strides_list, padding_list)): setattr(self.conv_list, "conv{}".format(i + 1), ConvBlock( in_channels=in_channels, out_channels=out_channels, ksize=kernel_size, stride=strides, pad=padding, bn_eps=bn_eps)) in_channels = out_channels self.conv1x3 = ConvBlock( in_channels=in_channels, out_channels=in_channels, ksize=(1, 3), stride=1, pad=(0, 1), bn_eps=bn_eps) self.conv3x1 = ConvBlock( in_channels=in_channels, out_channels=in_channels, ksize=(3, 1), stride=1, pad=(1, 0), bn_eps=bn_eps) def __call__(self, x): x = self.conv_list(x) y1 = self.conv1x3(x) y2 = self.conv3x1(x) x = F.concat((y1, y2), axis=1) return x class InceptionAUnit(Chain): """ InceptionV3 type Inception-A unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. bn_eps : float Small float added to variance in Batch norm. """ def __init__(self, in_channels, out_channels, bn_eps): super(InceptionAUnit, self).__init__() assert (out_channels > 224) pool_out_channels = out_channels - 224 with self.init_scope(): self.branches = Concurrent() with self.branches.init_scope(): setattr(self.branches, "branch1", Conv1x1Branch( in_channels=in_channels, out_channels=64, bn_eps=bn_eps)) setattr(self.branches, "branch2", ConvSeqBranch( in_channels=in_channels, out_channels_list=(48, 64), kernel_size_list=(1, 5), strides_list=(1, 1), padding_list=(0, 2), bn_eps=bn_eps)) setattr(self.branches, "branch3", 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_eps=bn_eps)) setattr(self.branches, "branch4", AvgPoolBranch( in_channels=in_channels, out_channels=pool_out_channels, bn_eps=bn_eps)) def __call__(self, x): x = self.branches(x) return x class ReductionAUnit(Chain): """ InceptionV3 type Reduction-A unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. bn_eps : float Small float added to variance in Batch norm. """ def __init__(self, in_channels, out_channels, bn_eps): super(ReductionAUnit, self).__init__() assert (in_channels == 288) assert (out_channels == 768) with self.init_scope(): self.branches = Concurrent() with self.branches.init_scope(): setattr(self.branches, "branch1", ConvSeqBranch( in_channels=in_channels, out_channels_list=(384,), kernel_size_list=(3,), strides_list=(2,), padding_list=(0,), bn_eps=bn_eps)) setattr(self.branches, "branch2", 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_eps=bn_eps)) setattr(self.branches, "branch3", MaxPoolBranch()) def __call__(self, x): x = self.branches(x) return x class InceptionBUnit(Chain): """ 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_eps : float Small float added to variance in Batch norm. """ def __init__(self, in_channels, out_channels, mid_channels, bn_eps): super(InceptionBUnit, self).__init__() assert (in_channels == 768) assert (out_channels == 768) with self.init_scope(): self.branches = Concurrent() with self.branches.init_scope(): setattr(self.branches, "branch1", Conv1x1Branch( in_channels=in_channels, out_channels=192, bn_eps=bn_eps)) setattr(self.branches, "branch2", 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_eps=bn_eps)) setattr(self.branches, "branch3", 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_eps=bn_eps)) setattr(self.branches, "branch4", AvgPoolBranch( in_channels=in_channels, out_channels=192, bn_eps=bn_eps)) def __call__(self, x): x = self.branches(x) return x class ReductionBUnit(Chain): """ InceptionV3 type Reduction-B unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. bn_eps : float Small float added to variance in Batch norm. """ def __init__(self, in_channels, out_channels, bn_eps): super(ReductionBUnit, self).__init__() assert (in_channels == 768) assert (out_channels == 1280) with self.init_scope(): self.branches = Concurrent() with self.branches.init_scope(): setattr(self.branches, "branch1", ConvSeqBranch( in_channels=in_channels, out_channels_list=(192, 320), kernel_size_list=(1, 3), strides_list=(1, 2), padding_list=(0, 0), bn_eps=bn_eps)) setattr(self.branches, "branch2", 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_eps=bn_eps)) setattr(self.branches, "branch3", MaxPoolBranch()) def __call__(self, x): x = self.branches(x) return x class InceptionCUnit(Chain): """ InceptionV3 type Inception-C unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. bn_eps : float Small float added to variance in Batch norm. """ def __init__(self, in_channels, out_channels, bn_eps): super(InceptionCUnit, self).__init__() assert (out_channels == 2048) with self.init_scope(): self.branches = Concurrent() with self.branches.init_scope(): setattr(self.branches, "branch1", Conv1x1Branch( in_channels=in_channels, out_channels=320, bn_eps=bn_eps)) setattr(self.branches, "branch2", ConvSeq3x3Branch( in_channels=in_channels, out_channels_list=(384,), kernel_size_list=(1,), strides_list=(1,), padding_list=(0,), bn_eps=bn_eps)) setattr(self.branches, "branch3", ConvSeq3x3Branch( in_channels=in_channels, out_channels_list=(448, 384), kernel_size_list=(1, 3), strides_list=(1, 1), padding_list=(0, 1), bn_eps=bn_eps)) setattr(self.branches, "branch4", AvgPoolBranch( in_channels=in_channels, out_channels=192, bn_eps=bn_eps)) def __call__(self, x): x = self.branches(x) return x class InceptInitBlock(Chain): """ InceptionV3 specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. bn_eps : float Small float added to variance in Batch norm. """ def __init__(self, in_channels, out_channels, bn_eps): super(InceptInitBlock, self).__init__() assert (out_channels == 192) with self.init_scope(): self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=32, stride=2, pad=0, bn_eps=bn_eps) self.conv2 = conv3x3_block( in_channels=32, out_channels=32, stride=1, pad=0, bn_eps=bn_eps) self.conv3 = conv3x3_block( in_channels=32, out_channels=64, stride=1, pad=1, bn_eps=bn_eps) self.pool1 = partial( F.max_pooling_2d, ksize=3, stride=2, pad=0, cover_all=False) self.conv4 = conv1x1_block( in_channels=64, out_channels=80, stride=1, pad=0, bn_eps=bn_eps) self.conv5 = conv3x3_block( in_channels=80, out_channels=192, stride=1, pad=0, bn_eps=bn_eps) self.pool2 = partial( F.max_pooling_2d, ksize=3, stride=2, pad=0, cover_all=False) def __call__(self, 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(Chain): """ 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_eps : float, default 1e-5 Small float added to variance in Batch norm. 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_eps=1e-5, in_channels=3, in_size=(299, 299), classes=1000): super(InceptionV3, self).__init__() self.in_size = in_size self.classes = classes normal_units = [InceptionAUnit, InceptionBUnit, InceptionCUnit] reduction_units = [ReductionAUnit, ReductionBUnit] with self.init_scope(): self.features = SimpleSequential() with self.features.init_scope(): setattr(self.features, "init_block", InceptInitBlock( in_channels=in_channels, out_channels=init_block_channels, bn_eps=bn_eps)) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential() with stage.init_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: setattr(stage, "unit{}".format(j + 1), unit( in_channels=in_channels, out_channels=out_channels, mid_channels=b_mid_channels[j - 1], bn_eps=bn_eps)) else: setattr(stage, "unit{}".format(j + 1), unit( in_channels=in_channels, out_channels=out_channels, bn_eps=bn_eps)) in_channels = out_channels setattr(self.features, "stage{}".format(i + 1), stage) setattr(self.features, "final_pool", partial( F.average_pooling_2d, ksize=8, stride=1)) self.output = SimpleSequential() with self.output.init_scope(): setattr(self.output, "flatten", partial( F.reshape, shape=(-1, in_channels))) setattr(self.output, "dropout", partial( F.dropout, ratio=dropout_rate)) setattr(self.output, "fc", L.Linear( in_size=in_channels, out_size=classes)) def __call__(self, x): x = self.features(x) x = self.output(x) return x def get_inceptionv3(model_name=None, pretrained=False, root=os.path.join("~", ".chainer", "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. root : str, default '~/.chainer/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 load_npz( file=get_model_file( model_name=model_name, local_model_store_dir_path=root), obj=net) 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. root : str, default '~/.chainer/models' Location for keeping the model parameters. """ return get_inceptionv3(model_name="inceptionv3", bn_eps=1e-3, **kwargs) def _test(): import numpy as np import chainer chainer.global_config.train = False pretrained = False models = [ inceptionv3, ] for model in models: net = model(pretrained=pretrained) weight_count = net.count_params() print("m={}, {}".format(model.__name__, weight_count)) assert (model != inceptionv3 or weight_count == 23834568) x = np.zeros((1, 3, 299, 299), np.float32) y = net(x) assert (y.shape == (1, 1000)) if __name__ == "__main__": _test()
23,987
32.178423
115
py
imgclsmob
imgclsmob-master/chainer_/chainercv2/models/fdmobilenet.py
""" FD-MobileNet for ImageNet-1K, implemented in Chainer. 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 chainer.serializers import load_npz from .mobilenet import MobileNet def get_fdmobilenet(width_scale, model_name=None, pretrained=False, root=os.path.join("~", ".chainer", "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. root : str, default '~/.chainer/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 load_npz( file=get_model_file( model_name=model_name, local_model_store_dir_path=root), obj=net) 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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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. root : str, default '~/.chainer/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 chainer chainer.global_config.train = False pretrained = False models = [ fdmobilenet_w1, fdmobilenet_w3d4, fdmobilenet_wd2, fdmobilenet_wd4, ] for model in models: net = model(pretrained=pretrained) weight_count = net.count_params() 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 = np.zeros((1, 3, 224, 224), np.float32) y = net(x) assert (y.shape == (1, 1000)) if __name__ == "__main__": _test()
4,627
29.853333
115
py
imgclsmob
imgclsmob-master/chainer_/chainercv2/models/others/__init__.py
0
0
0
py
imgclsmob
imgclsmob-master/chainer_/metrics/seg_metrics_np.py
""" Routines for segmentation metrics on numpy. """ import numpy as np __all__ = ['seg_pixel_accuracy_np', 'segm_mean_accuracy_hmasks', 'segm_mean_accuracy', 'seg_mean_iou_np', 'segm_mean_iou2', 'seg_mean_iou_imasks_np', 'segm_fw_iou_hmasks', 'segm_fw_iou'] def seg_pixel_accuracy_np(label_imask, pred_imask, vague_idx=-1, use_vague=False, macro_average=True, empty_result=0.0): """ The segmentation pixel accuracy. Parameters: ---------- label_imask : np.array Ground truth index mask (maybe batch of). pred_imask : np.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 ints PA metric value. """ assert (label_imask.shape == pred_imask.shape) if use_vague: sum_u_ij = np.sum(label_imask.flat != vague_idx) if sum_u_ij == 0: if macro_average: return empty_result else: return 0, 0 sum_u_ii = np.sum(np.logical_and(pred_imask.flat == label_imask.flat, label_imask.flat != vague_idx)) else: sum_u_ii = np.sum(pred_imask.flat == label_imask.flat) 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_hmasks(label_hmask, pred_hmask): """ The segmentation mean accuracy. Parameters: ---------- label_hmask : np.array Ground truth one-hot mask. pred_hmask : np.array Predicted one-hot mask. Returns: ------- float MA metric value. """ assert (pred_hmask.shape == label_hmask.shape) assert (len(pred_hmask.shape) == 3) n = label_hmask.shape[0] i_sum = 0 acc_sum = 0.0 for i in range(n): class_i_pred_mask = pred_hmask[i, :, :] class_i_label_mask = label_hmask[i, :, :] u_i = np.sum(class_i_label_mask) if u_i == 0: continue u_ii = np.sum(np.logical_and(class_i_pred_mask, class_i_label_mask)) 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_accuracy(label_hmask, pred_imask): """ The segmentation mean accuracy. Parameters: ---------- label_hmask : np.array Ground truth one-hot mask. pred_imask : np.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 = np.sum(class_i_label_mask) if u_i == 0: continue u_ii = np.sum(np.logical_and(class_i_pred_mask, class_i_label_mask)) 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_imasks(label_hmask, pred_hmask): """ The segmentation mean accuracy. Parameters: ---------- label_hmask : np.array Ground truth one-hot mask. pred_hmask : np.array Predicted one-hot mask. Returns: ------- float MA metric value. """ assert (pred_hmask.shape == label_hmask.shape) assert (len(pred_hmask.shape) == 3) n = label_hmask.shape[0] i_sum = 0 acc_sum = 0.0 for i in range(n): class_i_pred_mask = pred_hmask[i, :, :] class_i_label_mask = label_hmask[i, :, :] u_i = np.sum(class_i_label_mask) if u_i == 0: continue u_ii = np.sum(np.logical_and(class_i_pred_mask, class_i_label_mask)) 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 seg_mean_iou_np(label_hmask, pred_imask): """ The segmentation mean intersection over union. Parameters: ---------- label_hmask : np.array Ground truth one-hot mask. pred_imask : np.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 = np.sum(class_i_label_mask) u_ji_sj = np.sum(class_i_pred_mask) if (u_i + u_ji_sj) == 0: continue u_ii = np.sum(np.logical_and(class_i_pred_mask, class_i_label_mask)) 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 segm_mean_iou2(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 class_axis = 1 # The axis that represents classes inter_hmask = label_hmask * pred_hmask u_i = label_hmask.sum(axis=[2, 3]) u_ji_sj = pred_hmask.sum(axis=[2, 3]) u_ii = inter_hmask.sum(axis=[2, 3]) 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 seg_mean_iou_imasks_np(label_imask, pred_imask, num_classes, vague_idx=-1, use_vague=False, bg_idx=-1, ignore_bg=False, macro_average=True, empty_result=0.0): """ The segmentation mean intersection over union. Parameters: ---------- label_imask : nd.array Ground truth index mask (batch of). pred_imask : nd.array Predicted index mask (batch of). 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. empty_result : float, default 0.0 Result value for an image without any classes. Returns: ------- float or tuple of two np.arrays of int MIoU metric value. """ assert (len(label_imask.shape) == 2) assert (len(pred_imask.shape) == 2) assert (pred_imask.shape == label_imask.shape) min_i = 1 max_i = num_classes n_bins = num_classes if ignore_bg: n_bins -= 1 if bg_idx != 0: assert (bg_idx == num_classes - 1) max_i -= 1 if not (ignore_bg and (bg_idx == 0)): label_imask += 1 pred_imask += 1 vague_idx += 1 if use_vague: label_imask = label_imask * (label_imask != vague_idx) pred_imask = pred_imask * (pred_imask != vague_idx) intersection = pred_imask * (pred_imask == label_imask) area_inter, _ = np.histogram(intersection, bins=n_bins, range=(min_i, max_i)) area_pred, _ = np.histogram(pred_imask, bins=n_bins, range=(min_i, max_i)) area_label, _ = np.histogram(label_imask, bins=n_bins, range=(min_i, max_i)) area_union = area_pred + area_label - area_inter assert ((not ignore_bg) or (len(area_inter) == num_classes - 1)) assert (ignore_bg or (len(area_inter) == num_classes)) if macro_average: class_count = (area_union > 0).sum() if class_count == 0: return empty_result eps = np.finfo(np.float32).eps area_union = area_union + eps mean_iou = (area_inter / area_union).sum() / class_count return mean_iou else: return area_inter.astype(np.uint64), area_union.astype(np.uint64) def segm_fw_iou_hmasks(label_hmask, pred_hmask): """ The segmentation frequency weighted intersection over union. Parameters: ---------- label_hmask : np.array Ground truth one-hot mask. pred_hmask : np.array Predicted one-hot mask. Returns: ------- float FrIoU metric value. """ assert (pred_hmask.shape == label_hmask.shape) assert (len(pred_hmask.shape) == 3) n = label_hmask.shape[0] acc_iou = 0.0 for i in range(n): class_i_pred_mask = pred_hmask[i, :, :] class_i_label_mask = label_hmask[i, :, :] u_i = np.sum(class_i_label_mask) u_ji_sj = np.sum(class_i_pred_mask) if (u_i + u_ji_sj) == 0: continue u_ii = np.sum(np.logical_and(class_i_pred_mask, class_i_label_mask)) acc_iou += float(u_i * u_ii) / (u_i + u_ji_sj - u_ii) fw_factor = pred_hmask[0].size return acc_iou / fw_factor def segm_fw_iou(label_hmask, pred_imask): """ The segmentation frequency weighted intersection over union. Parameters: ---------- label_hmask : np.array Ground truth one-hot mask. pred_imask : np.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 = np.sum(class_i_label_mask) u_ji_sj = np.sum(class_i_pred_mask) if (u_i + u_ji_sj) == 0: continue u_ii = np.sum(np.logical_and(class_i_pred_mask, class_i_label_mask)) acc_iou += float(u_i * u_ii) / (u_i + u_ji_sj - u_ii) fw_factor = pred_imask.size return acc_iou / fw_factor
11,447
25.5
109
py
imgclsmob
imgclsmob-master/chainer_/metrics/seg_metrics.py
""" Evaluation Metrics for Semantic Segmentation. """ import numpy as np from .metric import EvalMetric 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 0 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=0, 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 : xp.array The labels of the data. preds : xp.array Predicted values. """ if self.on_cpu: if self.sparse_label: label_imask = labels.astype(np.int32) else: label_imask = np.argmax(labels, axis=self.axis).astype(np.int32) pred_imask = np.argmax(preds, axis=self.axis).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 0 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=0, 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 : xp.array The labels of the data. preds : xp.array Predicted values. """ if self.on_cpu: if self.sparse_label: label_imask = labels.astype(np.int32) else: assert False pred_imask = np.argmax(preds, axis=self.axis).astype(np.int32) if self.sparse_label: acc = seg_mean_iou_imasks_np( label_imask=label_imask, pred_imask=pred_imask, 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
8,639
31.603774
86
py
imgclsmob
imgclsmob-master/chainer_/metrics/cls_metrics.py
""" Evaluation Metrics for Image Classification. """ import numpy as np from chainer.backends import cuda from .metric import EvalMetric __all__ = ['Top1Error', 'TopKError'] class Accuracy(EvalMetric): """ Computes accuracy classification score. Parameters: ---------- 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, axis=1, name="accuracy", output_names=None, label_names=None): super(Accuracy, self).__init__( name, axis=axis, output_names=output_names, label_names=label_names, has_global_stats=True) self.axis = axis def update(self, labels, preds): """ Updates the internal evaluation result. Parameters: ---------- labels : xp.array The labels of the data with class indices as values, one per sample. preds : xp.array Prediction values for samples. Each prediction value can either be the class index, or a vector of likelihoods for all classes. """ if len(preds.shape) == 1: num_samples = 1 num_correct = (preds.argmax() == labels) else: assert (len(labels) == len(preds)) num_samples = preds.shape[0] label = labels.astype(np.int32).flat pred_label = preds.argmax(axis=self.axis).astype(np.int32).flat num_correct = (pred_label == label).sum() self.sum_metric += num_correct self.global_sum_metric += num_correct self.num_inst += num_samples self.global_num_inst += num_samples class TopKAccuracy(EvalMetric): """ Computes top k predictions accuracy. Parameters: ---------- top_k : int, default 1 Whether targets are in top k predictions. name : str, default 'top_k_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, top_k=1, name="top_k_accuracy", output_names=None, label_names=None): super(TopKAccuracy, self).__init__( name, top_k=top_k, output_names=output_names, label_names=label_names, has_global_stats=True) self.top_k = top_k assert (self.top_k > 1), "Please use Accuracy if top_k is no more than 1" self.name += "_{:d}".format(self.top_k) def update(self, labels, preds): """ Updates the internal evaluation result. Parameters: ---------- labels : xp.array The labels of the data. preds : xp.array Predicted values. """ xp = cuda.get_array_module(preds) if len(preds.shape) == 1: num_samples = 1 argsorted_pred = xp.argsort(preds)[-self.top_k:] num_correct = int(xp.any(argsorted_pred.T == labels, axis=0)) else: assert (len(labels) == len(preds)) num_samples = preds.shape[0] argsorted_pred = xp.argsort(preds)[:, -self.top_k:] num_correct = xp.any(argsorted_pred.T == labels, axis=0).sum() assert (num_correct <= num_samples) self.sum_metric += num_correct self.global_sum_metric += num_correct self.num_inst += num_samples self.global_num_inst += num_samples class Top1Error(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(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
7,114
31.340909
95
py
imgclsmob
imgclsmob-master/chainer_/metrics/__init__.py
0
0
0
py
imgclsmob
imgclsmob-master/chainer_/metrics/det_metrics.py
""" Evaluation Metrics for Object Detection. """ import warnings import numpy as np import mxnet as mx __all__ = ['CocoDetMApMetric'] 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 numpy.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 numpy.ndarray Prediction bounding boxes labels with shape `B, N`. pred_scores : mxnet.NDArray or numpy.ndarray Prediction bounding boxes scores with shape `B, N`. """ def as_numpy(a): """ Convert a (list of) mx.NDArray into numpy.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): 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 : 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]
8,392
38.219626
119
py
imgclsmob
imgclsmob-master/chainer_/metrics/hpe_metrics.py
""" Evaluation Metrics for Human Pose Estimation. """ import numpy as np from .metric import EvalMetric __all__ = ['CocoHpeOksApMetric'] class CocoHpeOksApMetric(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. use_file : bool, default False Whether to use temporary file for estimation. validation_ids : 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 : xp.array The labels of the data. preds : xp.array Predicted values. """ label = np.expand_dims(labels, axis=0) pred = np.expand_dims(preds, axis=0) 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})
3,975
31.859504
98
py
imgclsmob
imgclsmob-master/chainer_/metrics/metric.py
""" Several base metrics. """ __all__ = ['EvalMetric', 'CompositeEvalMetric', 'check_label_shapes'] from collections import OrderedDict def check_label_shapes(labels, preds, shape=False): """ Helper function for checking shape of label and prediction. Parameters: ---------- labels : list of xp.array The labels of the data. preds : list of xp.array Predicted values. shape : boolean If True, check the shape of labels and preds, otherwise only check their length. """ if not shape: label_shape, pred_shape = len(labels), len(preds) else: label_shape, pred_shape = labels.shape, preds.shape if label_shape != pred_shape: raise ValueError("Shape of labels {} does not match shape of predictions {}".format(label_shape, pred_shape)) class EvalMetric(object): """ Base class for all evaluation metrics. Parameters: ---------- name : str 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, name, output_names=None, label_names=None, **kwargs): super(EvalMetric, self).__init__() self.name = str(name) self.output_names = output_names self.label_names = label_names self._has_global_stats = kwargs.pop("has_global_stats", False) self._kwargs = kwargs self.reset() def __str__(self): return "EvalMetric: {}".format(dict(self.get_name_value())) def get_config(self): """ Save configurations of metric. Can be recreated from configs with metric.create(**config). """ config = self._kwargs.copy() config.update({ "metric": self.__class__.__name__, "name": self.name, "output_names": self.output_names, "label_names": self.label_names}) return config def update_dict(self, label, pred): """ Update the internal evaluation with named label and pred. Parameters: ---------- labels : OrderedDict of str -> xp.array name to array mapping for labels. preds : OrderedDict of str -> xp.array name to array mapping of predicted outputs. """ if self.output_names is not None: pred = [pred[name] for name in self.output_names] else: pred = list(pred.values()) if self.label_names is not None: label = [label[name] for name in self.label_names] else: label = list(label.values()) self.update(label, pred) def update(self, labels, preds): """ Updates the internal evaluation result. Parameters: ---------- labels : xp.array The labels of the data. preds : xp.array Predicted values. """ raise NotImplementedError() def reset(self): """ Resets the internal evaluation result to initial state. """ self.num_inst = 0 self.sum_metric = 0.0 self.global_num_inst = 0 self.global_sum_metric = 0.0 def reset_local(self): """ Resets the local portion of the internal evaluation results to initial state. """ self.num_inst = 0 self.sum_metric = 0.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.num_inst == 0: return self.name, float("nan") else: return self.name, self.sum_metric / self.num_inst def get_global(self): """ Gets the current global evaluation result. Returns: ------- names : list of str Name of the metrics. values : list of float Value of the evaluations. """ if self._has_global_stats: if self.global_num_inst == 0: return self.name, float("nan") else: return self.name, self.global_sum_metric / self.global_num_inst else: return self.get() def get_name_value(self): """ Returns zipped name and value pairs. Returns: ------- list of tuples A (name, value) tuple list. """ name, value = self.get() if not isinstance(name, list): name = [name] if not isinstance(value, list): value = [value] return list(zip(name, value)) def get_global_name_value(self): """ Returns zipped name and value pairs for global results. Returns: ------- list of tuples A (name, value) tuple list. """ if self._has_global_stats: name, value = self.get_global() if not isinstance(name, list): name = [name] if not isinstance(value, list): value = [value] return list(zip(name, value)) else: return self.get_name_value() class CompositeEvalMetric(EvalMetric): """ Manages multiple evaluation metrics. Parameters: ---------- name : str, default 'composite' 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, name="composite", output_names=None, label_names=None): super(CompositeEvalMetric, self).__init__( name, output_names=output_names, label_names=label_names, has_global_stats=True) self.metrics = [] def add(self, metric): """ Adds a child metric. Parameters: ---------- metric A metric instance. """ self.metrics.append(metric) def update_dict(self, labels, preds): if self.label_names is not None: labels = OrderedDict([i for i in labels.items() if i[0] in self.label_names]) if self.output_names is not None: preds = OrderedDict([i for i in preds.items() if i[0] in self.output_names]) for metric in self.metrics: metric.update_dict(labels, preds) def update(self, labels, preds): """ Updates the internal evaluation result. Parameters: ---------- labels : xp.array The labels of the data. preds : xp.array Predicted values. """ for metric in self.metrics: metric.update(labels, preds) def reset(self): """ Resets the internal evaluation result to initial state. """ try: for metric in self.metrics: metric.reset() except AttributeError: pass def reset_local(self): """ Resets the local portion of the internal evaluation results to initial state. """ try: for metric in self.metrics: metric.reset_local() except AttributeError: pass def get(self): """ Returns the current evaluation result. Returns: ------- names : list of str Name of the metrics. values : list of float Value of the evaluations. """ names = [] values = [] for metric in self.metrics: name, value = metric.get() name = [name] value = [value] names.extend(name) values.extend(value) return names, values def get_global(self): """ Returns the current evaluation result. Returns: ------- names : list of str Name of the metrics. values : list of float Value of the evaluations. """ names = [] values = [] for metric in self.metrics: name, value = metric.get_global() name = [name] value = [value] names.extend(name) values.extend(value) return names, values def get_config(self): config = super(CompositeEvalMetric, self).get_config() config.update({"metrics": [i.get_config() for i in self.metrics]}) return config
9,257
27.22561
117
py
imgclsmob
imgclsmob-master/chainer_/datasets/imagenet1k_cls_dataset.py
""" ImageNet-1K classification dataset. """ import os import math import numpy as np from PIL import Image from chainer.dataset import DatasetMixin from chainercv.transforms import random_crop from chainercv.transforms import random_flip from chainercv.transforms import pca_lighting from chainercv.transforms import scale from chainercv.transforms import center_crop from chainercv.datasets import DirectoryParsingLabelDataset from .dataset_metainfo import DatasetMetaInfo class ImageNet1K(DatasetMixin): """ ImageNet-1K classification dataset. Parameters: ---------- root : str, default '~/.chainer/datasets/imagenet' Path to the folder stored the dataset. mode: str, default 'train' 'train', 'val', or 'test'. transform : callable, optional A function that transforms the image. """ def __init__(self, root=os.path.join("~", ".chainer", "datasets", "imagenet"), mode="train", transform=None): split = "train" if mode == "train" else "val" root = os.path.join(root, split) self.transform = transform self.base = DirectoryParsingLabelDataset(root) def __len__(self): return len(self.base) def get_example(self, i): image, label = self.base[i] image = self.transform(image) return image, label class ImageNet1KMetaInfo(DatasetMetaInfo): 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.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 = ImageNetTrainTransform self.val_transform = ImageNetValTransform self.test_transform = ImageNetValTransform self.ml_type = "imgcls" self.use_cv_resize = False self.mean_rgb = (0.485, 0.456, 0.406) self.std_rgb = (0.229, 0.224, 0.225) self.interpolation = Image.BILINEAR def add_dataset_parser_arguments(self, parser, work_dir_path): 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( "--use-cv-resize", action="store_true", help="use OpenCV resize preprocessing") 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): super(ImageNet1KMetaInfo, self).update(args) self.input_image_size = (args.input_size, args.input_size) self.use_cv_resize = args.use_cv_resize self.mean_rgb = args.mean_rgb self.std_rgb = args.std_rgb self.interpolation = args.interpolation class ImageNetTrainTransform(object): """ ImageNet-1K training transform. """ def __init__(self, ds_metainfo): self.input_image_size = ds_metainfo.input_image_size self.resize_value = calc_val_resize_value( input_image_size=ds_metainfo.input_image_size, resize_inv_factor=ds_metainfo.resize_inv_factor) self.mean = np.array(ds_metainfo.mean_rgb, np.float32)[:, np.newaxis, np.newaxis] self.std = np.array(ds_metainfo.std_rgb, np.float32)[:, np.newaxis, np.newaxis] self.interpolation = ds_metainfo.interpolation def __call__(self, img): img = random_crop(img=img, size=self.resize_value) img = random_flip(img=img, x_random=True) img = pca_lighting(img=img, sigma=25.5) img = scale(img=img, size=self.resize_value, interpolation=self.interpolation) img = center_crop(img, self.input_image_size) img /= 255.0 img -= self.mean img /= self.std return img class ImageNetValTransform(object): """ ImageNet-1K validation transform. """ def __init__(self, ds_metainfo): self.input_image_size = ds_metainfo.input_image_size self.resize_value = calc_val_resize_value( input_image_size=ds_metainfo.input_image_size, resize_inv_factor=ds_metainfo.resize_inv_factor) self.mean = np.array(ds_metainfo.mean_rgb, np.float32)[:, np.newaxis, np.newaxis] self.std = np.array(ds_metainfo.std_rgb, np.float32)[:, np.newaxis, np.newaxis] self.interpolation = ds_metainfo.interpolation def __call__(self, img): img = scale(img=img, size=self.resize_value, interpolation=self.interpolation) img = center_crop(img, self.input_image_size) img /= 255.0 img -= self.mean img /= self.std return img def calc_val_resize_value(input_image_size=(224, 224), resize_inv_factor=0.875): 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
6,447
35.022346
95
py
imgclsmob
imgclsmob-master/chainer_/datasets/coco_hpe1_dataset.py
""" COCO keypoint detection (2D single human pose estimation) dataset. """ import os import copy import cv2 import numpy as np from chainercv.chainer_experimental.datasets.sliceable import GetterDataset from .dataset_metainfo import DatasetMetaInfo class CocoHpe1Dataset(GetterDataset): """ 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. """ CLASSES = ["person"] KEYPOINTS = { 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" } 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]] 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.num_class = len(self.CLASSES) if isinstance(splits, str): splits = [splits] self._splits = splits self._coco = [] self._check_centers = check_centers self._skip_empty = skip_empty 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._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 + ")" @property def classes(self): """ Category names. """ return type(self).CLASSES @property def num_joints(self): """ Dataset defined: number of joints provided. """ return 17 @property def joint_pairs(self): """ Joint pairs which defines the pairs of joint to be swapped when the image is flipped horizontally. """ return [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14], [15, 16]] @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".format(len(self._coco))) return self._coco[0] 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) img = cv2.imread(img_path, flags=cv2.IMREAD_COLOR) img = cv2.cvtColor(img, code=cv2.COLOR_BGR2RGB) 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 _get_image(self, idx): img_path = self._items[idx] label = copy.deepcopy(self._labels[idx]) # img = mx.image.imread(img_path, 1) img = cv2.imread(img_path, flags=cv2.IMREAD_COLOR) img = cv2.cvtColor(img, code=cv2.COLOR_BGR2RGB) if self.transform is not None: img, scale, center, score = self.transform(img, label) return img def _get_label(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) img = cv2.imread(img_path, flags=cv2.IMREAD_COLOR) img = cv2.cvtColor(img, code=cv2.COLOR_BGR2RGB) if self.transform is not None: img, scale, center, score = self.transform(img, label) res_label = np.array(list(scale) + list(center) + [float(score)] + [float(img_id)], np.float32) return 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, 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) img = img.astype(np.float32) img = img / 255.0 img = (img - np.array(self.mean, np.float32)) / np.array(self.std, np.float32) img = img.transpose((2, 0, 1)) 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) bbox = label["bbox"] assert len(bbox) == 4 score = label.get('score', 1) img, scale_box = detector_to_alpha_pose( src, class_ids=np.array([[0.]]), scores=np.array([[1.]]), bounding_boxs=np.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].astype(np.float32), 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]] = np.clip(boxes[:, [0, 2]], 0., img.shape[1] - 1) boxes[:, [1, 3]] = np.clip(boxes[:, [1, 3]], 0., img.shape[0] - 1) # select boxes mask1 = (class_idxs == 0).astype(np.int32) mask2 = (scores > thr).astype(np.int32) 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 = np.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): 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 = img.astype(np.float32) img = img / 255.0 img = img.transpose((2, 0, 1)) # img = mx.nd.image.to_tensor(np.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 = CocoHpe1Dataset.classes 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.net_extra_kwargs = {} 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
30,881
33.85553
119
py
imgclsmob
imgclsmob-master/chainer_/datasets/ade20k_seg_dataset.py
import os import numpy as np 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)) self.add_getter('img', self._get_image) self.add_getter('label', self._get_label) def _get_image(self, i): image = Image.open(self.images[i]).convert("RGB") assert (self.mode in ("test", "demo")) image = self._img_transform(image) if self.transform is not None: image = self.transform(image) return image def _get_label(self, i): if self.mode == "demo": return os.path.basename(self.images[i]) assert (self.mode == "test") mask = Image.open(self.masks[i]) mask = self._mask_transform(mask) return 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 np_mask 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}]
3,946
33.622807
93
py
imgclsmob
imgclsmob-master/chainer_/datasets/dataset_metainfo.py
""" Base dataset metainfo class. """ import os class DatasetMetaInfo(object): def __init__(self): self.use_imgrec = False self.label = None self.root_dir_name = None self.root_dir_path = None self.dataset_class = 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.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 = None self.test_net_extra_kwargs = None self.load_ignore_extra = False def add_dataset_parser_arguments(self, parser, work_dir_path): 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") def update(self, args): self.root_dir_path = args.data_dir self.num_classes = args.num_classes self.in_channels = args.in_channels def update_from_dataset(self, dataset): """ Update dataset metainfo after a dataset class instance creation. Parameters: ---------- args : obj A dataset class instance. """ pass
2,131
29.028169
72
py
imgclsmob
imgclsmob-master/chainer_/datasets/seg_dataset.py
import random import numpy as np from PIL import Image, ImageOps, ImageFilter from chainercv.chainer_experimental.datasets.sliceable import GetterDataset class SegDataset(GetterDataset): """ 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): super(SegDataset, self).__init__() assert (mode in ("train", "val", "test", "demo")) assert (mode in ("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): outsize = self.crop_size short_size = outsize w, h = image.size if w > h: oh = short_size ow = int(1.0 * w * oh / h) else: ow = short_size oh = int(1.0 * h * ow / w) image = image.resize((ow, oh), Image.BILINEAR) mask = mask.resize((ow, oh), Image.NEAREST) # center crop w, h = image.size x1 = int(round(0.5 * (w - outsize))) y1 = int(round(0.5 * (h - 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), self._mask_transform(mask) return image, mask def _sync_transform(self, image, mask): # random mirror if random.random() < 0.5: image = image.transpose(Image.FLIP_LEFT_RIGHT) mask = mask.transpose(Image.FLIP_LEFT_RIGHT) crop_size = self.crop_size # 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 h > w: ow = short_size oh = int(1.0 * h * ow / w) else: oh = short_size ow = int(1.0 * w * oh / h) image = image.resize((ow, oh), Image.BILINEAR) mask = mask.resize((ow, oh), Image.NEAREST) # pad crop 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), self._mask_transform(mask) return image, mask @staticmethod def _img_transform(image): return np.array(image) @staticmethod def _mask_transform(mask): return np.array(mask).astype(np.int32)
3,474
33.405941
89
py
imgclsmob
imgclsmob-master/chainer_/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 chainercv.chainer_experimental.datasets.sliceable import GetterDataset from .dataset_metainfo import DatasetMetaInfo class CocoHpe2Dataset(GetterDataset): """ 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 def _get_image(self, idx): image, label = self[idx] return image def _get_label(self, idx): image, label = self[idx] return 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.net_extra_kwargs = {} 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,988
39.597679
119
py
imgclsmob
imgclsmob-master/chainer_/datasets/svhn_cls_dataset.py
""" SVHN classification dataset. """ import os from chainer.dataset import DatasetMixin from chainer.datasets.svhn import get_svhn from .cifar10_cls_dataset import CIFAR10MetaInfo class SVHN(DatasetMixin): """ 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 '~/.chainer/datasets/svhn' Path to temp folder for storing data. 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("~", ".chainer", "datasets", "svhn"), mode="train", transform=None): assert (root is not None) self.transform = transform train_ds, test_ds = get_svhn() self.base = train_ds if mode == "train" else test_ds def __len__(self): return len(self.base) def get_example(self, i): image, label = self.base[i] image = self.transform(image) return image, label 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
1,587
29.538462
93
py
imgclsmob
imgclsmob-master/chainer_/datasets/coco_hpe3_dataset.py
""" COCO keypoint detection (2D multiple human pose estimation) dataset (for IBPPose). """ import os import math import cv2 import numpy as np from chainercv.chainer_experimental.datasets.sliceable import GetterDataset from .dataset_metainfo import DatasetMetaInfo class CocoHpe3Dataset(GetterDataset): """ 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 def _get_image(self, idx): image, label = self[idx] return image def _get_label(self, idx): image, label = self[idx] return 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.net_extra_kwargs = {} 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,313
39.830123
120
py
imgclsmob
imgclsmob-master/chainer_/datasets/cifar10_cls_dataset.py
""" CIFAR-10 classification dataset. """ import os import numpy as np from chainer.dataset import DatasetMixin from chainer.datasets.cifar import get_cifar10 from chainercv.transforms import random_crop from chainercv.transforms import random_flip from .dataset_metainfo import DatasetMetaInfo class CIFAR10(DatasetMixin): """ CIFAR-10 image classification dataset. Parameters: ---------- root : str, default '~/.chainer/datasets/cifar10' Path to temp folder for storing data. 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("~", ".chainer", "datasets", "cifar10"), mode="train", transform=None): assert (root is not None) self.transform = transform train_ds, test_ds = get_cifar10() self.base = train_ds if mode == "train" else test_ds def __len__(self): return len(self.base) def get_example(self, i): image, label = self.base[i] image = self.transform(image) return image, label 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 = CIFAR10 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 = CIFARTrainTransform self.val_transform = CIFARValTransform self.test_transform = CIFARValTransform self.ml_type = "imgcls" class CIFARTrainTransform(object): """ CIFAR-10 training transform. """ def __init__(self, ds_metainfo, mean_rgb=(0.4914, 0.4822, 0.4465), std_rgb=(0.2023, 0.1994, 0.2010)): assert (ds_metainfo is not None) self.mean = np.array(mean_rgb, np.float32)[:, np.newaxis, np.newaxis] self.std = np.array(std_rgb, np.float32)[:, np.newaxis, np.newaxis] def __call__(self, img): img = random_crop(img=img, size=self.resize_value) img = random_flip(img=img, x_random=True) img -= self.mean img /= self.std return img class CIFARValTransform(object): """ CIFAR-10 validation transform. """ def __init__(self, ds_metainfo, mean_rgb=(0.4914, 0.4822, 0.4465), std_rgb=(0.2023, 0.1994, 0.2010)): assert (ds_metainfo is not None) self.mean = np.array(mean_rgb, np.float32)[:, np.newaxis, np.newaxis] self.std = np.array(std_rgb, np.float32)[:, np.newaxis, np.newaxis] def __call__(self, img): img -= self.mean img /= self.std return img
3,307
30.207547
77
py
imgclsmob
imgclsmob-master/chainer_/datasets/__init__.py
0
0
0
py
imgclsmob
imgclsmob-master/chainer_/datasets/cub200_2011_cls_dataset.py
""" CUB-200-2011 classification dataset. """ import os import numpy as np import pandas as pd from chainercv.chainer_experimental.datasets.sliceable import GetterDataset from chainercv.utils import read_image from .imagenet1k_cls_dataset import ImageNet1KMetaInfo class CUB200_2011(GetterDataset): """ CUB-200-2011 fine-grained classification dataset. Parameters: ---------- root : str, default '~/.chainer/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 transforms it. """ def __init__(self, root=os.path.join("~", ".chainer", "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 self.add_getter('img', self._get_image) self.add_getter('label', self._get_label) def _get_image(self, i): image_file_name = self.image_file_names[i] image_file_path = os.path.join(self.images_dir_path, image_file_name) image = read_image(image_file_path, color=True) if self._transform is not None: image = self._transform(image) return image def _get_label(self, i): label = int(self.class_ids[i]) return label def __len__(self): return len(self.image_ids) # def __getitem__(self, i): # image = self._get_image(i) # label = self._get_label(i) # return image, label # # def get_example(self, i): # image, label = self[i] # return image, label 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.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.net_extra_kwargs = None self.load_ignore_extra = False
5,271
34.621622
94
py
imgclsmob
imgclsmob-master/chainer_/datasets/cityscapes_seg_dataset.py
import os import numpy as np 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)) self.add_getter('img', self._get_image) self.add_getter('label', self._get_label) def _get_image(self, i): image = Image.open(self.images[i]).convert("RGB") assert (self.mode in ("test", "demo")) image = self._img_transform(image) if self.transform is not None: image = self.transform(image) return image def _get_label(self, i): if self.mode == "demo": return os.path.basename(self.images[i]) assert (self.mode == "test") mask = Image.open(self.masks[i]) mask = self._mask_transform(mask) return 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 np_mask 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}] self.test_net_extra_kwargs = self.net_extra_kwargs
4,878
36.530769
105
py
imgclsmob
imgclsmob-master/chainer_/datasets/coco_seg_dataset.py
""" COCO semantic segmentation dataset. """ import os import logging import numpy as np 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: str Path to `annotations`, `train2017`, and `val2017` folders. 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(CocoSegDataset, self).__init__( root=root, mode=mode, transform=transform, **kwargs) 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") idx_file_path = os.path.join(annotations_dir_path, mode_name + "_idx.npy") self.image_dir_path = os.path.join(root, mode_name + "2017") 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) self.transform = transform self.add_getter('img', self._get_image) self.add_getter('label', self._get_label) def _get_image(self, i): image_idx = int(self.idx[i]) img_metadata = self.coco.loadImgs(image_idx)[0] image_file_name = img_metadata["file_name"] image_file_path = os.path.join(self.image_dir_path, image_file_name) image = Image.open(image_file_path).convert("RGB") assert (self.mode in ("test", "demo")) image = self._img_transform(image) if self.transform is not None: image = self.transform(image) return image def _get_label(self, i): if self.mode == "demo": image_idx = int(self.idx[i]) img_metadata = self.coco.loadImgs(image_idx)[0] image_file_name = img_metadata["file_name"] image_file_path = os.path.join(self.image_dir_path, image_file_name) return os.path.basename(image_file_path) assert (self.mode == "test") image_idx = int(self.idx[i]) img_metadata = self.coco.loadImgs(image_idx)[0] coco_target = self.coco.loadAnns(self.coco.getAnnIds(imgIds=image_idx)) mask = Image.fromarray(self._gen_seg_mask( coco_target, img_metadata["height"], img_metadata["width"])) mask = self._mask_transform(mask) return mask def _gen_seg_mask(self, target, h, w): 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((h, w), dtype=np.uint8) for instance in target: rle = self.coco_mask.frPyObjects(instance["segmentation"], h, w) 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, idx_file, pixels_thr=1000): logging.info("Filtering mask index") tbar = trange(len(idx)) filtered_idx = [] for i in tbar: img_id = idx[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), len(filtered_idx))) logging.info("Found number of qualified images: {}".format(len(filtered_idx))) np.save(idx_file, 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): np_mask = np.array(mask).astype(np.int32) return np_mask 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.test_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}]
5,768
33.753012
112
py
imgclsmob
imgclsmob-master/chainer_/datasets/voc_seg_dataset.py
""" Pascal VOC2012 semantic segmentation dataset. """ import os import numpy as np from PIL import Image from chainer import get_dtype 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)) # self.images = self.images[:10] # self.masks = self.masks[:10] self.add_getter('img', self._get_image) self.add_getter('label', self._get_label) def _get_image(self, i): image = Image.open(self.images[i]).convert("RGB") assert (self.mode in ("test", "demo")) image = self._img_transform(image) if self.transform is not None: image = self.transform(image) return image def _get_label(self, i): if self.mode == "demo": return os.path.basename(self.images[i]) assert (self.mode == "test") mask = Image.open(self.masks[i]) mask = self._mask_transform(mask) return mask classes = 21 vague_idx = 255 use_vague = True background_idx = 0 ignore_bg = True @staticmethod def _mask_transform(mask): np_mask = np.array(mask).astype(np.int32) # np_mask[np_mask == 255] = VOCSegDataset.vague_idx return np_mask def __len__(self): return len(self.images) class VOCSegTrainTransform(object): """ ImageNet-1K training transform. """ def __init__(self, ds_metainfo, mean_rgb=(0.485, 0.456, 0.406), std_rgb=(0.229, 0.224, 0.225)): assert (ds_metainfo is not None) self.mean = np.array(mean_rgb, np.float32)[:, np.newaxis, np.newaxis] self.std = np.array(std_rgb, np.float32)[:, np.newaxis, np.newaxis] def __call__(self, img): dtype = get_dtype(None) img = img.transpose(2, 0, 1) img = img.astype(dtype) img *= 1.0 / 255.0 img -= self.mean img /= self.std return img class VOCSegTestTransform(object): """ ImageNet-1K validation transform. """ def __init__(self, ds_metainfo, mean_rgb=(0.485, 0.456, 0.406), std_rgb=(0.229, 0.224, 0.225)): assert (ds_metainfo is not None) self.mean = np.array(mean_rgb, np.float32)[:, np.newaxis, np.newaxis] self.std = np.array(std_rgb, np.float32)[:, np.newaxis, np.newaxis] def __call__(self, img): dtype = get_dtype(None) img = img.transpose(2, 0, 1) img = img.astype(dtype) img *= 1.0 / 255.0 img -= self.mean img /= self.std return img 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.input_image_size = (480, 480) 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_extra_kwargs = None self.test_metric_capts = ["Val.PixAcc", "Val.IoU"] self.test_metric_names = ["PixelAccuracyMetric", "MeanIoUMetric"] self.test_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.saver_acc_ind = 1 self.train_transform = VOCSegTrainTransform self.val_transform = VOCSegTestTransform self.test_transform = VOCSegTestTransform self.ml_type = "imgseg" self.allow_hybridize = False self.net_extra_kwargs = {"aux": False, "fixed_size": False} self.load_ignore_extra = True self.image_base_size = 520 self.image_crop_size = 480 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,790
31.966019
90
py
imgclsmob
imgclsmob-master/chainer_/datasets/cifar100_cls_dataset.py
""" CIFAR-100 classification dataset. """ import os from chainer.dataset import DatasetMixin from chainer.datasets.cifar import get_cifar100 from .cifar10_cls_dataset import CIFAR10MetaInfo class CIFAR100(DatasetMixin): """ CIFAR-100 image classification dataset. Parameters: ---------- root : str, default '~/.chainer/datasets/cifar100' Path to temp folder for storing data. 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("~", ".chainer", "datasets", "cifar100"), mode="train", transform=None): assert (root is not None) self.transform = transform train_ds, test_ds = get_cifar100() self.base = train_ds if mode == "train" else test_ds def __len__(self): return len(self.base) def get_example(self, i): image, label = self.base[i] image = self.transform(image) return image, label class CIFAR100MetaInfo(CIFAR10MetaInfo): def __init__(self): super(CIFAR100MetaInfo, self).__init__() self.label = "CIFAR100" self.root_dir_name = "cifar100" self.dataset_class = CIFAR100 self.num_classes = 100
1,375
26.52
76
py
imgclsmob
imgclsmob-master/tensorflow2/dataset_utils.py
""" Dataset routines. """ __all__ = ['get_dataset_metainfo', 'get_train_data_source', 'get_val_data_source', 'get_test_data_source'] import tensorflow as tf 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_hpe1_dataset import CocoHpe1MetaInfo from .datasets.coco_hpe2_dataset import CocoHpe2MetaInfo from .datasets.coco_hpe3_dataset import CocoHpe3MetaInfo 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, "CocoHpe1": CocoHpe1MetaInfo, "CocoHpe2": CocoHpe2MetaInfo, "CocoHpe3": CocoHpe3MetaInfo, } 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, data_format="channels_last"): """ Get data source for training subset. Parameters: ---------- ds_metainfo : DatasetMetaInfo Dataset metainfo. batch_size : int Batch size. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. Returns: ------- DataLoader Data source. int Dataset size. """ data_generator = ds_metainfo.train_transform( ds_metainfo=ds_metainfo, data_format=data_format) generator = ds_metainfo.train_generator( data_generator=data_generator, ds_metainfo=ds_metainfo, batch_size=batch_size) return tf.data.Dataset.from_generator( generator=lambda: generator, output_types=(tf.float32, tf.float32)),\ generator.n def get_val_data_source(ds_metainfo, batch_size, data_format="channels_last"): """ Get data source for validation subset. Parameters: ---------- ds_metainfo : DatasetMetaInfo Dataset metainfo. batch_size : int Batch size. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. Returns: ------- DataLoader Data source. int Dataset size. """ data_generator = ds_metainfo.val_transform( ds_metainfo=ds_metainfo, data_format=data_format) generator = ds_metainfo.val_generator( data_generator=data_generator, ds_metainfo=ds_metainfo, batch_size=batch_size) if hasattr(generator, "dataset"): ds_metainfo.update_from_dataset(generator.dataset) return tf.data.Dataset.from_generator( generator=lambda: generator, output_types=(tf.float32, tf.float32)),\ generator.n def get_test_data_source(ds_metainfo, batch_size, data_format="channels_last"): """ Get data source for testing subset. Parameters: ---------- ds_metainfo : DatasetMetaInfo Dataset metainfo. batch_size : int Batch size. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. Returns: ------- DataLoader Data source. int Dataset size. """ data_generator = ds_metainfo.test_transform( ds_metainfo=ds_metainfo, data_format=data_format) generator = ds_metainfo.test_generator( data_generator=data_generator, ds_metainfo=ds_metainfo, batch_size=batch_size) if hasattr(generator, "dataset"): ds_metainfo.update_from_dataset(generator.dataset) return tf.data.Dataset.from_generator( generator=lambda: generator, output_types=(tf.float32, tf.float32)),\ generator.n
4,740
28.08589
106
py
imgclsmob
imgclsmob-master/tensorflow2/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='tf2cv', version='0.0.18', description='Image classification models for TensorFlow 2.0', 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 tensorflow imagenet vgg resnet resnext ' 'senet densenet darknet squeezenet squeezenext shufflenet menet mobilenent igcv3 mnasnet', packages=find_packages(exclude=['datasets', 'metrics', 'others', '*.others', 'others.*', '*.others.*']), include_package_data=True, install_requires=['numpy', 'requests'], )
1,287
38.030303
120
py
imgclsmob
imgclsmob-master/tensorflow2/utils.py
__all__ = ['prepare_model'] import os import logging import tensorflow as tf from .tf2cv.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 def prepare_model(model_name, use_pretrained, pretrained_model_file_path, net_extra_kwargs=None, load_ignore_extra=False, batch_size=None, use_cuda=True): kwargs = {"pretrained": use_pretrained} if net_extra_kwargs is not None: kwargs.update(net_extra_kwargs) # kwargs["input_shape"] = (1, 224, 224, 3) # my_devices = tf.config.experimental.list_physical_devices(device_type="CPU") # tf.config.experimental.set_visible_devices(devices=my_devices, device_type="CPU") # tf.debugging.set_log_device_placement(True) if not use_cuda: with tf.device("/cpu:0"): net = get_model(model_name, **kwargs) # input_shape = ((1, 3, net.in_size[0], net.in_size[1]) if # net.data_format == "channels_first" else (1, net.in_size[0], net.in_size[1], 3)) # net.build(input_shape=input_shape) else: net = get_model(model_name, **kwargs) # input_shape = ((batch_size, 3, net.in_size[0], net.in_size[1]) if # net.data_format == "channels_first" else (batch_size, net.in_size[0], net.in_size[1], 3)) # net.build(input_shape=input_shape) if pretrained_model_file_path: assert (os.path.isfile(pretrained_model_file_path)) logging.info("Loading model: {}".format(pretrained_model_file_path)) input_shape = ((batch_size, 3, net.in_size[0], net.in_size[1]) if net.data_format == "channels_first" else (batch_size, net.in_size[0], net.in_size[1], 3)) net.build(input_shape=input_shape) if load_ignore_extra: net.load_weights( filepath=pretrained_model_file_path, by_name=True, skip_mismatch=True) else: net.load_weights( filepath=pretrained_model_file_path) return net 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. Returns: ------- 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) 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)))
5,931
31.773481
116
py
imgclsmob
imgclsmob-master/tensorflow2/__init__.py
0
0
0
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/__init__.py
0
0
0
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/model_provider.py
from .models.alexnet import * from .models.zfnet import * from .models.vgg import * from .models.bninception import * from .models.resnet import * from .models.preresnet import * from .models.resnext import * from .models.seresnet import * from .models.sepreresnet import * from .models.seresnext import * from .models.senet import * from .models.resnesta import * from .models.ibnresnet import * from .models.ibnbresnet import * from .models.ibnresnext import * from .models.ibndensenet import * from .models.airnet import * from .models.airnext import * from .models.bamresnet import * from .models.cbamresnet import * from .models.scnet import * from .models.regnet import * from .models.pyramidnet import * from .models.diracnetv2 import * from .models.densenet import * from .models.peleenet import * from .models.wrn import * from .models.drn import * from .models.dpn import * from .models.darknet import * from .models.darknet53 import * from .models.bagnet import * from .models.dla import * from .models.dicenet import * from .models.hrnet import * from .models.vovnet import * from .models.selecsls import * from .models.hardnet import * from .models.squeezenet import * from .models.squeezenext import * from .models.shufflenet import * from .models.shufflenetv2 import * from .models.shufflenetv2b import * from .models.menet import * from .models.mobilenet import * from .models.mobilenetb import * from .models.fdmobilenet import * from .models.mobilenetv2 import * from .models.mobilenetv3 import * from .models.igcv3 import * from .models.ghostnet import * from .models.mnasnet import * from .models.proxylessnas import * from .models.fbnet import * from .models.xception import * from .models.inceptionv3 import * from .models.inceptionv4 import * from .models.inceptionresnetv1 import * from .models.inceptionresnetv2 import * from .models.polynet import * from .models.nasnet import * from .models.pnasnet import * from .models.spnasnet import * from .models.efficientnet import * from .models.efficientnetedge import * from .models.mixnet import * from .models.resnet_cifar import * from .models.preresnet_cifar import * from .models.resnext_cifar import * from .models.seresnet_cifar import * from .models.sepreresnet_cifar import * from .models.pyramidnet_cifar import * from .models.densenet_cifar import * from .models.wrn_cifar import * from .models.resneta import * from .models.resnetd import * from .models.fastseresnet import * from .models.resnet_cub import * from .models.seresnet_cub import * from .models.mobilenet_cub import * from .models.proxylessnas_cub import * from .models.fcn8sd import * from .models.pspnet import * from .models.deeplabv3 import * from .models.icnet import * from .models.fastscnn import * from .models.cgnet import * from .models.dabnet import * from .models.sinet import * from .models.bisenet import * from .models.danet import * from .models.fpenet import * from .models.lednet import * from .models.alphapose_coco import * from .models.simplepose_coco import * from .models.simpleposemobile_coco import * from .models.lwopenpose_cmupan import * from .models.ibppose_coco import * from .models.grmiposelite_coco import * from .models.centernet import * from .models.lffd import * from .models.voca import * from .models.nvpattexp import * from .models.jasper import * from .models.jasperdr import * from .models.quartznet import * __all__ = ['get_model'] _models = { 'alexnet': alexnet, 'alexnetb': alexnetb, 'zfnet': zfnet, 'zfnetb': zfnetb, 'vgg11': vgg11, 'vgg13': vgg13, 'vgg16': vgg16, 'vgg19': vgg19, 'bn_vgg11': bn_vgg11, 'bn_vgg13': bn_vgg13, 'bn_vgg16': bn_vgg16, 'bn_vgg19': bn_vgg19, 'bn_vgg11b': bn_vgg11b, 'bn_vgg13b': bn_vgg13b, 'bn_vgg16b': bn_vgg16b, 'bn_vgg19b': bn_vgg19b, 'bninception': bninception, 'resnet10': resnet10, 'resnet12': resnet12, 'resnet14': resnet14, 'resnetbc14b': resnetbc14b, 'resnet16': resnet16, 'resnet18_wd4': resnet18_wd4, 'resnet18_wd2': resnet18_wd2, 'resnet18_w3d4': resnet18_w3d4, 'resnet18': resnet18, 'resnet26': resnet26, 'resnetbc26b': resnetbc26b, 'resnet34': resnet34, 'resnetbc38b': resnetbc38b, 'resnet50': resnet50, 'resnet50b': resnet50b, 'resnet101': resnet101, 'resnet101b': resnet101b, 'resnet152': resnet152, 'resnet152b': resnet152b, 'resnet200': resnet200, 'resnet200b': resnet200b, 'preresnet10': preresnet10, 'preresnet12': preresnet12, 'preresnet14': preresnet14, 'preresnetbc14b': preresnetbc14b, 'preresnet16': preresnet16, 'preresnet18_wd4': preresnet18_wd4, 'preresnet18_wd2': preresnet18_wd2, 'preresnet18_w3d4': preresnet18_w3d4, 'preresnet18': preresnet18, 'preresnet26': preresnet26, 'preresnetbc26b': preresnetbc26b, 'preresnet34': preresnet34, 'preresnetbc38b': preresnetbc38b, 'preresnet50': preresnet50, 'preresnet50b': preresnet50b, 'preresnet101': preresnet101, 'preresnet101b': preresnet101b, 'preresnet152': preresnet152, 'preresnet152b': preresnet152b, 'preresnet200': preresnet200, 'preresnet200b': preresnet200b, 'preresnet269b': preresnet269b, 'resnext14_16x4d': resnext14_16x4d, 'resnext14_32x2d': resnext14_32x2d, 'resnext14_32x4d': resnext14_32x4d, 'resnext26_16x4d': resnext26_16x4d, 'resnext26_32x2d': resnext26_32x2d, 'resnext26_32x4d': resnext26_32x4d, 'resnext38_32x4d': resnext38_32x4d, 'resnext50_32x4d': resnext50_32x4d, 'resnext101_32x4d': resnext101_32x4d, 'resnext101_64x4d': resnext101_64x4d, 'seresnet10': seresnet10, 'seresnet12': seresnet12, 'seresnet14': seresnet14, 'seresnet16': seresnet16, 'seresnet18': seresnet18, 'seresnet26': seresnet26, 'seresnetbc26b': seresnetbc26b, 'seresnet34': seresnet34, 'seresnetbc38b': seresnetbc38b, 'seresnet50': seresnet50, 'seresnet50b': seresnet50b, 'seresnet101': seresnet101, 'seresnet101b': seresnet101b, 'seresnet152': seresnet152, 'seresnet152b': seresnet152b, 'seresnet200': seresnet200, 'seresnet200b': seresnet200b, 'sepreresnet10': sepreresnet10, 'sepreresnet12': sepreresnet12, 'sepreresnet14': sepreresnet14, 'sepreresnet16': sepreresnet16, 'sepreresnet18': sepreresnet18, 'sepreresnet26': sepreresnet26, 'sepreresnetbc26b': sepreresnetbc26b, 'sepreresnet34': sepreresnet34, 'sepreresnetbc38b': sepreresnetbc38b, 'sepreresnet50': sepreresnet50, 'sepreresnet50b': sepreresnet50b, 'sepreresnet101': sepreresnet101, 'sepreresnet101b': sepreresnet101b, 'sepreresnet152': sepreresnet152, 'sepreresnet152b': sepreresnet152b, 'sepreresnet200': sepreresnet200, 'sepreresnet200b': sepreresnet200b, 'seresnext50_32x4d': seresnext50_32x4d, 'seresnext101_32x4d': seresnext101_32x4d, 'seresnext101_64x4d': seresnext101_64x4d, 'senet16': senet16, 'senet28': senet28, 'senet40': senet40, 'senet52': senet52, 'senet103': senet103, 'senet154': senet154, 'resnestabc14': resnestabc14, 'resnesta18': resnesta18, 'resnestabc26': resnestabc26, 'resnesta50': resnesta50, 'resnesta101': resnesta101, 'resnesta152': resnesta152, 'resnesta200': resnesta200, 'resnesta269': resnesta269, 'ibn_resnet50': ibn_resnet50, 'ibn_resnet101': ibn_resnet101, 'ibn_resnet152': ibn_resnet152, 'ibnb_resnet50': ibnb_resnet50, 'ibnb_resnet101': ibnb_resnet101, 'ibnb_resnet152': ibnb_resnet152, 'ibn_resnext50_32x4d': ibn_resnext50_32x4d, 'ibn_resnext101_32x4d': ibn_resnext101_32x4d, 'ibn_resnext101_64x4d': ibn_resnext101_64x4d, 'ibn_densenet121': ibn_densenet121, 'ibn_densenet161': ibn_densenet161, 'ibn_densenet169': ibn_densenet169, 'ibn_densenet201': ibn_densenet201, 'airnet50_1x64d_r2': airnet50_1x64d_r2, 'airnet50_1x64d_r16': airnet50_1x64d_r16, 'airnet101_1x64d_r2': airnet101_1x64d_r2, 'airnext50_32x4d_r2': airnext50_32x4d_r2, 'airnext101_32x4d_r2': airnext101_32x4d_r2, 'airnext101_32x4d_r16': airnext101_32x4d_r16, 'bam_resnet18': bam_resnet18, 'bam_resnet34': bam_resnet34, 'bam_resnet50': bam_resnet50, 'bam_resnet101': bam_resnet101, 'bam_resnet152': bam_resnet152, 'cbam_resnet18': cbam_resnet18, 'cbam_resnet34': cbam_resnet34, 'cbam_resnet50': cbam_resnet50, 'cbam_resnet101': cbam_resnet101, 'cbam_resnet152': cbam_resnet152, 'scnet50': scnet50, 'scnet101': scnet101, 'scneta50': scneta50, 'scneta101': scneta101, 'regnetx002': regnetx002, 'regnetx004': regnetx004, 'regnetx006': regnetx006, 'regnetx008': regnetx008, 'regnetx016': regnetx016, 'regnetx032': regnetx032, 'regnetx040': regnetx040, 'regnetx064': regnetx064, 'regnetx080': regnetx080, 'regnetx120': regnetx120, 'regnetx160': regnetx160, 'regnetx320': regnetx320, 'regnety002': regnety002, 'regnety004': regnety004, 'regnety006': regnety006, 'regnety008': regnety008, 'regnety016': regnety016, 'regnety032': regnety032, 'regnety040': regnety040, 'regnety064': regnety064, 'regnety080': regnety080, 'regnety120': regnety120, 'regnety160': regnety160, 'regnety320': regnety320, 'pyramidnet101_a360': pyramidnet101_a360, 'diracnet18v2': diracnet18v2, 'diracnet34v2': diracnet34v2, 'densenet121': densenet121, 'densenet161': densenet161, 'densenet169': densenet169, 'densenet201': densenet201, 'peleenet': peleenet, 'wrn50_2': wrn50_2, 'drnc26': drnc26, 'drnc42': drnc42, 'drnc58': drnc58, 'drnd22': drnd22, 'drnd38': drnd38, 'drnd54': drnd54, 'drnd105': drnd105, 'dpn68': dpn68, 'dpn68b': dpn68b, 'dpn98': dpn98, 'dpn107': dpn107, 'dpn131': dpn131, 'darknet_ref': darknet_ref, 'darknet_tiny': darknet_tiny, 'darknet19': darknet19, 'darknet53': darknet53, 'bagnet9': bagnet9, 'bagnet17': bagnet17, 'bagnet33': bagnet33, 'dla34': dla34, 'dla46c': dla46c, 'dla46xc': dla46xc, 'dla60': dla60, 'dla60x': dla60x, 'dla60xc': dla60xc, 'dla102': dla102, 'dla102x': dla102x, 'dla102x2': dla102x2, 'dla169': dla169, 'dicenet_wd5': dicenet_wd5, 'dicenet_wd2': dicenet_wd2, 'dicenet_w3d4': dicenet_w3d4, 'dicenet_w1': dicenet_w1, 'dicenet_w5d4': dicenet_w5d4, 'dicenet_w3d2': dicenet_w3d2, 'dicenet_w7d8': dicenet_w7d8, 'dicenet_w2': dicenet_w2, 'hrnet_w18_small_v1': hrnet_w18_small_v1, 'hrnet_w18_small_v2': hrnet_w18_small_v2, 'hrnetv2_w18': hrnetv2_w18, 'hrnetv2_w30': hrnetv2_w30, 'hrnetv2_w32': hrnetv2_w32, 'hrnetv2_w40': hrnetv2_w40, 'hrnetv2_w44': hrnetv2_w44, 'hrnetv2_w48': hrnetv2_w48, 'hrnetv2_w64': hrnetv2_w64, 'vovnet27s': vovnet27s, 'vovnet39': vovnet39, 'vovnet57': vovnet57, 'selecsls42': selecsls42, 'selecsls42b': selecsls42b, 'selecsls60': selecsls60, 'selecsls60b': selecsls60b, 'selecsls84': selecsls84, 'hardnet39ds': hardnet39ds, 'hardnet68ds': hardnet68ds, 'hardnet68': hardnet68, 'hardnet85': hardnet85, 'squeezenet_v1_0': squeezenet_v1_0, 'squeezenet_v1_1': squeezenet_v1_1, 'squeezeresnet_v1_0': squeezeresnet_v1_0, 'squeezeresnet_v1_1': squeezeresnet_v1_1, 'sqnxt23_w1': sqnxt23_w1, 'sqnxt23_w3d2': sqnxt23_w3d2, 'sqnxt23_w2': sqnxt23_w2, 'sqnxt23v5_w1': sqnxt23v5_w1, 'sqnxt23v5_w3d2': sqnxt23v5_w3d2, 'sqnxt23v5_w2': sqnxt23v5_w2, 'shufflenet_g1_w1': shufflenet_g1_w1, 'shufflenet_g2_w1': shufflenet_g2_w1, 'shufflenet_g3_w1': shufflenet_g3_w1, 'shufflenet_g4_w1': shufflenet_g4_w1, 'shufflenet_g8_w1': shufflenet_g8_w1, 'shufflenet_g1_w3d4': shufflenet_g1_w3d4, 'shufflenet_g3_w3d4': shufflenet_g3_w3d4, 'shufflenet_g1_wd2': shufflenet_g1_wd2, 'shufflenet_g3_wd2': shufflenet_g3_wd2, 'shufflenet_g1_wd4': shufflenet_g1_wd4, 'shufflenet_g3_wd4': shufflenet_g3_wd4, 'shufflenetv2_wd2': shufflenetv2_wd2, 'shufflenetv2_w1': shufflenetv2_w1, 'shufflenetv2_w3d2': shufflenetv2_w3d2, 'shufflenetv2_w2': shufflenetv2_w2, 'shufflenetv2b_wd2': shufflenetv2b_wd2, 'shufflenetv2b_w1': shufflenetv2b_w1, 'shufflenetv2b_w3d2': shufflenetv2b_w3d2, 'shufflenetv2b_w2': shufflenetv2b_w2, 'menet108_8x1_g3': menet108_8x1_g3, 'menet128_8x1_g4': menet128_8x1_g4, 'menet160_8x1_g8': menet160_8x1_g8, 'menet228_12x1_g3': menet228_12x1_g3, 'menet256_12x1_g4': menet256_12x1_g4, 'menet348_12x1_g3': menet348_12x1_g3, 'menet352_12x1_g8': menet352_12x1_g8, 'menet456_24x1_g3': menet456_24x1_g3, 'mobilenet_w1': mobilenet_w1, 'mobilenet_w3d4': mobilenet_w3d4, 'mobilenet_wd2': mobilenet_wd2, 'mobilenet_wd4': mobilenet_wd4, 'mobilenetb_w1': mobilenetb_w1, 'mobilenetb_w3d4': mobilenetb_w3d4, 'mobilenetb_wd2': mobilenetb_wd2, 'mobilenetb_wd4': mobilenetb_wd4, 'fdmobilenet_w1': fdmobilenet_w1, 'fdmobilenet_w3d4': fdmobilenet_w3d4, 'fdmobilenet_wd2': fdmobilenet_wd2, 'fdmobilenet_wd4': fdmobilenet_wd4, 'mobilenetv2_w1': mobilenetv2_w1, 'mobilenetv2_w3d4': mobilenetv2_w3d4, 'mobilenetv2_wd2': mobilenetv2_wd2, 'mobilenetv2_wd4': mobilenetv2_wd4, 'mobilenetv2b_w1': mobilenetv2b_w1, 'mobilenetv2b_w3d4': mobilenetv2b_w3d4, 'mobilenetv2b_wd2': mobilenetv2b_wd2, 'mobilenetv2b_wd4': mobilenetv2b_wd4, 'mobilenetv3_small_w7d20': mobilenetv3_small_w7d20, 'mobilenetv3_small_wd2': mobilenetv3_small_wd2, 'mobilenetv3_small_w3d4': mobilenetv3_small_w3d4, 'mobilenetv3_small_w1': mobilenetv3_small_w1, 'mobilenetv3_small_w5d4': mobilenetv3_small_w5d4, 'mobilenetv3_large_w7d20': mobilenetv3_large_w7d20, 'mobilenetv3_large_wd2': mobilenetv3_large_wd2, 'mobilenetv3_large_w3d4': mobilenetv3_large_w3d4, 'mobilenetv3_large_w1': mobilenetv3_large_w1, 'mobilenetv3_large_w5d4': mobilenetv3_large_w5d4, 'igcv3_w1': igcv3_w1, 'igcv3_w3d4': igcv3_w3d4, 'igcv3_wd2': igcv3_wd2, 'igcv3_wd4': igcv3_wd4, 'ghostnet': ghostnet, 'mnasnet_b1': mnasnet_b1, 'mnasnet_a1': mnasnet_a1, 'mnasnet_small': mnasnet_small, 'proxylessnas_cpu': proxylessnas_cpu, 'proxylessnas_gpu': proxylessnas_gpu, 'proxylessnas_mobile': proxylessnas_mobile, 'proxylessnas_mobile14': proxylessnas_mobile14, 'fbnet_cb': fbnet_cb, 'xception': xception, 'inceptionv3': inceptionv3, 'inceptionv4': inceptionv4, 'inceptionresnetv1': inceptionresnetv1, 'inceptionresnetv2': inceptionresnetv2, 'polynet': polynet, 'nasnet_4a1056': nasnet_4a1056, 'nasnet_6a4032': nasnet_6a4032, 'pnasnet5large': pnasnet5large, 'spnasnet': spnasnet, 'efficientnet_b0': efficientnet_b0, 'efficientnet_b1': efficientnet_b1, 'efficientnet_b2': efficientnet_b2, 'efficientnet_b3': efficientnet_b3, 'efficientnet_b4': efficientnet_b4, 'efficientnet_b5': efficientnet_b5, 'efficientnet_b6': efficientnet_b6, 'efficientnet_b7': efficientnet_b7, 'efficientnet_b8': efficientnet_b8, 'efficientnet_b0b': efficientnet_b0b, 'efficientnet_b1b': efficientnet_b1b, 'efficientnet_b2b': efficientnet_b2b, 'efficientnet_b3b': efficientnet_b3b, 'efficientnet_b4b': efficientnet_b4b, 'efficientnet_b5b': efficientnet_b5b, 'efficientnet_b6b': efficientnet_b6b, 'efficientnet_b7b': efficientnet_b7b, 'efficientnet_b0c': efficientnet_b0c, 'efficientnet_b1c': efficientnet_b1c, 'efficientnet_b2c': efficientnet_b2c, 'efficientnet_b3c': efficientnet_b3c, 'efficientnet_b4c': efficientnet_b4c, 'efficientnet_b5c': efficientnet_b5c, 'efficientnet_b6c': efficientnet_b6c, 'efficientnet_b7c': efficientnet_b7c, 'efficientnet_b8c': efficientnet_b8c, 'efficientnet_edge_small_b': efficientnet_edge_small_b, 'efficientnet_edge_medium_b': efficientnet_edge_medium_b, 'efficientnet_edge_large_b': efficientnet_edge_large_b, 'mixnet_s': mixnet_s, 'mixnet_m': mixnet_m, 'mixnet_l': mixnet_l, 'resnet20_cifar10': resnet20_cifar10, 'resnet20_cifar100': resnet20_cifar100, 'resnet20_svhn': resnet20_svhn, 'resnet56_cifar10': resnet56_cifar10, 'resnet56_cifar100': resnet56_cifar100, 'resnet56_svhn': resnet56_svhn, 'resnet110_cifar10': resnet110_cifar10, 'resnet110_cifar100': resnet110_cifar100, 'resnet110_svhn': resnet110_svhn, 'resnet164bn_cifar10': resnet164bn_cifar10, 'resnet164bn_cifar100': resnet164bn_cifar100, 'resnet164bn_svhn': resnet164bn_svhn, 'resnet272bn_cifar10': resnet272bn_cifar10, 'resnet272bn_cifar100': resnet272bn_cifar100, 'resnet272bn_svhn': resnet272bn_svhn, 'resnet542bn_cifar10': resnet542bn_cifar10, 'resnet542bn_cifar100': resnet542bn_cifar100, 'resnet542bn_svhn': resnet542bn_svhn, 'resnet1001_cifar10': resnet1001_cifar10, 'resnet1001_cifar100': resnet1001_cifar100, 'resnet1001_svhn': resnet1001_svhn, 'resnet1202_cifar10': resnet1202_cifar10, 'resnet1202_cifar100': resnet1202_cifar100, 'resnet1202_svhn': resnet1202_svhn, 'preresnet20_cifar10': preresnet20_cifar10, 'preresnet20_cifar100': preresnet20_cifar100, 'preresnet20_svhn': preresnet20_svhn, 'preresnet56_cifar10': preresnet56_cifar10, 'preresnet56_cifar100': preresnet56_cifar100, 'preresnet56_svhn': preresnet56_svhn, 'preresnet110_cifar10': preresnet110_cifar10, 'preresnet110_cifar100': preresnet110_cifar100, 'preresnet110_svhn': preresnet110_svhn, 'preresnet164bn_cifar10': preresnet164bn_cifar10, 'preresnet164bn_cifar100': preresnet164bn_cifar100, 'preresnet164bn_svhn': preresnet164bn_svhn, 'preresnet272bn_cifar10': preresnet272bn_cifar10, 'preresnet272bn_cifar100': preresnet272bn_cifar100, 'preresnet272bn_svhn': preresnet272bn_svhn, 'preresnet542bn_cifar10': preresnet542bn_cifar10, 'preresnet542bn_cifar100': preresnet542bn_cifar100, 'preresnet542bn_svhn': preresnet542bn_svhn, 'preresnet1001_cifar10': preresnet1001_cifar10, 'preresnet1001_cifar100': preresnet1001_cifar100, 'preresnet1001_svhn': preresnet1001_svhn, 'preresnet1202_cifar10': preresnet1202_cifar10, 'preresnet1202_cifar100': preresnet1202_cifar100, 'preresnet1202_svhn': preresnet1202_svhn, 'resnext20_1x64d_cifar10': resnext20_1x64d_cifar10, 'resnext20_1x64d_cifar100': resnext20_1x64d_cifar100, 'resnext20_1x64d_svhn': resnext20_1x64d_svhn, 'resnext20_2x32d_cifar10': resnext20_2x32d_cifar10, 'resnext20_2x32d_cifar100': resnext20_2x32d_cifar100, 'resnext20_2x32d_svhn': resnext20_2x32d_svhn, 'resnext20_2x64d_cifar10': resnext20_2x64d_cifar10, 'resnext20_2x64d_cifar100': resnext20_2x64d_cifar100, 'resnext20_2x64d_svhn': resnext20_2x64d_svhn, 'resnext20_4x16d_cifar10': resnext20_4x16d_cifar10, 'resnext20_4x16d_cifar100': resnext20_4x16d_cifar100, 'resnext20_4x16d_svhn': resnext20_4x16d_svhn, 'resnext20_4x32d_cifar10': resnext20_4x32d_cifar10, 'resnext20_4x32d_cifar100': resnext20_4x32d_cifar100, 'resnext20_4x32d_svhn': resnext20_4x32d_svhn, 'resnext20_8x8d_cifar10': resnext20_8x8d_cifar10, 'resnext20_8x8d_cifar100': resnext20_8x8d_cifar100, 'resnext20_8x8d_svhn': resnext20_8x8d_svhn, 'resnext20_8x16d_cifar10': resnext20_8x16d_cifar10, 'resnext20_8x16d_cifar100': resnext20_8x16d_cifar100, 'resnext20_8x16d_svhn': resnext20_8x16d_svhn, 'resnext20_16x4d_cifar10': resnext20_16x4d_cifar10, 'resnext20_16x4d_cifar100': resnext20_16x4d_cifar100, 'resnext20_16x4d_svhn': resnext20_16x4d_svhn, 'resnext20_16x8d_cifar10': resnext20_16x8d_cifar10, 'resnext20_16x8d_cifar100': resnext20_16x8d_cifar100, 'resnext20_16x8d_svhn': resnext20_16x8d_svhn, 'resnext20_32x2d_cifar10': resnext20_32x2d_cifar10, 'resnext20_32x2d_cifar100': resnext20_32x2d_cifar100, 'resnext20_32x2d_svhn': resnext20_32x2d_svhn, 'resnext20_32x4d_cifar10': resnext20_32x4d_cifar10, 'resnext20_32x4d_cifar100': resnext20_32x4d_cifar100, 'resnext20_32x4d_svhn': resnext20_32x4d_svhn, 'resnext20_64x1d_cifar10': resnext20_64x1d_cifar10, 'resnext20_64x1d_cifar100': resnext20_64x1d_cifar100, 'resnext20_64x1d_svhn': resnext20_64x1d_svhn, 'resnext20_64x2d_cifar10': resnext20_64x2d_cifar10, 'resnext20_64x2d_cifar100': resnext20_64x2d_cifar100, 'resnext20_64x2d_svhn': resnext20_64x2d_svhn, 'resnext29_32x4d_cifar10': resnext29_32x4d_cifar10, 'resnext29_32x4d_cifar100': resnext29_32x4d_cifar100, 'resnext29_32x4d_svhn': resnext29_32x4d_svhn, 'resnext29_16x64d_cifar10': resnext29_16x64d_cifar10, 'resnext29_16x64d_cifar100': resnext29_16x64d_cifar100, 'resnext29_16x64d_svhn': resnext29_16x64d_svhn, 'resnext56_1x64d_cifar10': resnext56_1x64d_cifar10, 'resnext56_1x64d_cifar100': resnext56_1x64d_cifar100, 'resnext56_1x64d_svhn': resnext56_1x64d_svhn, 'resnext56_2x32d_cifar10': resnext56_2x32d_cifar10, 'resnext56_2x32d_cifar100': resnext56_2x32d_cifar100, 'resnext56_2x32d_svhn': resnext56_2x32d_svhn, 'resnext56_4x16d_cifar10': resnext56_4x16d_cifar10, 'resnext56_4x16d_cifar100': resnext56_4x16d_cifar100, 'resnext56_4x16d_svhn': resnext56_4x16d_svhn, 'resnext56_8x8d_cifar10': resnext56_8x8d_cifar10, 'resnext56_8x8d_cifar100': resnext56_8x8d_cifar100, 'resnext56_8x8d_svhn': resnext56_8x8d_svhn, 'resnext56_16x4d_cifar10': resnext56_16x4d_cifar10, 'resnext56_16x4d_cifar100': resnext56_16x4d_cifar100, 'resnext56_16x4d_svhn': resnext56_16x4d_svhn, 'resnext56_32x2d_cifar10': resnext56_32x2d_cifar10, 'resnext56_32x2d_cifar100': resnext56_32x2d_cifar100, 'resnext56_32x2d_svhn': resnext56_32x2d_svhn, 'resnext56_64x1d_cifar10': resnext56_64x1d_cifar10, 'resnext56_64x1d_cifar100': resnext56_64x1d_cifar100, 'resnext56_64x1d_svhn': resnext56_64x1d_svhn, 'resnext272_1x64d_cifar10': resnext272_1x64d_cifar10, 'resnext272_1x64d_cifar100': resnext272_1x64d_cifar100, 'resnext272_1x64d_svhn': resnext272_1x64d_svhn, 'resnext272_2x32d_cifar10': resnext272_2x32d_cifar10, 'resnext272_2x32d_cifar100': resnext272_2x32d_cifar100, 'resnext272_2x32d_svhn': resnext272_2x32d_svhn, 'seresnet20_cifar10': seresnet20_cifar10, 'seresnet20_cifar100': seresnet20_cifar100, 'seresnet20_svhn': seresnet20_svhn, 'seresnet56_cifar10': seresnet56_cifar10, 'seresnet56_cifar100': seresnet56_cifar100, 'seresnet56_svhn': seresnet56_svhn, 'seresnet110_cifar10': seresnet110_cifar10, 'seresnet110_cifar100': seresnet110_cifar100, 'seresnet110_svhn': seresnet110_svhn, 'seresnet164bn_cifar10': seresnet164bn_cifar10, 'seresnet164bn_cifar100': seresnet164bn_cifar100, 'seresnet164bn_svhn': seresnet164bn_svhn, 'seresnet272bn_cifar10': seresnet272bn_cifar10, 'seresnet272bn_cifar100': seresnet272bn_cifar100, 'seresnet272bn_svhn': seresnet272bn_svhn, 'seresnet542bn_cifar10': seresnet542bn_cifar10, 'seresnet542bn_cifar100': seresnet542bn_cifar100, 'seresnet542bn_svhn': seresnet542bn_svhn, 'seresnet1001_cifar10': seresnet1001_cifar10, 'seresnet1001_cifar100': seresnet1001_cifar100, 'seresnet1001_svhn': seresnet1001_svhn, 'seresnet1202_cifar10': seresnet1202_cifar10, 'seresnet1202_cifar100': seresnet1202_cifar100, 'seresnet1202_svhn': seresnet1202_svhn, 'sepreresnet20_cifar10': sepreresnet20_cifar10, 'sepreresnet20_cifar100': sepreresnet20_cifar100, 'sepreresnet20_svhn': sepreresnet20_svhn, 'sepreresnet56_cifar10': sepreresnet56_cifar10, 'sepreresnet56_cifar100': sepreresnet56_cifar100, 'sepreresnet56_svhn': sepreresnet56_svhn, 'sepreresnet110_cifar10': sepreresnet110_cifar10, 'sepreresnet110_cifar100': sepreresnet110_cifar100, 'sepreresnet110_svhn': sepreresnet110_svhn, 'sepreresnet164bn_cifar10': sepreresnet164bn_cifar10, 'sepreresnet164bn_cifar100': sepreresnet164bn_cifar100, 'sepreresnet164bn_svhn': sepreresnet164bn_svhn, 'sepreresnet272bn_cifar10': sepreresnet272bn_cifar10, 'sepreresnet272bn_cifar100': sepreresnet272bn_cifar100, 'sepreresnet272bn_svhn': sepreresnet272bn_svhn, 'sepreresnet542bn_cifar10': sepreresnet542bn_cifar10, 'sepreresnet542bn_cifar100': sepreresnet542bn_cifar100, 'sepreresnet542bn_svhn': sepreresnet542bn_svhn, 'sepreresnet1001_cifar10': sepreresnet1001_cifar10, 'sepreresnet1001_cifar100': sepreresnet1001_cifar100, 'sepreresnet1001_svhn': sepreresnet1001_svhn, 'sepreresnet1202_cifar10': sepreresnet1202_cifar10, 'sepreresnet1202_cifar100': sepreresnet1202_cifar100, 'sepreresnet1202_svhn': sepreresnet1202_svhn, 'pyramidnet110_a48_cifar10': pyramidnet110_a48_cifar10, 'pyramidnet110_a48_cifar100': pyramidnet110_a48_cifar100, 'pyramidnet110_a48_svhn': pyramidnet110_a48_svhn, 'pyramidnet110_a84_cifar10': pyramidnet110_a84_cifar10, 'pyramidnet110_a84_cifar100': pyramidnet110_a84_cifar100, 'pyramidnet110_a84_svhn': pyramidnet110_a84_svhn, 'pyramidnet110_a270_cifar10': pyramidnet110_a270_cifar10, 'pyramidnet110_a270_cifar100': pyramidnet110_a270_cifar100, 'pyramidnet110_a270_svhn': pyramidnet110_a270_svhn, 'pyramidnet164_a270_bn_cifar10': pyramidnet164_a270_bn_cifar10, 'pyramidnet164_a270_bn_cifar100': pyramidnet164_a270_bn_cifar100, 'pyramidnet164_a270_bn_svhn': pyramidnet164_a270_bn_svhn, 'pyramidnet200_a240_bn_cifar10': pyramidnet200_a240_bn_cifar10, 'pyramidnet200_a240_bn_cifar100': pyramidnet200_a240_bn_cifar100, 'pyramidnet200_a240_bn_svhn': pyramidnet200_a240_bn_svhn, 'pyramidnet236_a220_bn_cifar10': pyramidnet236_a220_bn_cifar10, 'pyramidnet236_a220_bn_cifar100': pyramidnet236_a220_bn_cifar100, 'pyramidnet236_a220_bn_svhn': pyramidnet236_a220_bn_svhn, 'pyramidnet272_a200_bn_cifar10': pyramidnet272_a200_bn_cifar10, 'pyramidnet272_a200_bn_cifar100': pyramidnet272_a200_bn_cifar100, 'pyramidnet272_a200_bn_svhn': pyramidnet272_a200_bn_svhn, 'densenet40_k12_cifar10': densenet40_k12_cifar10, 'densenet40_k12_cifar100': densenet40_k12_cifar100, 'densenet40_k12_svhn': densenet40_k12_svhn, 'densenet40_k12_bc_cifar10': densenet40_k12_bc_cifar10, 'densenet40_k12_bc_cifar100': densenet40_k12_bc_cifar100, 'densenet40_k12_bc_svhn': densenet40_k12_bc_svhn, 'densenet40_k24_bc_cifar10': densenet40_k24_bc_cifar10, 'densenet40_k24_bc_cifar100': densenet40_k24_bc_cifar100, 'densenet40_k24_bc_svhn': densenet40_k24_bc_svhn, 'densenet40_k36_bc_cifar10': densenet40_k36_bc_cifar10, 'densenet40_k36_bc_cifar100': densenet40_k36_bc_cifar100, 'densenet40_k36_bc_svhn': densenet40_k36_bc_svhn, 'densenet100_k12_cifar10': densenet100_k12_cifar10, 'densenet100_k12_cifar100': densenet100_k12_cifar100, 'densenet100_k12_svhn': densenet100_k12_svhn, 'densenet100_k24_cifar10': densenet100_k24_cifar10, 'densenet100_k24_cifar100': densenet100_k24_cifar100, 'densenet100_k24_svhn': densenet100_k24_svhn, 'densenet100_k12_bc_cifar10': densenet100_k12_bc_cifar10, 'densenet100_k12_bc_cifar100': densenet100_k12_bc_cifar100, 'densenet100_k12_bc_svhn': densenet100_k12_bc_svhn, 'densenet190_k40_bc_cifar10': densenet190_k40_bc_cifar10, 'densenet190_k40_bc_cifar100': densenet190_k40_bc_cifar100, 'densenet190_k40_bc_svhn': densenet190_k40_bc_svhn, 'densenet250_k24_bc_cifar10': densenet250_k24_bc_cifar10, 'densenet250_k24_bc_cifar100': densenet250_k24_bc_cifar100, 'densenet250_k24_bc_svhn': densenet250_k24_bc_svhn, 'wrn16_10_cifar10': wrn16_10_cifar10, 'wrn16_10_cifar100': wrn16_10_cifar100, 'wrn16_10_svhn': wrn16_10_svhn, 'wrn28_10_cifar10': wrn28_10_cifar10, 'wrn28_10_cifar100': wrn28_10_cifar100, 'wrn28_10_svhn': wrn28_10_svhn, 'wrn40_8_cifar10': wrn40_8_cifar10, 'wrn40_8_cifar100': wrn40_8_cifar100, 'wrn40_8_svhn': wrn40_8_svhn, 'resneta10': resneta10, 'resnetabc14b': resnetabc14b, 'resneta18': resneta18, 'resneta50b': resneta50b, 'resneta101b': resneta101b, 'resneta152b': resneta152b, 'resnetd50b': resnetd50b, 'resnetd101b': resnetd101b, 'resnetd152b': resnetd152b, 'fastseresnet101b': fastseresnet101b, 'resnet10_cub': resnet10_cub, 'resnet12_cub': resnet12_cub, 'resnet14_cub': resnet14_cub, 'resnetbc14b_cub': resnetbc14b_cub, 'resnet16_cub': resnet16_cub, 'resnet18_cub': resnet18_cub, 'resnet26_cub': resnet26_cub, 'resnetbc26b_cub': resnetbc26b_cub, 'resnet34_cub': resnet34_cub, 'resnetbc38b_cub': resnetbc38b_cub, 'resnet50_cub': resnet50_cub, 'resnet50b_cub': resnet50b_cub, 'resnet101_cub': resnet101_cub, 'resnet101b_cub': resnet101b_cub, 'resnet152_cub': resnet152_cub, 'resnet152b_cub': resnet152b_cub, 'resnet200_cub': resnet200_cub, 'resnet200b_cub': resnet200b_cub, 'seresnet10_cub': seresnet10_cub, 'seresnet12_cub': seresnet12_cub, 'seresnet14_cub': seresnet14_cub, 'seresnetbc14b_cub': seresnetbc14b_cub, 'seresnet16_cub': seresnet16_cub, 'seresnet18_cub': seresnet18_cub, 'seresnet26_cub': seresnet26_cub, 'seresnetbc26b_cub': seresnetbc26b_cub, 'seresnet34_cub': seresnet34_cub, 'seresnetbc38b_cub': seresnetbc38b_cub, 'seresnet50_cub': seresnet50_cub, 'seresnet50b_cub': seresnet50b_cub, 'seresnet101_cub': seresnet101_cub, 'seresnet101b_cub': seresnet101b_cub, 'seresnet152_cub': seresnet152_cub, 'seresnet152b_cub': seresnet152b_cub, 'seresnet200_cub': seresnet200_cub, 'seresnet200b_cub': seresnet200b_cub, 'mobilenet_w1_cub': mobilenet_w1_cub, 'mobilenet_w3d4_cub': mobilenet_w3d4_cub, 'mobilenet_wd2_cub': mobilenet_wd2_cub, 'mobilenet_wd4_cub': mobilenet_wd4_cub, 'fdmobilenet_w1_cub': fdmobilenet_w1_cub, 'fdmobilenet_w3d4_cub': fdmobilenet_w3d4_cub, 'fdmobilenet_wd2_cub': fdmobilenet_wd2_cub, 'fdmobilenet_wd4_cub': fdmobilenet_wd4_cub, 'proxylessnas_cpu_cub': proxylessnas_cpu_cub, 'proxylessnas_gpu_cub': proxylessnas_gpu_cub, 'proxylessnas_mobile_cub': proxylessnas_mobile_cub, 'proxylessnas_mobile14_cub': proxylessnas_mobile14_cub, 'fcn8sd_resnetd50b_voc': fcn8sd_resnetd50b_voc, 'fcn8sd_resnetd101b_voc': fcn8sd_resnetd101b_voc, 'fcn8sd_resnetd50b_coco': fcn8sd_resnetd50b_coco, 'fcn8sd_resnetd101b_coco': fcn8sd_resnetd101b_coco, 'fcn8sd_resnetd50b_ade20k': fcn8sd_resnetd50b_ade20k, 'fcn8sd_resnetd101b_ade20k': fcn8sd_resnetd101b_ade20k, 'fcn8sd_resnetd50b_cityscapes': fcn8sd_resnetd50b_cityscapes, 'fcn8sd_resnetd101b_cityscapes': fcn8sd_resnetd101b_cityscapes, 'pspnet_resnetd50b_voc': pspnet_resnetd50b_voc, 'pspnet_resnetd101b_voc': pspnet_resnetd101b_voc, 'pspnet_resnetd50b_coco': pspnet_resnetd50b_coco, 'pspnet_resnetd101b_coco': pspnet_resnetd101b_coco, 'pspnet_resnetd50b_ade20k': pspnet_resnetd50b_ade20k, 'pspnet_resnetd101b_ade20k': pspnet_resnetd101b_ade20k, 'pspnet_resnetd50b_cityscapes': pspnet_resnetd50b_cityscapes, 'pspnet_resnetd101b_cityscapes': pspnet_resnetd101b_cityscapes, 'deeplabv3_resnetd50b_voc': deeplabv3_resnetd50b_voc, 'deeplabv3_resnetd101b_voc': deeplabv3_resnetd101b_voc, 'deeplabv3_resnetd152b_voc': deeplabv3_resnetd152b_voc, 'deeplabv3_resnetd50b_coco': deeplabv3_resnetd50b_coco, 'deeplabv3_resnetd101b_coco': deeplabv3_resnetd101b_coco, 'deeplabv3_resnetd152b_coco': deeplabv3_resnetd152b_coco, 'deeplabv3_resnetd50b_ade20k': deeplabv3_resnetd50b_ade20k, 'deeplabv3_resnetd101b_ade20k': deeplabv3_resnetd101b_ade20k, 'deeplabv3_resnetd50b_cityscapes': deeplabv3_resnetd50b_cityscapes, 'deeplabv3_resnetd101b_cityscapes': deeplabv3_resnetd101b_cityscapes, 'icnet_resnetd50b_cityscapes': icnet_resnetd50b_cityscapes, 'fastscnn_cityscapes': fastscnn_cityscapes, 'cgnet_cityscapes': cgnet_cityscapes, 'dabnet_cityscapes': dabnet_cityscapes, 'sinet_cityscapes': sinet_cityscapes, 'bisenet_resnet18_celebamaskhq': bisenet_resnet18_celebamaskhq, 'danet_resnetd50b_cityscapes': danet_resnetd50b_cityscapes, 'danet_resnetd101b_cityscapes': danet_resnetd101b_cityscapes, 'fpenet_cityscapes': fpenet_cityscapes, 'lednet_cityscapes': lednet_cityscapes, 'alphapose_fastseresnet101b_coco': alphapose_fastseresnet101b_coco, 'simplepose_resnet18_coco': simplepose_resnet18_coco, 'simplepose_resnet50b_coco': simplepose_resnet50b_coco, 'simplepose_resnet101b_coco': simplepose_resnet101b_coco, 'simplepose_resnet152b_coco': simplepose_resnet152b_coco, 'simplepose_resneta50b_coco': simplepose_resneta50b_coco, 'simplepose_resneta101b_coco': simplepose_resneta101b_coco, 'simplepose_resneta152b_coco': simplepose_resneta152b_coco, 'simplepose_mobile_resnet18_coco': simplepose_mobile_resnet18_coco, 'simplepose_mobile_resnet50b_coco': simplepose_mobile_resnet50b_coco, 'simplepose_mobile_mobilenet_w1_coco': simplepose_mobile_mobilenet_w1_coco, 'simplepose_mobile_mobilenetv2b_w1_coco': simplepose_mobile_mobilenetv2b_w1_coco, 'simplepose_mobile_mobilenetv3_small_w1_coco': simplepose_mobile_mobilenetv3_small_w1_coco, 'simplepose_mobile_mobilenetv3_large_w1_coco': simplepose_mobile_mobilenetv3_large_w1_coco, 'lwopenpose2d_mobilenet_cmupan_coco': lwopenpose2d_mobilenet_cmupan_coco, 'lwopenpose3d_mobilenet_cmupan_coco': lwopenpose3d_mobilenet_cmupan_coco, 'ibppose_coco': ibppose_coco, 'grmiposelite_mobilenet_w1_coco': grmiposelite_mobilenet_w1_coco, 'centernet_resnet18_voc': centernet_resnet18_voc, 'centernet_resnet18_coco': centernet_resnet18_coco, 'centernet_resnet50b_voc': centernet_resnet50b_voc, 'centernet_resnet50b_coco': centernet_resnet50b_coco, 'centernet_resnet101b_voc': centernet_resnet101b_voc, 'centernet_resnet101b_coco': centernet_resnet101b_coco, 'lffd20x5s320v2_widerface': lffd20x5s320v2_widerface, 'lffd25x8s560v1_widerface': lffd25x8s560v1_widerface, 'voca8flame': voca8flame, 'nvpattexp116bazel76': nvpattexp116bazel76, 'jasper5x3': jasper5x3, 'jasper10x4': jasper10x4, 'jasper10x5': jasper10x5, 'jasperdr10x5_en': jasperdr10x5_en, 'jasperdr10x5_en_nr': jasperdr10x5_en_nr, 'quartznet5x5_en_ls': quartznet5x5_en_ls, 'quartznet15x5_en': quartznet15x5_en, 'quartznet15x5_en_nr': quartznet15x5_en_nr, 'quartznet15x5_fr': quartznet15x5_fr, 'quartznet15x5_de': quartznet15x5_de, 'quartznet15x5_it': quartznet15x5_it, 'quartznet15x5_es': quartznet15x5_es, 'quartznet15x5_ca': quartznet15x5_ca, 'quartznet15x5_pl': quartznet15x5_pl, 'quartznet15x5_ru': quartznet15x5_ru, 'quartznet15x5_ru34': quartznet15x5_ru34, } def get_model(name, **kwargs): """ Get supported model. Parameters: ---------- name : str Name of model. Returns: ------- Module Resulted model. """ name = name.lower() if name not in _models: raise ValueError("Unsupported model: {}".format(name)) net = _models[name](**kwargs) return net
35,437
35.458848
95
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/airnext.py
""" AirNeXt for ImageNet-1K, implemented in TensorFlow. Original paper: 'Attention Inspiring Receptive-Fields Network for Learning Invariant Representations,' https://ieeexplore.ieee.org/document/8510896. """ __all__ = ['AirNeXt', 'airnext50_32x4d_r2', 'airnext101_32x4d_r2', 'airnext101_32x4d_r16'] import os import math import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1_block, conv3x3_block, SimpleSequential, flatten, is_channels_first from .airnet import AirBlock, AirInitBlock class AirNeXtBottleneck(nn.Layer): """ AirNet bottleneck block for residual path in 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. cardinality: int Number of groups. bottleneck_width: int Width of bottleneck block. ratio: int Air compression ratio. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, cardinality, bottleneck_width, ratio, data_format="channels_last", **kwargs): super(AirNeXtBottleneck, self).__init__(**kwargs) mid_channels = out_channels // 4 D = int(math.floor(mid_channels * (bottleneck_width / 64.0))) group_width = cardinality * D self.use_air_block = (strides == 1 and mid_channels < 512) self.conv1 = conv1x1_block( in_channels=in_channels, out_channels=group_width, data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=group_width, out_channels=group_width, strides=strides, groups=cardinality, data_format=data_format, name="conv2") self.conv3 = conv1x1_block( in_channels=group_width, out_channels=out_channels, activation=None, data_format=data_format, name="conv3") if self.use_air_block: self.air = AirBlock( in_channels=in_channels, out_channels=group_width, groups=(cardinality // ratio), ratio=ratio, data_format=data_format, name="air") def call(self, x, training=None): if self.use_air_block: att = self.air(x, training=training) x = self.conv1(x, training=training) x = self.conv2(x, training=training) if self.use_air_block: x = x * att x = self.conv3(x, training=training) return x class AirNeXtUnit(nn.Layer): """ AirNet 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. ratio: int Air compression ratio. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, cardinality, bottleneck_width, ratio, data_format="channels_last", **kwargs): super(AirNeXtUnit, self).__init__(**kwargs) self.resize_identity = (in_channels != out_channels) or (strides != 1) self.body = AirNeXtBottleneck( in_channels=in_channels, out_channels=out_channels, strides=strides, cardinality=cardinality, bottleneck_width=bottleneck_width, ratio=ratio, data_format=data_format, name="body") if self.resize_identity: self.identity_conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, strides=strides, activation=None, data_format=data_format, name="identity_conv") self.activ = nn.ReLU() def call(self, x, training=None): if self.resize_identity: identity = self.identity_conv(x, training=training) else: identity = x x = self.body(x, training=training) x = x + identity x = self.activ(x) return x class AirNeXt(tf.keras.Model): """ AirNet model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant Representations,' https://ieeexplore.ieee.org/document/8510896. 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. ratio: int Air compression ratio. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, cardinality, bottleneck_width, ratio, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(AirNeXt, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(AirInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(AirNeXtUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, cardinality=cardinality, bottleneck_width=bottleneck_width, ratio=ratio, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_airnext(blocks, cardinality, bottleneck_width, base_channels, ratio, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create AirNet model with specific parameters. Parameters: ---------- blocks : int Number of blocks. cardinality: int Number of groups. bottleneck_width: int Width of bottleneck block. base_channels: int Base number of channels. ratio: int Air compression ratio. 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if blocks == 50: layers = [3, 4, 6, 3] elif blocks == 101: layers = [3, 4, 23, 3] else: raise ValueError("Unsupported AirNeXt with number of blocks: {}".format(blocks)) bottleneck_expansion = 4 init_block_channels = base_channels channels_per_layers = [base_channels * (2 ** i) * bottleneck_expansion for i in range(len(layers))] channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)] net = AirNeXt( channels=channels, init_block_channels=init_block_channels, cardinality=cardinality, bottleneck_width=bottleneck_width, ratio=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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def airnext50_32x4d_r2(**kwargs): """ AirNeXt50-32x4d (r=2) model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant Representations,' https://ieeexplore.ieee.org/document/8510896. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_airnext( blocks=50, cardinality=32, bottleneck_width=4, base_channels=64, ratio=2, model_name="airnext50_32x4d_r2", **kwargs) def airnext101_32x4d_r2(**kwargs): """ AirNeXt101-32x4d (r=2) model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant Representations,' https://ieeexplore.ieee.org/document/8510896. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_airnext( blocks=101, cardinality=32, bottleneck_width=4, base_channels=64, ratio=2, model_name="airnext101_32x4d_r2", **kwargs) def airnext101_32x4d_r16(**kwargs): """ AirNeXt101-32x4d (r=16) model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant Representations,' https://ieeexplore.ieee.org/document/8510896. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_airnext( blocks=101, cardinality=32, bottleneck_width=4, base_channels=64, ratio=16, model_name="airnext101_32x4d_r16", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ airnext50_32x4d_r2, airnext101_32x4d_r2, airnext101_32x4d_r16, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != airnext50_32x4d_r2 or weight_count == 27604296) assert (model != airnext101_32x4d_r2 or weight_count == 54099272) assert (model != airnext101_32x4d_r16 or weight_count == 45456456) if __name__ == "__main__": _test()
12,866
31.087282
115
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/pspnet.py
""" PSPNet for image segmentation, implemented in TensorFlow. Original paper: 'Pyramid Scene Parsing Network,' https://arxiv.org/abs/1612.01105. """ __all__ = ['PSPNet', 'pspnet_resnetd50b_voc', 'pspnet_resnetd101b_voc', 'pspnet_resnetd50b_coco', 'pspnet_resnetd101b_coco', 'pspnet_resnetd50b_ade20k', 'pspnet_resnetd101b_ade20k', 'pspnet_resnetd50b_cityscapes', 'pspnet_resnetd101b_cityscapes', 'PyramidPooling'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1, conv1x1_block, conv3x3_block, Concurrent, Identity, is_channels_first, interpolate_im,\ get_im_size from .resnetd import resnetd50b, resnetd101b class PSPFinalBlock(nn.Layer): """ PSPNet final block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. bottleneck_factor : int, default 4 Bottleneck factor. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, bottleneck_factor=4, data_format="channels_last", **kwargs): super(PSPFinalBlock, self).__init__(**kwargs) assert (in_channels % bottleneck_factor == 0) self.data_format = data_format mid_channels = in_channels // bottleneck_factor self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv1") self.dropout = nn.Dropout( rate=0.1, name="dropout") self.conv2 = conv1x1( in_channels=mid_channels, out_channels=out_channels, use_bias=True, data_format=data_format, name="conv2") def call(self, x, out_size, training=None): x = self.conv1(x, training=training) x = self.dropout(x, training=training) x = self.conv2(x) x = interpolate_im(x, out_size=out_size, data_format=self.data_format) return x class PyramidPoolingBranch(nn.Layer): """ Pyramid Pooling branch. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. pool_out_size : int Target output size of the image. upscale_out_size : tuple of 2 int or None Spatial size of output image for the bilinear upsampling operation. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, pool_out_size, upscale_out_size, data_format="channels_last", **kwargs): super(PyramidPoolingBranch, self).__init__(**kwargs) self.upscale_out_size = upscale_out_size self.data_format = data_format self.pool = nn.AveragePooling2D( pool_size=pool_out_size, data_format=data_format, name="pool") self.conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, data_format=data_format, name="conv") def call(self, x, training=None): in_size = self.upscale_out_size if self.upscale_out_size is not None else\ get_im_size(x, data_format=self.data_format) x = self.pool(x) x = self.conv(x, training=training) x = interpolate_im(x, out_size=in_size, data_format=self.data_format) return x class PyramidPooling(nn.Layer): """ Pyramid Pooling 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, upscale_out_size, data_format="channels_last", **kwargs): super(PyramidPooling, self).__init__(**kwargs) pool_out_sizes = [1, 2, 3, 6] assert (len(pool_out_sizes) == 4) assert (in_channels % 4 == 0) mid_channels = in_channels // 4 self.branches = Concurrent( data_format=data_format, name="branches") self.branches.add(Identity(name="branch1")) for i, pool_out_size in enumerate(pool_out_sizes): self.branches.add(PyramidPoolingBranch( in_channels=in_channels, out_channels=mid_channels, pool_out_size=pool_out_size, upscale_out_size=upscale_out_size, data_format=data_format, name="branch{}".format(i + 2))) def call(self, x, training=None): x = self.branches(x, training=training) return x class PSPNet(tf.keras.Model): """ PSPNet model from 'Pyramid Scene Parsing Network,' https://arxiv.org/abs/1612.01105. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, backbone, backbone_out_channels=2048, aux=False, fixed_size=True, in_channels=3, in_size=(480, 480), classes=21, data_format="channels_last", **kwargs): super(PSPNet, 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 self.data_format = data_format self.backbone = backbone pool_out_size = (self.in_size[0] // 8, self.in_size[1] // 8) if fixed_size else None self.pool = PyramidPooling( in_channels=backbone_out_channels, upscale_out_size=pool_out_size, data_format=data_format, name="pool") pool_out_channels = 2 * backbone_out_channels self.final_block = PSPFinalBlock( in_channels=pool_out_channels, out_channels=classes, bottleneck_factor=8, data_format=data_format, name="final_block") if self.aux: aux_out_channels = backbone_out_channels // 2 self.aux_block = PSPFinalBlock( in_channels=aux_out_channels, out_channels=classes, bottleneck_factor=4, data_format=data_format, name="aux_block") def call(self, x, training=None): in_size = self.in_size if self.fixed_size else get_im_size(x, data_format=self.data_format) x, y = self.backbone(x, training=training) x = self.pool(x, training=training) x = self.final_block(x, in_size, training=training) if self.aux: y = self.aux_block(y, in_size, training=training) return x, y else: return x def get_pspnet(backbone, classes, aux=False, model_name=None, data_format="channels_last", pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create PSPNet 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ net = PSPNet( backbone=backbone, classes=classes, aux=aux, data_format=data_format, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root), by_name=True, skip_mismatch=True) return net def pspnet_resnetd50b_voc(pretrained_backbone=False, classes=21, aux=True, data_format="channels_last", **kwargs): """ PSPNet model on the base of ResNet(D)-50b for Pascal VOC from 'Pyramid Scene Parsing Network,' https://arxiv.org/abs/1612.01105. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_pspnet(backbone=backbone, classes=classes, aux=aux, model_name="pspnet_resnetd50b_voc", data_format=data_format, **kwargs) def pspnet_resnetd101b_voc(pretrained_backbone=False, classes=21, aux=True, data_format="channels_last", **kwargs): """ PSPNet model on the base of ResNet(D)-101b for Pascal VOC from 'Pyramid Scene Parsing Network,' https://arxiv.org/abs/1612.01105. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_pspnet(backbone=backbone, classes=classes, aux=aux, model_name="pspnet_resnetd101b_voc", data_format=data_format, **kwargs) def pspnet_resnetd50b_coco(pretrained_backbone=False, classes=21, aux=True, data_format="channels_last", **kwargs): """ PSPNet model on the base of ResNet(D)-50b for COCO from 'Pyramid Scene Parsing Network,' https://arxiv.org/abs/1612.01105. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_pspnet(backbone=backbone, classes=classes, aux=aux, model_name="pspnet_resnetd50b_coco", data_format=data_format, **kwargs) def pspnet_resnetd101b_coco(pretrained_backbone=False, classes=21, aux=True, data_format="channels_last", **kwargs): """ PSPNet model on the base of ResNet(D)-101b for COCO from 'Pyramid Scene Parsing Network,' https://arxiv.org/abs/1612.01105. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_pspnet(backbone=backbone, classes=classes, aux=aux, model_name="pspnet_resnetd101b_coco", data_format=data_format, **kwargs) def pspnet_resnetd50b_ade20k(pretrained_backbone=False, classes=150, aux=True, data_format="channels_last", **kwargs): """ PSPNet model on the base of ResNet(D)-50b for ADE20K from 'Pyramid Scene Parsing Network,' https://arxiv.org/abs/1612.01105. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_pspnet(backbone=backbone, classes=classes, aux=aux, model_name="pspnet_resnetd50b_ade20k", data_format=data_format, **kwargs) def pspnet_resnetd101b_ade20k(pretrained_backbone=False, classes=150, aux=True, data_format="channels_last", **kwargs): """ PSPNet model on the base of ResNet(D)-101b for ADE20K from 'Pyramid Scene Parsing Network,' https://arxiv.org/abs/1612.01105. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_pspnet(backbone=backbone, classes=classes, aux=aux, model_name="pspnet_resnetd101b_ade20k", data_format=data_format, **kwargs) def pspnet_resnetd50b_cityscapes(pretrained_backbone=False, classes=19, aux=True, data_format="channels_last", **kwargs): """ PSPNet model on the base of ResNet(D)-50b for Cityscapes from 'Pyramid Scene Parsing Network,' https://arxiv.org/abs/1612.01105. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_pspnet(backbone=backbone, classes=classes, aux=aux, model_name="pspnet_resnetd50b_cityscapes", data_format=data_format, **kwargs) def pspnet_resnetd101b_cityscapes(pretrained_backbone=False, classes=19, aux=True, data_format="channels_last", **kwargs): """ PSPNet model on the base of ResNet(D)-101b for Cityscapes from 'Pyramid Scene Parsing Network,' https://arxiv.org/abs/1612.01105. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_pspnet(backbone=backbone, classes=classes, aux=aux, model_name="pspnet_resnetd101b_cityscapes", data_format=data_format, **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" in_size = (480, 480) aux = False pretrained = False models = [ (pspnet_resnetd50b_voc, 21), (pspnet_resnetd101b_voc, 21), (pspnet_resnetd50b_coco, 21), (pspnet_resnetd101b_coco, 21), (pspnet_resnetd50b_ade20k, 150), (pspnet_resnetd101b_ade20k, 150), (pspnet_resnetd50b_cityscapes, 19), (pspnet_resnetd101b_cityscapes, 19), ] for model, classes in models: net = model(pretrained=pretrained, in_size=in_size, aux=aux, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, in_size[0], in_size[1]) if is_channels_first(data_format) else (batch, in_size[0], in_size[1], 3)) ys = net(x) y = ys[0] if aux else ys assert (y.shape[0] == x.shape[0]) if is_channels_first(data_format): assert ((y.shape[1] == classes) and (y.shape[2] == x.shape[2]) and (y.shape[3] == x.shape[3])) else: assert ((y.shape[3] == classes) and (y.shape[1] == x.shape[1]) and (y.shape[2] == x.shape[2])) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) if aux: assert (model != pspnet_resnetd50b_voc or weight_count == 49081578) assert (model != pspnet_resnetd101b_voc or weight_count == 68073706) assert (model != pspnet_resnetd50b_coco or weight_count == 49081578) assert (model != pspnet_resnetd101b_coco or weight_count == 68073706) assert (model != pspnet_resnetd50b_ade20k or weight_count == 49180908) assert (model != pspnet_resnetd101b_ade20k or weight_count == 68173036) assert (model != pspnet_resnetd50b_cityscapes or weight_count == 49080038) assert (model != pspnet_resnetd101b_cityscapes or weight_count == 68072166) else: assert (model != pspnet_resnetd50b_voc or weight_count == 46716373) assert (model != pspnet_resnetd101b_voc or weight_count == 65708501) assert (model != pspnet_resnetd50b_coco or weight_count == 46716373) assert (model != pspnet_resnetd101b_coco or weight_count == 65708501) assert (model != pspnet_resnetd50b_ade20k or weight_count == 46782550) assert (model != pspnet_resnetd101b_ade20k or weight_count == 65774678) assert (model != pspnet_resnetd50b_cityscapes or weight_count == 46715347) assert (model != pspnet_resnetd101b_cityscapes or weight_count == 65707475) if __name__ == "__main__": _test()
22,270
38.487589
119
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/dla.py
""" DLA for ImageNet-1K, implemented in TensorFlow. Original paper: 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484. """ __all__ = ['DLA', 'dla34', 'dla46c', 'dla46xc', 'dla60', 'dla60x', 'dla60xc', 'dla102', 'dla102x', 'dla102x2', 'dla169'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1, conv1x1_block, conv3x3_block, conv7x7_block, SimpleSequential, flatten, is_channels_first,\ get_channel_axis from .resnet import ResBlock, ResBottleneck from .resnext import ResNeXtBottleneck class DLABottleneck(ResBottleneck): """ DLA bottleneck block for residual path in residual 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. bottleneck_factor : int, default 2 Bottleneck factor. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, bottleneck_factor=2, data_format="channels_last", **kwargs): super(DLABottleneck, self).__init__( in_channels=in_channels, out_channels=out_channels, strides=strides, bottleneck_factor=bottleneck_factor, data_format=data_format, **kwargs) class DLABottleneckX(ResNeXtBottleneck): """ DLA ResNeXt-like bottleneck block for residual path in residual 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, default 32 Number of groups. bottleneck_width: int, default 8 Width of bottleneck block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, cardinality=32, bottleneck_width=8, data_format="channels_last", **kwargs): super(DLABottleneckX, self).__init__( in_channels=in_channels, out_channels=out_channels, strides=strides, cardinality=cardinality, bottleneck_width=bottleneck_width, data_format=data_format, **kwargs) class DLAResBlock(nn.Layer): """ DLA residual block 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. body_class : nn.Module, default ResBlock Residual block body class. return_down : bool, default False Whether return downsample result. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, body_class=ResBlock, return_down=False, data_format="channels_last", **kwargs): super(DLAResBlock, self).__init__(**kwargs) self.return_down = return_down self.downsample = (strides > 1) self.project = (in_channels != out_channels) self.body = body_class( in_channels=in_channels, out_channels=out_channels, strides=strides, data_format=data_format, name="body") self.activ = nn.ReLU() if self.downsample: self.downsample_pool = nn.MaxPool2D( pool_size=strides, strides=strides, data_format=data_format, name="downsample_pool") if self.project: self.project_conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, activation=None, data_format=data_format, name="project_conv") def call(self, x, training=None): down = self.downsample_pool(x) if self.downsample else x identity = self.project_conv(down, training=training) if self.project else down if identity is None: identity = x x = self.body(x, training=training) x = x + identity x = self.activ(x) if self.return_down: return x, down else: return x class DLARoot(nn.Layer): """ DLA root block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. residual : bool Whether use residual connection. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, residual, data_format="channels_last", **kwargs): super(DLARoot, self).__init__(**kwargs) self.residual = residual self.data_format = data_format self.conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, activation=None, data_format=data_format, name="conv") self.activ = nn.ReLU() def call(self, x2, x1, extra, training=None): last_branch = x2 x = tf.concat([x2, x1] + list(extra), axis=get_channel_axis(self.data_format)) x = self.conv(x, training=training) if self.residual: x += last_branch x = self.activ(x) return x class DLATree(nn.Layer): """ DLA tree unit. It's like iterative stage. Parameters: ---------- levels : int Number of levels in the stage. in_channels : int Number of input channels. out_channels : int Number of output channels. res_body_class : nn.Module Residual block body class. strides : int or tuple/list of 2 int Strides of the convolution in a residual block. root_residual : bool Whether use residual connection in the root. root_dim : int Number of input channels in the root block. first_tree : bool, default False Is this tree stage the first stage in the net. input_level : bool, default True Is this tree unit the first unit in the stage. return_down : bool, default False Whether return downsample result. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, levels, in_channels, out_channels, res_body_class, strides, root_residual, root_dim=0, first_tree=False, input_level=True, return_down=False, data_format="channels_last", **kwargs): super(DLATree, self).__init__(**kwargs) self.return_down = return_down self.add_down = (input_level and not first_tree) self.root_level = (levels == 1) if root_dim == 0: root_dim = 2 * out_channels if self.add_down: root_dim += in_channels if self.root_level: self.tree1 = DLAResBlock( in_channels=in_channels, out_channels=out_channels, strides=strides, body_class=res_body_class, return_down=True, data_format=data_format, name="tree1") self.tree2 = DLAResBlock( in_channels=out_channels, out_channels=out_channels, strides=1, body_class=res_body_class, return_down=False, data_format=data_format, name="tree2") else: self.tree1 = DLATree( levels=levels - 1, in_channels=in_channels, out_channels=out_channels, res_body_class=res_body_class, strides=strides, root_residual=root_residual, root_dim=0, input_level=False, return_down=True, data_format=data_format, name="tree1") self.tree2 = DLATree( levels=levels - 1, in_channels=out_channels, out_channels=out_channels, res_body_class=res_body_class, strides=1, root_residual=root_residual, root_dim=root_dim + out_channels, input_level=False, return_down=False, data_format=data_format, name="tree2") if self.root_level: self.root = DLARoot( in_channels=root_dim, out_channels=out_channels, residual=root_residual, data_format=data_format, name="root") def call(self, x, extra=None, training=None): extra = [] if extra is None else extra x1, down = self.tree1(x, training=training) if self.add_down: extra.append(down) if self.root_level: x2 = self.tree2(x1, training=training) x = self.root(x2, x1, extra, training=training) else: extra.append(x1) x = self.tree2(x1, extra, training=training) if self.return_down: return x, down else: return x class DLAInitBlock(nn.Layer): """ DLA specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(DLAInitBlock, self).__init__(**kwargs) mid_channels = out_channels // 2 self.conv1 = conv7x7_block( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=mid_channels, out_channels=mid_channels, data_format=data_format, name="conv2") self.conv3 = conv3x3_block( in_channels=mid_channels, out_channels=out_channels, strides=2, data_format=data_format, name="conv3") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.conv3(x, training=training) return x class DLA(tf.keras.Model): """ DLA model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484. Parameters: ---------- levels : int Number of levels in each stage. channels : list of int Number of output channels for each stage. init_block_channels : int Number of output channels for the initial unit. res_body_class : nn.Module Residual block body class. residual_root : bool Whether use residual connection in the root blocks. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, levels, channels, init_block_channels, res_body_class, residual_root, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(DLA, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(DLAInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i in range(len(levels)): levels_i = levels[i] out_channels = channels[i] first_tree = (i == 0) self.features.add(DLATree( levels=levels_i, in_channels=in_channels, out_channels=out_channels, res_body_class=res_body_class, strides=2, root_residual=residual_root, first_tree=first_tree, data_format=data_format, name="stage{}".format(i + 1))) in_channels = out_channels self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = conv1x1( in_channels=in_channels, out_channels=classes, use_bias=True, data_format=data_format, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = self.output1(x) x = flatten(x, self.data_format) return x def get_dla(levels, channels, res_body_class, residual_root=False, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create DLA model with specific parameters. Parameters: ---------- levels : int Number of levels in each stage. channels : list of int Number of output channels for each stage. res_body_class : nn.Module Residual block body class. residual_root : bool, default False Whether use residual connection in the root 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ init_block_channels = 32 net = DLA( levels=levels, channels=channels, init_block_channels=init_block_channels, res_body_class=res_body_class, residual_root=residual_root, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def dla34(**kwargs): """ DLA-34 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_dla(levels=[1, 2, 2, 1], channels=[64, 128, 256, 512], res_body_class=ResBlock, model_name="dla34", **kwargs) def dla46c(**kwargs): """ DLA-46-C model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_dla(levels=[1, 2, 2, 1], channels=[64, 64, 128, 256], res_body_class=DLABottleneck, model_name="dla46c", **kwargs) def dla46xc(**kwargs): """ DLA-X-46-C model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_dla(levels=[1, 2, 2, 1], channels=[64, 64, 128, 256], res_body_class=DLABottleneckX, model_name="dla46xc", **kwargs) def dla60(**kwargs): """ DLA-60 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_dla(levels=[1, 2, 3, 1], channels=[128, 256, 512, 1024], res_body_class=DLABottleneck, model_name="dla60", **kwargs) def dla60x(**kwargs): """ DLA-X-60 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_dla(levels=[1, 2, 3, 1], channels=[128, 256, 512, 1024], res_body_class=DLABottleneckX, model_name="dla60x", **kwargs) def dla60xc(**kwargs): """ DLA-X-60-C model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_dla(levels=[1, 2, 3, 1], channels=[64, 64, 128, 256], res_body_class=DLABottleneckX, model_name="dla60xc", **kwargs) def dla102(**kwargs): """ DLA-102 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_dla(levels=[1, 3, 4, 1], channels=[128, 256, 512, 1024], res_body_class=DLABottleneck, residual_root=True, model_name="dla102", **kwargs) def dla102x(**kwargs): """ DLA-X-102 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_dla(levels=[1, 3, 4, 1], channels=[128, 256, 512, 1024], res_body_class=DLABottleneckX, residual_root=True, model_name="dla102x", **kwargs) def dla102x2(**kwargs): """ DLA-X2-102 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ class DLABottleneckX64(DLABottleneckX): def __init__(self, in_channels, out_channels, strides, **kwargs): super(DLABottleneckX64, self).__init__(in_channels, out_channels, strides, cardinality=64, **kwargs) return get_dla(levels=[1, 3, 4, 1], channels=[128, 256, 512, 1024], res_body_class=DLABottleneckX64, residual_root=True, model_name="dla102x2", **kwargs) def dla169(**kwargs): """ DLA-169 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_dla(levels=[2, 3, 5, 1], channels=[128, 256, 512, 1024], res_body_class=DLABottleneck, residual_root=True, model_name="dla169", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ dla34, dla46c, dla46xc, dla60, dla60x, dla60xc, dla102, dla102x, dla102x2, dla169, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != dla34 or weight_count == 15742104) assert (model != dla46c or weight_count == 1301400) assert (model != dla46xc or weight_count == 1068440) assert (model != dla60 or weight_count == 22036632) assert (model != dla60x or weight_count == 17352344) assert (model != dla60xc or weight_count == 1319832) assert (model != dla102 or weight_count == 33268888) assert (model != dla102x or weight_count == 26309272) assert (model != dla102x2 or weight_count == 41282200) assert (model != dla169 or weight_count == 53389720) if __name__ == "__main__": _test()
22,786
31.599428
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/proxylessnas.py
""" ProxylessNAS for ImageNet-1K, implemented in TensorFlow. Original paper: 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,' https://arxiv.org/abs/1812.00332. """ __all__ = ['ProxylessNAS', 'proxylessnas_cpu', 'proxylessnas_gpu', 'proxylessnas_mobile', 'proxylessnas_mobile14', 'ProxylessUnit', 'get_proxylessnas'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import ConvBlock, conv1x1_block, conv3x3_block, SimpleSequential, flatten, is_channels_first class ProxylessBlock(nn.Layer): """ ProxylessNAS block for residual path in ProxylessNAS unit. 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. bn_eps : float Small float added to variance in Batch norm. expansion : int Expansion ratio. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, strides, bn_eps, expansion, data_format="channels_last", **kwargs): super(ProxylessBlock, self).__init__(**kwargs) self.use_bc = (expansion > 1) mid_channels = in_channels * expansion if self.use_bc: self.bc_conv = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, bn_eps=bn_eps, activation="relu6", data_format=data_format, name="bc_conv") padding = (kernel_size - 1) // 2 self.dw_conv = ConvBlock( in_channels=mid_channels, out_channels=mid_channels, kernel_size=kernel_size, strides=strides, padding=padding, groups=mid_channels, bn_eps=bn_eps, activation="relu6", data_format=data_format, name="dw_conv") self.pw_conv = conv1x1_block( in_channels=mid_channels, out_channels=out_channels, bn_eps=bn_eps, activation=None, data_format=data_format, name="pw_conv") def call(self, x, training=None): if self.use_bc: x = self.bc_conv(x, training=training) x = self.dw_conv(x, training=training) x = self.pw_conv(x, training=training) return x class ProxylessUnit(nn.Layer): """ ProxylessNAS unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int Convolution window size for body block. strides : int Strides of the convolution. bn_eps : float Small float added to variance in Batch norm. expansion : int Expansion ratio for body block. residual : bool Whether to use residual branch. shortcut : bool Whether to use identity branch. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, strides, bn_eps, expansion, residual, shortcut, data_format="channels_last", **kwargs): super(ProxylessUnit, self).__init__(**kwargs) assert (residual or shortcut) self.residual = residual self.shortcut = shortcut if self.residual: self.body = ProxylessBlock( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, strides=strides, bn_eps=bn_eps, expansion=expansion, data_format=data_format, name="body") def call(self, x, training=None): if not self.residual: return x if not self.shortcut: return self.body(x, training=training) identity = x x = self.body(x, training=training) x = identity + x return x class ProxylessNAS(tf.keras.Model): """ ProxylessNAS model from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,' https://arxiv.org/abs/1812.00332. 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. residuals : list of list of int Whether to use residual branch in units. shortcuts : list of list of int Whether to use identity branch in units. kernel_sizes : list of list of int Convolution window size for each units. expansions : list of list of int Expansion ratio for each units. bn_eps : float, default 1e-3 Small float added to variance in Batch norm. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, final_block_channels, residuals, shortcuts, kernel_sizes, expansions, bn_eps=1e-3, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(ProxylessNAS, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(conv3x3_block( in_channels=in_channels, out_channels=init_block_channels, strides=2, bn_eps=bn_eps, activation="relu6", data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) residuals_per_stage = residuals[i] shortcuts_per_stage = shortcuts[i] kernel_sizes_per_stage = kernel_sizes[i] expansions_per_stage = expansions[i] for j, out_channels in enumerate(channels_per_stage): residual = (residuals_per_stage[j] == 1) shortcut = (shortcuts_per_stage[j] == 1) kernel_size = kernel_sizes_per_stage[j] expansion = expansions_per_stage[j] strides = 2 if (j == 0) and (i != 0) else 1 stage.add(ProxylessUnit( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, strides=strides, bn_eps=bn_eps, expansion=expansion, residual=residual, shortcut=shortcut, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(conv1x1_block( in_channels=in_channels, out_channels=final_block_channels, bn_eps=bn_eps, activation="relu6", data_format=data_format, name="final_block")) in_channels = final_block_channels self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_proxylessnas(version, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create ProxylessNAS model with specific parameters. Parameters: ---------- version : str Version of ProxylessNAS ('cpu', 'gpu', 'mobile' or 'mobile14'). 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if version == "cpu": residuals = [[1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1]] channels = [[24], [32, 32, 32, 32], [48, 48, 48, 48], [88, 88, 88, 88, 104, 104, 104, 104], [216, 216, 216, 216, 360]] kernel_sizes = [[3], [3, 3, 3, 3], [3, 3, 3, 5], [3, 3, 3, 3, 5, 3, 3, 3], [5, 5, 5, 3, 5]] expansions = [[1], [6, 3, 3, 3], [6, 3, 3, 3], [6, 3, 3, 3, 6, 3, 3, 3], [6, 3, 3, 3, 6]] init_block_channels = 40 final_block_channels = 1432 elif version == "gpu": residuals = [[1], [1, 0, 0, 0], [1, 0, 0, 1], [1, 0, 0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1]] channels = [[24], [32, 32, 32, 32], [56, 56, 56, 56], [112, 112, 112, 112, 128, 128, 128, 128], [256, 256, 256, 256, 432]] kernel_sizes = [[3], [5, 3, 3, 3], [7, 3, 3, 3], [7, 5, 5, 5, 5, 3, 3, 5], [7, 7, 7, 5, 7]] expansions = [[1], [3, 3, 3, 3], [3, 3, 3, 3], [6, 3, 3, 3, 6, 3, 3, 3], [6, 6, 6, 6, 6]] init_block_channels = 40 final_block_channels = 1728 elif version == "mobile": residuals = [[1], [1, 1, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1]] channels = [[16], [32, 32, 32, 32], [40, 40, 40, 40], [80, 80, 80, 80, 96, 96, 96, 96], [192, 192, 192, 192, 320]] kernel_sizes = [[3], [5, 3, 3, 3], [7, 3, 5, 5], [7, 5, 5, 5, 5, 5, 5, 5], [7, 7, 7, 7, 7]] expansions = [[1], [3, 3, 3, 3], [3, 3, 3, 3], [6, 3, 3, 3, 6, 3, 3, 3], [6, 6, 3, 3, 6]] init_block_channels = 32 final_block_channels = 1280 elif version == "mobile14": residuals = [[1], [1, 1, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1]] channels = [[24], [40, 40, 40, 40], [56, 56, 56, 56], [112, 112, 112, 112, 136, 136, 136, 136], [256, 256, 256, 256, 448]] kernel_sizes = [[3], [5, 3, 3, 3], [7, 3, 5, 5], [7, 5, 5, 5, 5, 5, 5, 5], [7, 7, 7, 7, 7]] expansions = [[1], [3, 3, 3, 3], [3, 3, 3, 3], [6, 3, 3, 3, 6, 3, 3, 3], [6, 6, 3, 3, 6]] init_block_channels = 48 final_block_channels = 1792 else: raise ValueError("Unsupported ProxylessNAS version: {}".format(version)) shortcuts = [[0], [0, 1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1, 0, 1, 1, 1], [0, 1, 1, 1, 0]] net = ProxylessNAS( channels=channels, init_block_channels=init_block_channels, final_block_channels=final_block_channels, residuals=residuals, shortcuts=shortcuts, kernel_sizes=kernel_sizes, expansions=expansions, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def proxylessnas_cpu(**kwargs): """ ProxylessNAS (CPU) model from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,' https://arxiv.org/abs/1812.00332. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_proxylessnas(version="cpu", model_name="proxylessnas_cpu", **kwargs) def proxylessnas_gpu(**kwargs): """ ProxylessNAS (GPU) model from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,' https://arxiv.org/abs/1812.00332. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_proxylessnas(version="gpu", model_name="proxylessnas_gpu", **kwargs) def proxylessnas_mobile(**kwargs): """ ProxylessNAS (Mobile) model from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,' https://arxiv.org/abs/1812.00332. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_proxylessnas(version="mobile", model_name="proxylessnas_mobile", **kwargs) def proxylessnas_mobile14(**kwargs): """ ProxylessNAS (Mobile-14) model from 'ProxylessNAS: Direct Neural Architecture Search on Target Task and Hardware,' https://arxiv.org/abs/1812.00332. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_proxylessnas(version="mobile14", model_name="proxylessnas_mobile14", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ proxylessnas_cpu, proxylessnas_gpu, proxylessnas_mobile, proxylessnas_mobile14, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != proxylessnas_cpu or weight_count == 4361648) assert (model != proxylessnas_gpu or weight_count == 7119848) assert (model != proxylessnas_mobile or weight_count == 4080512) assert (model != proxylessnas_mobile14 or weight_count == 6857568) if __name__ == "__main__": _test()
15,845
35.178082
118
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/shufflenetv2.py
""" ShuffleNet V2 for ImageNet-1K, implemented in TensorFlow. Original paper: 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,' https://arxiv.org/abs/1807.11164. """ __all__ = ['ShuffleNetV2', 'shufflenetv2_wd2', 'shufflenetv2_w1', 'shufflenetv2_w3d2', 'shufflenetv2_w2'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1, depthwise_conv3x3, conv1x1_block, conv3x3_block, ChannelShuffle, SEBlock,\ BatchNorm, MaxPool2d, SimpleSequential, get_channel_axis, flatten class ShuffleUnit(nn.Layer): """ ShuffleNetV2 unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. downsample : bool Whether do downsample. use_se : bool Whether to use SE block. use_residual : bool Whether to use residual connection. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, downsample, use_se, use_residual, data_format="channels_last", **kwargs): super(ShuffleUnit, self).__init__(**kwargs) self.data_format = data_format self.downsample = downsample self.use_se = use_se self.use_residual = use_residual mid_channels = out_channels // 2 self.compress_conv1 = conv1x1( in_channels=(in_channels if self.downsample else mid_channels), out_channels=mid_channels, data_format=data_format, name="compress_conv1") self.compress_bn1 = BatchNorm( # in_channels=mid_channels, data_format=data_format, name="compress_bn1") self.dw_conv2 = depthwise_conv3x3( channels=mid_channels, strides=(2 if self.downsample else 1), data_format=data_format, name="dw_conv2") self.dw_bn2 = BatchNorm( # in_channels=mid_channels, data_format=data_format, name="dw_bn2") self.expand_conv3 = conv1x1( in_channels=mid_channels, out_channels=mid_channels, data_format=data_format, name="expand_conv3") self.expand_bn3 = BatchNorm( # in_channels=mid_channels, data_format=data_format, name="expand_bn3") if self.use_se: self.se = SEBlock( channels=mid_channels, data_format=data_format, name="se") if downsample: self.dw_conv4 = depthwise_conv3x3( channels=in_channels, strides=2, data_format=data_format, name="dw_conv4") self.dw_bn4 = BatchNorm( # in_channels=in_channels, data_format=data_format, name="dw_bn4") self.expand_conv5 = conv1x1( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="expand_conv5") self.expand_bn5 = BatchNorm( # in_channels=mid_channels, data_format=data_format, name="expand_bn5") self.activ = nn.ReLU() self.c_shuffle = ChannelShuffle( channels=out_channels, groups=2, data_format=data_format, name="c_shuffle") def call(self, x, training=None): if self.downsample: y1 = self.dw_conv4(x) y1 = self.dw_bn4(y1, training=training) y1 = self.expand_conv5(y1) y1 = self.expand_bn5(y1, training=training) y1 = self.activ(y1) x2 = x else: y1, x2 = tf.split(x, num_or_size_splits=2, axis=get_channel_axis(self.data_format)) y2 = self.compress_conv1(x2) y2 = self.compress_bn1(y2, training=training) y2 = self.activ(y2) y2 = self.dw_conv2(y2) y2 = self.dw_bn2(y2, training=training) y2 = self.expand_conv3(y2) y2 = self.expand_bn3(y2, training=training) y2 = self.activ(y2) if self.use_se: y2 = self.se(y2) if self.use_residual and not self.downsample: y2 = y2 + x2 x = tf.concat([y1, y2], axis=get_channel_axis(self.data_format)) x = self.c_shuffle(x) return x class ShuffleInitBlock(nn.Layer): """ ShuffleNetV2 specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(ShuffleInitBlock, self).__init__(**kwargs) self.conv = conv3x3_block( in_channels=in_channels, out_channels=out_channels, strides=2, data_format=data_format, name="conv") self.pool = MaxPool2d( pool_size=3, strides=2, padding=0, ceil_mode=True, data_format=data_format, name="pool") def call(self, x, training=None): x = self.conv(x, training=training) x = self.pool(x) return x class ShuffleNetV2(tf.keras.Model): """ ShuffleNetV2 model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,' https://arxiv.org/abs/1807.11164. 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. use_se : bool, default False Whether to use SE block. use_residual : bool, default False Whether to use residual connections. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, final_block_channels, use_se=False, use_residual=False, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(ShuffleNetV2, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(ShuffleInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) for j, out_channels in enumerate(channels_per_stage): downsample = (j == 0) stage.add(ShuffleUnit( in_channels=in_channels, out_channels=out_channels, downsample=downsample, use_se=use_se, use_residual=use_residual, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(conv1x1_block( in_channels=in_channels, out_channels=final_block_channels, data_format=data_format, name="final_block")) in_channels = final_block_channels self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_shufflenetv2(width_scale, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create ShuffleNetV2 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ init_block_channels = 24 final_block_channels = 1024 layers = [4, 8, 4] channels_per_layers = [116, 232, 464] 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] if width_scale > 1.5: final_block_channels = int(final_block_channels * width_scale) net = ShuffleNetV2( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def shufflenetv2_wd2(**kwargs): """ ShuffleNetV2 0.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,' https://arxiv.org/abs/1807.11164. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_shufflenetv2(width_scale=(12.0 / 29.0), model_name="shufflenetv2_wd2", **kwargs) def shufflenetv2_w1(**kwargs): """ ShuffleNetV2 1x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,' https://arxiv.org/abs/1807.11164. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_shufflenetv2(width_scale=1.0, model_name="shufflenetv2_w1", **kwargs) def shufflenetv2_w3d2(**kwargs): """ ShuffleNetV2 1.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,' https://arxiv.org/abs/1807.11164. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_shufflenetv2(width_scale=(44.0 / 29.0), model_name="shufflenetv2_w3d2", **kwargs) def shufflenetv2_w2(**kwargs): """ ShuffleNetV2 2x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,' https://arxiv.org/abs/1807.11164. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_shufflenetv2(width_scale=(61.0 / 29.0), model_name="shufflenetv2_w2", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K pretrained = False models = [ shufflenetv2_wd2, shufflenetv2_w1, shufflenetv2_w3d2, shufflenetv2_w2, ] for model in models: net = model(pretrained=pretrained) batch = 14 x = tf.random.normal((batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != shufflenetv2_wd2 or weight_count == 1366792) assert (model != shufflenetv2_w1 or weight_count == 2278604) assert (model != shufflenetv2_w3d2 or weight_count == 4406098) assert (model != shufflenetv2_w2 or weight_count == 7601686) if __name__ == "__main__": _test()
13,783
32.784314
115
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/hrnet.py
""" HRNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'Deep High-Resolution Representation Learning for Visual Recognition,' https://arxiv.org/abs/1908.07919. """ __all__ = ['HRNet', 'hrnet_w18_small_v1', 'hrnet_w18_small_v2', 'hrnetv2_w18', 'hrnetv2_w30', 'hrnetv2_w32', 'hrnetv2_w40', 'hrnetv2_w44', 'hrnetv2_w48', 'hrnetv2_w64'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1_block, conv3x3_block, Identity, SimpleSequential, flatten, is_channels_first from .resnet import ResUnit class UpSamplingBlock(nn.Layer): """ HFNet specific upsampling block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. scale_factor : int Multiplier for spatial size. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, scale_factor, data_format="channels_last", **kwargs): super(UpSamplingBlock, self).__init__(**kwargs) self.scale_factor = scale_factor self.conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, strides=1, activation=None, data_format=data_format, name="conv") self.upsample = nn.UpSampling2D( size=scale_factor, data_format=data_format, interpolation="nearest", name="upsample") def call(self, x, training=None): x = self.conv(x, training=training) x = self.upsample(x) return x class HRBlock(nn.Layer): """ HFNet block. Parameters: ---------- in_channels_list : list of int Number of input channels. out_channels_list : list of int Number of output channels. num_branches : int Number of branches. num_subblocks : list of int Number of subblock. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels_list, out_channels_list, num_branches, num_subblocks, data_format="channels_last", **kwargs): super(HRBlock, self).__init__(**kwargs) self.in_channels_list = in_channels_list self.num_branches = num_branches self.branches = SimpleSequential(name="branches") for i in range(num_branches): layers = SimpleSequential(name="branches/branch{}".format(i + 1)) in_channels_i = self.in_channels_list[i] out_channels_i = out_channels_list[i] for j in range(num_subblocks[i]): layers.add(ResUnit( in_channels=in_channels_i, out_channels=out_channels_i, strides=1, bottleneck=False, data_format=data_format, name="unit{}".format(j + 1))) in_channels_i = out_channels_i self.in_channels_list[i] = out_channels_i self.branches.add(layers) if num_branches > 1: self.fuse_layers = SimpleSequential(name="fuse_layers") for i in range(num_branches): fuse_layer_name = "fuse_layers/fuse_layer{}".format(i + 1) fuse_layer = SimpleSequential(name=fuse_layer_name) for j in range(num_branches): if j > i: fuse_layer.add(UpSamplingBlock( in_channels=in_channels_list[j], out_channels=in_channels_list[i], scale_factor=2 ** (j - i), data_format=data_format, name=fuse_layer_name + "/block{}".format(j + 1))) elif j == i: fuse_layer.add(Identity(name=fuse_layer_name + "/block{}".format(j + 1))) else: conv3x3_seq_name = fuse_layer_name + "/block{}_conv3x3_seq".format(j + 1) conv3x3_seq = SimpleSequential(name=conv3x3_seq_name) for k in range(i - j): if k == i - j - 1: conv3x3_seq.add(conv3x3_block( in_channels=in_channels_list[j], out_channels=in_channels_list[i], strides=2, activation=None, data_format=data_format, name="subblock{}".format(k + 1))) else: conv3x3_seq.add(conv3x3_block( in_channels=in_channels_list[j], out_channels=in_channels_list[j], strides=2, data_format=data_format, name="subblock{}".format(k + 1))) fuse_layer.add(conv3x3_seq) self.fuse_layers.add(fuse_layer) self.activ = nn.ReLU() def call(self, x, training=None): for i in range(self.num_branches): x[i] = self.branches[i](x[i], training=training) if self.num_branches == 1: return x x_fuse = [] for i in range(len(self.fuse_layers)): y = x[0] if i == 0 else self.fuse_layers[i][0](x[0], training=training) for j in range(1, self.num_branches): if i == j: y = y + x[j] else: y = y + self.fuse_layers[i][j](x[j], training=training) x_fuse.append(self.activ(y)) return x_fuse class HRStage(nn.Layer): """ HRNet stage block. Parameters: ---------- in_channels_list : list of int Number of output channels from the previous layer. out_channels_list : list of int Number of output channels in the current layer. num_modules : int Number of modules. num_branches : int Number of branches. num_subblocks : list of int Number of subblocks. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels_list, out_channels_list, num_modules, num_branches, num_subblocks, data_format="channels_last", **kwargs): super(HRStage, self).__init__(**kwargs) self.branches = num_branches self.in_channels_list = out_channels_list in_branches = len(in_channels_list) out_branches = len(out_channels_list) self.transition = SimpleSequential(name="transition") for i in range(out_branches): if i < in_branches: if out_channels_list[i] != in_channels_list[i]: self.transition.add(conv3x3_block( in_channels=in_channels_list[i], out_channels=out_channels_list[i], strides=1, data_format=data_format, name="transition/block{}".format(i + 1))) else: self.transition.add(Identity(name="transition/block{}".format(i + 1))) else: conv3x3_seq = SimpleSequential(name="transition/conv3x3_seq{}".format(i + 1)) for j in range(i + 1 - in_branches): in_channels_i = in_channels_list[-1] out_channels_i = out_channels_list[i] if j == i - in_branches else in_channels_i conv3x3_seq.add(conv3x3_block( in_channels=in_channels_i, out_channels=out_channels_i, strides=2, data_format=data_format, name="subblock{}".format(j + 1))) self.transition.add(conv3x3_seq) self.layers = SimpleSequential(name="layers") for i in range(num_modules): self.layers.add(HRBlock( in_channels_list=self.in_channels_list, out_channels_list=out_channels_list, num_branches=num_branches, num_subblocks=num_subblocks, data_format=data_format, name="block{}".format(i + 1))) self.in_channels_list = list(self.layers[-1].in_channels_list) def call(self, x, training=None): x_list = [] for j in range(self.branches): if not isinstance(self.transition[j], Identity): x_list.append(self.transition[j](x[-1] if type(x) in (list, tuple) else x, training=training)) else: x_list_j = x[j] if type(x) in (list, tuple) else x x_list.append(x_list_j) y_list = self.layers(x_list, training=training) return y_list class HRInitBlock(nn.Layer): """ HRNet 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. num_subblocks : int Number of subblocks. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, mid_channels, num_subblocks, data_format="channels_last", **kwargs): super(HRInitBlock, self).__init__(**kwargs) self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels, strides=2, data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=mid_channels, out_channels=mid_channels, strides=2, data_format=data_format, name="conv2") in_channels = mid_channels self.subblocks = SimpleSequential(name="subblocks") for i in range(num_subblocks): self.subblocks.add(ResUnit( in_channels=in_channels, out_channels=out_channels, strides=1, bottleneck=True, data_format=data_format, name="block{}".format(i + 1))) in_channels = out_channels def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.subblocks(x, training=training) return x class HRFinalBlock(nn.Layer): """ HRNet specific final block. Parameters: ---------- in_channels_list : list of int Number of input channels per stage. out_channels_list : list of int Number of output channels per stage. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels_list, out_channels_list, data_format="channels_last", **kwargs): super(HRFinalBlock, self).__init__(**kwargs) self.inc_blocks = SimpleSequential(name="inc_blocks") for i, in_channels_i in enumerate(in_channels_list): self.inc_blocks.add(ResUnit( in_channels=in_channels_i, out_channels=out_channels_list[i], strides=1, bottleneck=True, data_format=data_format, name="inc_blocks/block{}".format(i + 1))) self.down_blocks = SimpleSequential(name="down_blocks") for i in range(len(in_channels_list) - 1): self.down_blocks.add(conv3x3_block( in_channels=out_channels_list[i], out_channels=out_channels_list[i + 1], strides=2, use_bias=True, data_format=data_format, name="down_blocks/block{}".format(i + 1))) self.final_layer = conv1x1_block( in_channels=1024, out_channels=2048, strides=1, use_bias=True, data_format=data_format, name="final_layer") def call(self, x, training=None): y = self.inc_blocks[0](x[0], training=training) for i in range(len(self.down_blocks)): y = self.inc_blocks[i + 1](x[i + 1], training=training) + self.down_blocks[i](y, training=training) y = self.final_layer(y, training=training) return y class HRNet(tf.keras.Model): """ HRNet model from 'Deep High-Resolution Representation Learning for Visual Recognition,' https://arxiv.org/abs/1908.07919. Parameters: ---------- channels : list of int Number of output channels for each unit. init_block_channels : int Number of output channels for the initial unit. init_num_subblocks : int Number of subblocks in the initial unit. num_modules : int Number of modules per stage. num_subblocks : list of int Number of subblocks per stage. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, init_num_subblocks, num_modules, num_subblocks, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(HRNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.branches = [2, 3, 4] self.features = SimpleSequential(name="features") self.features.add(HRInitBlock( in_channels=in_channels, out_channels=init_block_channels, mid_channels=64, num_subblocks=init_num_subblocks, data_format=data_format, name="init_block")) in_channels_list = [init_block_channels] for i in range(len(self.branches)): self.features.add(HRStage( in_channels_list=in_channels_list, out_channels_list=channels[i], num_modules=num_modules[i], num_branches=self.branches[i], num_subblocks=num_subblocks[i], data_format=data_format, name="stage{}".format(i + 1))) in_channels_list = self.features[-1].in_channels_list self.features.add(HRFinalBlock( in_channels_list=in_channels_list, out_channels_list=[128, 256, 512, 1024], data_format=data_format, name="final_block")) self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=2048, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_hrnet(version, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create HRNet model with specific parameters. Parameters: ---------- version : str Version of MobileNetV3 ('s' or 'm'). 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if version == "w18s1": init_block_channels = 128 init_num_subblocks = 1 channels = [[16, 32], [16, 32, 64], [16, 32, 64, 128]] num_modules = [1, 1, 1] elif version == "w18s2": init_block_channels = 256 init_num_subblocks = 2 channels = [[18, 36], [18, 36, 72], [18, 36, 72, 144]] num_modules = [1, 3, 2] elif version == "w18": init_block_channels = 256 init_num_subblocks = 4 channels = [[18, 36], [18, 36, 72], [18, 36, 72, 144]] num_modules = [1, 4, 3] elif version == "w30": init_block_channels = 256 init_num_subblocks = 4 channels = [[30, 60], [30, 60, 120], [30, 60, 120, 240]] num_modules = [1, 4, 3] elif version == "w32": init_block_channels = 256 init_num_subblocks = 4 channels = [[32, 64], [32, 64, 128], [32, 64, 128, 256]] num_modules = [1, 4, 3] elif version == "w40": init_block_channels = 256 init_num_subblocks = 4 channels = [[40, 80], [40, 80, 160], [40, 80, 160, 320]] num_modules = [1, 4, 3] elif version == "w44": init_block_channels = 256 init_num_subblocks = 4 channels = [[44, 88], [44, 88, 176], [44, 88, 176, 352]] num_modules = [1, 4, 3] elif version == "w48": init_block_channels = 256 init_num_subblocks = 4 channels = [[48, 96], [48, 96, 192], [48, 96, 192, 384]] num_modules = [1, 4, 3] elif version == "w64": init_block_channels = 256 init_num_subblocks = 4 channels = [[64, 128], [64, 128, 256], [64, 128, 256, 512]] num_modules = [1, 4, 3] else: raise ValueError("Unsupported HRNet version {}".format(version)) num_subblocks = [[max(2, init_num_subblocks)] * len(ci) for ci in channels] net = HRNet( channels=channels, init_block_channels=init_block_channels, init_num_subblocks=init_num_subblocks, num_modules=num_modules, num_subblocks=num_subblocks, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def hrnet_w18_small_v1(**kwargs): """ HRNet-W18 Small V1 model from 'Deep High-Resolution Representation Learning for Visual Recognition,' https://arxiv.org/abs/1908.07919. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_hrnet(version="w18s1", model_name="hrnet_w18_small_v1", **kwargs) def hrnet_w18_small_v2(**kwargs): """ HRNet-W18 Small V2 model from 'Deep High-Resolution Representation Learning for Visual Recognition,' https://arxiv.org/abs/1908.07919. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_hrnet(version="w18s2", model_name="hrnet_w18_small_v2", **kwargs) def hrnetv2_w18(**kwargs): """ HRNetV2-W18 model from 'Deep High-Resolution Representation Learning for Visual Recognition,' https://arxiv.org/abs/1908.07919. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_hrnet(version="w18", model_name="hrnetv2_w18", **kwargs) def hrnetv2_w30(**kwargs): """ HRNetV2-W30 model from 'Deep High-Resolution Representation Learning for Visual Recognition,' https://arxiv.org/abs/1908.07919. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_hrnet(version="w30", model_name="hrnetv2_w30", **kwargs) def hrnetv2_w32(**kwargs): """ HRNetV2-W32 model from 'Deep High-Resolution Representation Learning for Visual Recognition,' https://arxiv.org/abs/1908.07919. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_hrnet(version="w32", model_name="hrnetv2_w32", **kwargs) def hrnetv2_w40(**kwargs): """ HRNetV2-W40 model from 'Deep High-Resolution Representation Learning for Visual Recognition,' https://arxiv.org/abs/1908.07919. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_hrnet(version="w40", model_name="hrnetv2_w40", **kwargs) def hrnetv2_w44(**kwargs): """ HRNetV2-W44 model from 'Deep High-Resolution Representation Learning for Visual Recognition,' https://arxiv.org/abs/1908.07919. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_hrnet(version="w44", model_name="hrnetv2_w44", **kwargs) def hrnetv2_w48(**kwargs): """ HRNetV2-W48 model from 'Deep High-Resolution Representation Learning for Visual Recognition,' https://arxiv.org/abs/1908.07919. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_hrnet(version="w48", model_name="hrnetv2_w48", **kwargs) def hrnetv2_w64(**kwargs): """ HRNetV2-W64 model from 'Deep High-Resolution Representation Learning for Visual Recognition,' https://arxiv.org/abs/1908.07919. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_hrnet(version="w64", model_name="hrnetv2_w64", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ hrnet_w18_small_v1, hrnet_w18_small_v2, hrnetv2_w18, hrnetv2_w30, hrnetv2_w32, hrnetv2_w40, hrnetv2_w44, hrnetv2_w48, hrnetv2_w64, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != hrnet_w18_small_v1 or weight_count == 13187464) assert (model != hrnet_w18_small_v2 or weight_count == 15597464) assert (model != hrnetv2_w18 or weight_count == 21299004) assert (model != hrnetv2_w30 or weight_count == 37712220) assert (model != hrnetv2_w32 or weight_count == 41232680) assert (model != hrnetv2_w40 or weight_count == 57557160) assert (model != hrnetv2_w44 or weight_count == 67064984) assert (model != hrnetv2_w48 or weight_count == 77469864) assert (model != hrnetv2_w64 or weight_count == 128059944) if __name__ == "__main__": _test()
25,313
34.703808
115
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/fcn8sd.py
""" FCN-8s(d) for image segmentation, implemented in TensorFlow. Original paper: 'Fully Convolutional Networks for Semantic Segmentation,' https://arxiv.org/abs/1411.4038. """ __all__ = ['FCN8sd', 'fcn8sd_resnetd50b_voc', 'fcn8sd_resnetd101b_voc', 'fcn8sd_resnetd50b_coco', 'fcn8sd_resnetd101b_coco', 'fcn8sd_resnetd50b_ade20k', 'fcn8sd_resnetd101b_ade20k', 'fcn8sd_resnetd50b_cityscapes', 'fcn8sd_resnetd101b_cityscapes'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1, conv3x3_block, is_channels_first, interpolate_im, get_im_size from .resnetd import resnetd50b, resnetd101b class FCNFinalBlock(nn.Layer): """ FCN-8s(d) final block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. bottleneck_factor : int, default 4 Bottleneck factor. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, bottleneck_factor=4, data_format="channels_last", **kwargs): super(FCNFinalBlock, self).__init__(**kwargs) assert (in_channels % bottleneck_factor == 0) self.data_format = data_format mid_channels = in_channels // bottleneck_factor self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv1") self.dropout = nn.Dropout( rate=0.1, name="dropout") self.conv2 = conv1x1( in_channels=mid_channels, out_channels=out_channels, use_bias=True, data_format=data_format, name="conv2") def call(self, x, out_size, training=None): x = self.conv1(x, training=training) x = self.dropout(x, training=training) x = self.conv2(x) x = interpolate_im(x, out_size=out_size, data_format=self.data_format) return x class FCN8sd(tf.keras.Model): """ FCN-8s(d) model from 'Fully Convolutional Networks for Semantic Segmentation,' https://arxiv.org/abs/1411.4038. It is an experimental model mixed FCN-8s and PSPNet. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, backbone, backbone_out_channels=2048, aux=False, fixed_size=True, in_channels=3, in_size=(480, 480), classes=21, data_format="channels_last", **kwargs): super(FCN8sd, self).__init__(**kwargs) assert (in_channels > 0) self.in_size = in_size self.classes = classes self.aux = aux self.fixed_size = fixed_size self.data_format = data_format self.backbone = backbone pool_out_channels = backbone_out_channels self.final_block = FCNFinalBlock( in_channels=pool_out_channels, out_channels=classes, data_format=data_format, name="final_block") if self.aux: aux_out_channels = backbone_out_channels // 2 self.aux_block = FCNFinalBlock( in_channels=aux_out_channels, out_channels=classes, data_format=data_format, name="aux_block") def call(self, x, training=None): in_size = self.in_size if self.fixed_size else get_im_size(x, data_format=self.data_format) x, y = self.backbone(x, training=training) x = self.final_block(x, in_size, training=training) if self.aux: y = self.aux_block(y, in_size, training=training) return x, y else: return x def get_fcn8sd(backbone, classes, aux=False, model_name=None, data_format="channels_last", pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create FCN-8s(d) 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ net = FCN8sd( backbone=backbone, classes=classes, aux=aux, data_format=data_format, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root), by_name=True, skip_mismatch=True) return net def fcn8sd_resnetd50b_voc(pretrained_backbone=False, classes=21, aux=True, data_format="channels_last", **kwargs): """ FCN-8s(d) model on the base of ResNet(D)-50b for Pascal VOC from 'Fully Convolutional Networks for Semantic Segmentation,' https://arxiv.org/abs/1411.4038. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_fcn8sd(backbone=backbone, classes=classes, aux=aux, model_name="fcn8sd_resnetd50b_voc", data_format=data_format, **kwargs) def fcn8sd_resnetd101b_voc(pretrained_backbone=False, classes=21, aux=True, data_format="channels_last", **kwargs): """ FCN-8s(d) model on the base of ResNet(D)-101b for Pascal VOC from 'Fully Convolutional Networks for Semantic Segmentation,' https://arxiv.org/abs/1411.4038. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_fcn8sd(backbone=backbone, classes=classes, aux=aux, model_name="fcn8sd_resnetd101b_voc", data_format=data_format, **kwargs) def fcn8sd_resnetd50b_coco(pretrained_backbone=False, classes=21, aux=True, data_format="channels_last", **kwargs): """ FCN-8s(d) model on the base of ResNet(D)-50b for COCO from 'Fully Convolutional Networks for Semantic Segmentation,' https://arxiv.org/abs/1411.4038. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_fcn8sd(backbone=backbone, classes=classes, aux=aux, model_name="fcn8sd_resnetd50b_coco", data_format=data_format, **kwargs) def fcn8sd_resnetd101b_coco(pretrained_backbone=False, classes=21, aux=True, data_format="channels_last", **kwargs): """ FCN-8s(d) model on the base of ResNet(D)-101b for COCO from 'Fully Convolutional Networks for Semantic Segmentation,' https://arxiv.org/abs/1411.4038. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_fcn8sd(backbone=backbone, classes=classes, aux=aux, model_name="fcn8sd_resnetd101b_coco", data_format=data_format, **kwargs) def fcn8sd_resnetd50b_ade20k(pretrained_backbone=False, classes=150, aux=True, data_format="channels_last", **kwargs): """ FCN-8s(d) model on the base of ResNet(D)-50b for ADE20K from 'Fully Convolutional Networks for Semantic Segmentation,' https://arxiv.org/abs/1411.4038. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_fcn8sd(backbone=backbone, classes=classes, aux=aux, model_name="fcn8sd_resnetd50b_ade20k", data_format=data_format, **kwargs) def fcn8sd_resnetd101b_ade20k(pretrained_backbone=False, classes=150, aux=True, data_format="channels_last", **kwargs): """ FCN-8s(d) model on the base of ResNet(D)-101b for ADE20K from 'Fully Convolutional Networks for Semantic Segmentation,' https://arxiv.org/abs/1411.4038. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_fcn8sd(backbone=backbone, classes=classes, aux=aux, model_name="fcn8sd_resnetd101b_ade20k", data_format=data_format, **kwargs) def fcn8sd_resnetd50b_cityscapes(pretrained_backbone=False, classes=19, aux=True, data_format="channels_last", **kwargs): """ FCN-8s(d) model on the base of ResNet(D)-50b for Cityscapes from 'Fully Convolutional Networks for Semantic Segmentation,' https://arxiv.org/abs/1411.4038. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_fcn8sd(backbone=backbone, classes=classes, aux=aux, model_name="fcn8sd_resnetd50b_cityscapes", data_format=data_format, **kwargs) def fcn8sd_resnetd101b_cityscapes(pretrained_backbone=False, classes=19, aux=True, data_format="channels_last", **kwargs): """ FCN-8s(d) model on the base of ResNet(D)-101b for Cityscapes from 'Fully Convolutional Networks for Semantic Segmentation,' https://arxiv.org/abs/1411.4038. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_fcn8sd(backbone=backbone, classes=classes, aux=aux, model_name="fcn8sd_resnetd101b_cityscapes", data_format=data_format, **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" in_size = (480, 480) aux = False pretrained = False models = [ (fcn8sd_resnetd50b_voc, 21), (fcn8sd_resnetd101b_voc, 21), (fcn8sd_resnetd50b_coco, 21), (fcn8sd_resnetd101b_coco, 21), (fcn8sd_resnetd50b_ade20k, 150), (fcn8sd_resnetd101b_ade20k, 150), (fcn8sd_resnetd50b_cityscapes, 19), (fcn8sd_resnetd101b_cityscapes, 19), ] for model, classes in models: net = model(pretrained=pretrained, in_size=in_size, aux=aux, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, in_size[0], in_size[1]) if is_channels_first(data_format) else (batch, in_size[0], in_size[1], 3)) ys = net(x) y = ys[0] if aux else ys assert (y.shape[0] == x.shape[0]) if is_channels_first(data_format): assert ((y.shape[1] == classes) and (y.shape[2] == x.shape[2]) and (y.shape[3] == x.shape[3])) else: assert ((y.shape[3] == classes) and (y.shape[1] == x.shape[1]) and (y.shape[2] == x.shape[2])) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) if aux: assert (model != fcn8sd_resnetd50b_voc or weight_count == 35445994) assert (model != fcn8sd_resnetd101b_voc or weight_count == 54438122) assert (model != fcn8sd_resnetd50b_coco or weight_count == 35445994) assert (model != fcn8sd_resnetd101b_coco or weight_count == 54438122) assert (model != fcn8sd_resnetd50b_ade20k or weight_count == 35545324) assert (model != fcn8sd_resnetd101b_ade20k or weight_count == 54537452) assert (model != fcn8sd_resnetd50b_cityscapes or weight_count == 35444454) assert (model != fcn8sd_resnetd101b_cityscapes or weight_count == 54436582) else: assert (model != fcn8sd_resnetd50b_voc or weight_count == 33080789) assert (model != fcn8sd_resnetd101b_voc or weight_count == 52072917) assert (model != fcn8sd_resnetd50b_coco or weight_count == 33080789) assert (model != fcn8sd_resnetd101b_coco or weight_count == 52072917) assert (model != fcn8sd_resnetd50b_ade20k or weight_count == 33146966) assert (model != fcn8sd_resnetd101b_ade20k or weight_count == 52139094) assert (model != fcn8sd_resnetd50b_cityscapes or weight_count == 33079763) assert (model != fcn8sd_resnetd101b_cityscapes or weight_count == 52071891) if __name__ == "__main__": _test()
19,136
40.154839
119
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/selecsls.py
""" SelecSLS for ImageNet-1K, implemented in TensorFlow. Original paper: 'XNect: Real-time Multi-person 3D Human Pose Estimation with a Single RGB Camera,' https://arxiv.org/abs/1907.00837. """ __all__ = ['SelecSLS', 'selecsls42', 'selecsls42b', 'selecsls60', 'selecsls60b', 'selecsls84'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1_block, conv3x3_block, DualPathSequential, AvgPool2d, SimpleSequential, flatten,\ is_channels_first, get_channel_axis class SelecSLSBlock(nn.Layer): """ SelecSLS block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(SelecSLSBlock, self).__init__(**kwargs) mid_channels = 2 * out_channels self.conv1 = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=mid_channels, out_channels=out_channels, data_format=data_format, name="conv2") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) return x class SelecSLSUnit(nn.Layer): """ SelecSLS unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. skip_channels : int Number of skipped channels. mid_channels : int Number of middle channels. strides : int or tuple/list of 2 int Strides of the branch convolution layers. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, skip_channels, mid_channels, strides, data_format="channels_last", **kwargs): super(SelecSLSUnit, self).__init__(**kwargs) self.data_format = data_format self.resize = (strides == 2) mid2_channels = mid_channels // 2 last_channels = 2 * mid_channels + (skip_channels if strides == 1 else 0) self.branch1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels, strides=strides, data_format=data_format, name="branch1") self.branch2 = SelecSLSBlock( in_channels=mid_channels, out_channels=mid2_channels, data_format=data_format, name="branch2") self.branch3 = SelecSLSBlock( in_channels=mid2_channels, out_channels=mid2_channels, data_format=data_format, name="branch3") self.last_conv = conv1x1_block( in_channels=last_channels, out_channels=out_channels, data_format=data_format, name="last_conv") def call(self, x, x0=None, training=None): x1 = self.branch1(x, training=training) x2 = self.branch2(x1, training=training) x3 = self.branch3(x2, training=training) if self.resize: y = tf.concat([x1, x2, x3], axis=get_channel_axis(self.data_format)) y = self.last_conv(y, training=training) return y, y else: y = tf.concat([x1, x2, x3, x0], axis=get_channel_axis(self.data_format)) y = self.last_conv(y, training=training) return y, x0 class SelecSLS(tf.keras.Model): """ SelecSLS model from 'XNect: Real-time Multi-person 3D Human Pose Estimation with a Single RGB Camera,' https://arxiv.org/abs/1907.00837. Parameters: ---------- channels : list of list of int Number of output channels for each unit. skip_channels : list of list of int Number of skipped channels for each unit. mid_channels : list of list of int Number of middle channels for each unit. kernels3 : list of list of int/bool Using 3x3 (instead of 1x1) kernel for each head unit. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, skip_channels, mid_channels, kernels3, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(SelecSLS, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format init_block_channels = 32 self.features = DualPathSequential( return_two=False, first_ordinals=1, last_ordinals=(1 + len(kernels3)), name="features") self.features.add(conv3x3_block( in_channels=in_channels, out_channels=init_block_channels, strides=2, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): k = i - len(skip_channels) stage = DualPathSequential(name="stage{}".format(i + 1)) if k < 0 else\ SimpleSequential(name="stage{}".format(i + 1)) for j, out_channels in enumerate(channels_per_stage): strides = 2 if j == 0 else 1 if k < 0: unit = SelecSLSUnit( in_channels=in_channels, out_channels=out_channels, skip_channels=skip_channels[i][j], mid_channels=mid_channels[i][j], strides=strides, data_format=data_format, name="unit{}".format(j + 1)) else: conv_block_class = conv3x3_block if kernels3[k][j] == 1 else conv1x1_block unit = conv_block_class( in_channels=in_channels, out_channels=out_channels, strides=strides, data_format=data_format, name="unit{}".format(j + 1)) stage.add(unit) in_channels = out_channels self.features.add(stage) self.features.add(AvgPool2d( pool_size=4, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_selecsls(version, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create SelecSLS model with specific parameters. Parameters: ---------- version : str Version of SelecSLS. 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if version in ("42", "42b"): channels = [[64, 128], [144, 288], [304, 480]] skip_channels = [[0, 64], [0, 144], [0, 304]] mid_channels = [[64, 64], [144, 144], [304, 304]] kernels3 = [[1, 1], [1, 0]] if version == "42": head_channels = [[960, 1024], [1024, 1280]] else: head_channels = [[960, 1024], [1280, 1024]] elif version in ("60", "60b"): channels = [[64, 128], [128, 128, 288], [288, 288, 288, 416]] skip_channels = [[0, 64], [0, 128, 128], [0, 288, 288, 288]] mid_channels = [[64, 64], [128, 128, 128], [288, 288, 288, 288]] kernels3 = [[1, 1], [1, 0]] if version == "60": head_channels = [[756, 1024], [1024, 1280]] else: head_channels = [[756, 1024], [1280, 1024]] elif version == "84": channels = [[64, 144], [144, 144, 144, 144, 304], [304, 304, 304, 304, 304, 512]] skip_channels = [[0, 64], [0, 144, 144, 144, 144], [0, 304, 304, 304, 304, 304]] mid_channels = [[64, 64], [144, 144, 144, 144, 144], [304, 304, 304, 304, 304, 304]] kernels3 = [[1, 1], [1, 1]] head_channels = [[960, 1024], [1024, 1280]] else: raise ValueError("Unsupported SelecSLS version {}".format(version)) channels += head_channels net = SelecSLS( channels=channels, skip_channels=skip_channels, mid_channels=mid_channels, kernels3=kernels3, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def selecsls42(**kwargs): """ SelecSLS-42 model from 'XNect: Real-time Multi-person 3D Human Pose Estimation with a Single RGB Camera,' https://arxiv.org/abs/1907.00837. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_selecsls(version="42", model_name="selecsls42", **kwargs) def selecsls42b(**kwargs): """ SelecSLS-42b model from 'XNect: Real-time Multi-person 3D Human Pose Estimation with a Single RGB Camera,' https://arxiv.org/abs/1907.00837. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_selecsls(version="42b", model_name="selecsls42b", **kwargs) def selecsls60(**kwargs): """ SelecSLS-60 model from 'XNect: Real-time Multi-person 3D Human Pose Estimation with a Single RGB Camera,' https://arxiv.org/abs/1907.00837. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_selecsls(version="60", model_name="selecsls60", **kwargs) def selecsls60b(**kwargs): """ SelecSLS-60b model from 'XNect: Real-time Multi-person 3D Human Pose Estimation with a Single RGB Camera,' https://arxiv.org/abs/1907.00837. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_selecsls(version="60b", model_name="selecsls60b", **kwargs) def selecsls84(**kwargs): """ SelecSLS-84 model from 'XNect: Real-time Multi-person 3D Human Pose Estimation with a Single RGB Camera,' https://arxiv.org/abs/1907.00837. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_selecsls(version="84", model_name="selecsls84", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" pretrained = False models = [ selecsls42, selecsls42b, selecsls60, selecsls60b, selecsls84, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != selecsls42 or weight_count == 30354952) assert (model != selecsls42b or weight_count == 32458248) assert (model != selecsls60 or weight_count == 30670768) assert (model != selecsls60b or weight_count == 32774064) assert (model != selecsls84 or weight_count == 50954600) if __name__ == "__main__": _test()
13,913
33.698254
115
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/inceptionv4.py
""" InceptionV4 for ImageNet-1K, implemented in TensorFlow. Original paper: 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,' https://arxiv.org/abs/1602.07261. """ __all__ = ['InceptionV4', 'inceptionv4'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import ConvBlock, conv3x3_block, SimpleSequential, Concurrent, flatten, is_channels_first, get_channel_axis from .inceptionv3 import MaxPoolBranch, AvgPoolBranch, Conv1x1Branch, ConvSeqBranch class Conv3x3Branch(nn.Layer): """ InceptionV4 specific convolutional 3x3 branch block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, bn_eps, data_format="channels_last", **kwargs): super(Conv3x3Branch, self).__init__(**kwargs) self.conv = conv3x3_block( in_channels=in_channels, out_channels=out_channels, strides=2, padding=0, bn_eps=bn_eps, data_format=data_format, name="conv") def call(self, x, training=None): x = self.conv(x, training=training) return x class ConvSeq3x3Branch(nn.Layer): """ InceptionV4 specific convolutional sequence branch block with splitting by 3x3. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. mid_channels_list : list of tuple of int List of numbers of output channels for middle layers. 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_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, mid_channels_list, kernel_size_list, strides_list, padding_list, bn_eps, data_format="channels_last", **kwargs): super(ConvSeq3x3Branch, self).__init__(**kwargs) self.data_format = data_format self.conv_list = SimpleSequential(name="conv_list") for i, (mid_channels, kernel_size, strides, padding) in enumerate(zip( mid_channels_list, kernel_size_list, strides_list, padding_list)): self.conv_list.children.append(ConvBlock( in_channels=in_channels, out_channels=mid_channels, kernel_size=kernel_size, strides=strides, padding=padding, bn_eps=bn_eps, data_format=data_format, name="conv{}".format(i + 1))) in_channels = mid_channels self.conv1x3 = ConvBlock( in_channels=in_channels, out_channels=out_channels, kernel_size=(1, 3), strides=1, padding=(0, 1), bn_eps=bn_eps, data_format=data_format, name="conv1x3") self.conv3x1 = ConvBlock( in_channels=in_channels, out_channels=out_channels, kernel_size=(3, 1), strides=1, padding=(1, 0), bn_eps=bn_eps, data_format=data_format, name="conv3x1") def call(self, x, training=None): x = self.conv_list(x, training=training) y1 = self.conv1x3(x, training=training) y2 = self.conv3x1(x, training=training) x = tf.concat([y1, y2], axis=get_channel_axis(self.data_format)) return x class InceptionAUnit(nn.Layer): """ InceptionV4 type Inception-A unit. Parameters: ---------- bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, bn_eps, data_format="channels_last", **kwargs): super(InceptionAUnit, self).__init__(**kwargs) in_channels = 384 self.branches = Concurrent( data_format=data_format, name="branches") self.branches.children.append(Conv1x1Branch( in_channels=in_channels, out_channels=96, bn_eps=bn_eps, data_format=data_format, name="branch1")) self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=(64, 96), kernel_size_list=(1, 3), strides_list=(1, 1), padding_list=(0, 1), bn_eps=bn_eps, data_format=data_format, name="branch2")) self.branches.children.append(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_eps=bn_eps, data_format=data_format, name="branch3")) self.branches.children.append(AvgPoolBranch( in_channels=in_channels, out_channels=96, bn_eps=bn_eps, count_include_pad=False, data_format=data_format, name="branch4")) def call(self, x, training=None): x = self.branches(x, training=training) return x class ReductionAUnit(nn.Layer): """ InceptionV4 type Reduction-A unit. Parameters: ---------- bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, bn_eps, data_format="channels_last", **kwargs): super(ReductionAUnit, self).__init__(**kwargs) in_channels = 384 self.branches = Concurrent( data_format=data_format, name="branches") self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=(384,), kernel_size_list=(3,), strides_list=(2,), padding_list=(0,), bn_eps=bn_eps, data_format=data_format, name="branch1")) self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=(192, 224, 256), kernel_size_list=(1, 3, 3), strides_list=(1, 1, 2), padding_list=(0, 1, 0), bn_eps=bn_eps, data_format=data_format, name="branch2")) self.branches.children.append(MaxPoolBranch( data_format=data_format, name="branch3")) def call(self, x, training=None): x = self.branches(x, training=training) return x class InceptionBUnit(nn.Layer): """ InceptionV4 type Inception-B unit. Parameters: ---------- bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, bn_eps, data_format="channels_last", **kwargs): super(InceptionBUnit, self).__init__(**kwargs) in_channels = 1024 self.branches = Concurrent( data_format=data_format, name="branches") self.branches.children.append(Conv1x1Branch( in_channels=in_channels, out_channels=384, bn_eps=bn_eps, data_format=data_format, name="branch1")) self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=(192, 224, 256), kernel_size_list=(1, (1, 7), (7, 1)), strides_list=(1, 1, 1), padding_list=(0, (0, 3), (3, 0)), bn_eps=bn_eps, data_format=data_format, name="branch2")) self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=(192, 192, 224, 224, 256), 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_eps=bn_eps, data_format=data_format, name="branch3")) self.branches.children.append(AvgPoolBranch( in_channels=in_channels, out_channels=128, bn_eps=bn_eps, count_include_pad=False, data_format=data_format, name="branch4")) def call(self, x, training=None): x = self.branches(x, training=training) return x class ReductionBUnit(nn.Layer): """ InceptionV4 type Reduction-B unit. Parameters: ---------- bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, bn_eps, data_format="channels_last", **kwargs): super(ReductionBUnit, self).__init__(**kwargs) in_channels = 1024 self.branches = Concurrent( data_format=data_format, name="branches") self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=(192, 192), kernel_size_list=(1, 3), strides_list=(1, 2), padding_list=(0, 0), bn_eps=bn_eps, data_format=data_format, name="branch1")) self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=(256, 256, 320, 320), kernel_size_list=(1, (1, 7), (7, 1), 3), strides_list=(1, 1, 1, 2), padding_list=(0, (0, 3), (3, 0), 0), bn_eps=bn_eps, data_format=data_format, name="branch2")) self.branches.children.append(MaxPoolBranch( data_format=data_format, name="branch3")) def call(self, x, training=None): x = self.branches(x, training=training) return x class InceptionCUnit(nn.Layer): """ InceptionV4 type Inception-C unit. Parameters: ---------- bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, bn_eps, data_format="channels_last", **kwargs): super(InceptionCUnit, self).__init__(**kwargs) in_channels = 1536 self.branches = Concurrent( data_format=data_format, name="branches") self.branches.children.append(Conv1x1Branch( in_channels=in_channels, out_channels=256, bn_eps=bn_eps, data_format=data_format, name="branch1")) self.branches.children.append(ConvSeq3x3Branch( in_channels=in_channels, out_channels=256, mid_channels_list=(384,), kernel_size_list=(1,), strides_list=(1,), padding_list=(0,), bn_eps=bn_eps, data_format=data_format, name="branch2")) self.branches.children.append(ConvSeq3x3Branch( in_channels=in_channels, out_channels=256, mid_channels_list=(384, 448, 512), kernel_size_list=(1, (3, 1), (1, 3)), strides_list=(1, 1, 1), padding_list=(0, (1, 0), (0, 1)), bn_eps=bn_eps, data_format=data_format, name="branch3")) self.branches.children.append(AvgPoolBranch( in_channels=in_channels, out_channels=256, bn_eps=bn_eps, count_include_pad=False, data_format=data_format, name="branch4")) def call(self, x, training=None): x = self.branches(x, training=training) return x class InceptBlock3a(nn.Layer): """ InceptionV4 type Mixed-3a block. Parameters: ---------- bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, bn_eps, data_format="channels_last", **kwargs): super(InceptBlock3a, self).__init__(**kwargs) self.branches = Concurrent( data_format=data_format, name="branches") self.branches.children.append(MaxPoolBranch( data_format=data_format, name="branch1")) self.branches.children.append(Conv3x3Branch( in_channels=64, out_channels=96, bn_eps=bn_eps, data_format=data_format, name="branch2")) def call(self, x, training=None): x = self.branches(x, training=training) return x class InceptBlock4a(nn.Layer): """ InceptionV4 type Mixed-4a block. Parameters: ---------- bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, bn_eps, data_format="channels_last", **kwargs): super(InceptBlock4a, self).__init__(**kwargs) self.branches = Concurrent( data_format=data_format, name="branches") self.branches.children.append(ConvSeqBranch( in_channels=160, out_channels_list=(64, 96), kernel_size_list=(1, 3), strides_list=(1, 1), padding_list=(0, 0), bn_eps=bn_eps, data_format=data_format, name="branch1")) self.branches.children.append(ConvSeqBranch( in_channels=160, out_channels_list=(64, 64, 64, 96), kernel_size_list=(1, (1, 7), (7, 1), 3), strides_list=(1, 1, 1, 1), padding_list=(0, (0, 3), (3, 0), 0), bn_eps=bn_eps, data_format=data_format, name="branch2")) def call(self, x, training=None): x = self.branches(x, training=training) return x class InceptBlock5a(nn.Layer): """ InceptionV4 type Mixed-5a block. Parameters: ---------- bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, bn_eps, data_format="channels_last", **kwargs): super(InceptBlock5a, self).__init__(**kwargs) self.branches = Concurrent( data_format=data_format, name="branches") self.branches.children.append(Conv3x3Branch( in_channels=192, out_channels=192, bn_eps=bn_eps, data_format=data_format, name="branch1")) self.branches.children.append(MaxPoolBranch( data_format=data_format, name="branch2")) def call(self, x, training=None): x = self.branches(x, training=training) return x class InceptInitBlock(nn.Layer): """ InceptionV4 specific initial block. Parameters: ---------- in_channels : int Number of input channels. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, bn_eps, data_format="channels_last", **kwargs): super(InceptInitBlock, self).__init__(**kwargs) self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=32, strides=2, padding=0, bn_eps=bn_eps, data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=32, out_channels=32, strides=1, padding=0, bn_eps=bn_eps, data_format=data_format, name="conv2") self.conv3 = conv3x3_block( in_channels=32, out_channels=64, strides=1, padding=1, bn_eps=bn_eps, data_format=data_format, name="conv3") self.block1 = InceptBlock3a( bn_eps=bn_eps, data_format=data_format, name="block1") self.block2 = InceptBlock4a( bn_eps=bn_eps, data_format=data_format, name="block2") self.block3 = InceptBlock5a( bn_eps=bn_eps, data_format=data_format, name="block3") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.conv3(x, training=training) x = self.block1(x, training=training) x = self.block2(x, training=training) x = self.block3(x, training=training) return x class InceptionV4(tf.keras.Model): """ InceptionV4 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,' https://arxiv.org/abs/1602.07261. Parameters: ---------- dropout_rate : float, default 0.0 Fraction of the input units to drop. Must be a number between 0 and 1. bn_eps : float, default 1e-5 Small float added to variance in Batch norm. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, dropout_rate=0.0, bn_eps=1e-5, in_channels=3, in_size=(299, 299), classes=1000, data_format="channels_last", **kwargs): super(InceptionV4, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format layers = [4, 8, 4] normal_units = [InceptionAUnit, InceptionBUnit, InceptionCUnit] reduction_units = [ReductionAUnit, ReductionBUnit] self.features = SimpleSequential(name="features") self.features.add(InceptInitBlock( in_channels=in_channels, bn_eps=bn_eps, data_format=data_format, name="init_block")) for i, layers_per_stage in enumerate(layers): stage = SimpleSequential(name="stage{}".format(i + 1)) for j in range(layers_per_stage): if (j == 0) and (i != 0): unit = reduction_units[i - 1] else: unit = normal_units[i] stage.add(unit( bn_eps=bn_eps, data_format=data_format, name="unit{}".format(j + 1))) self.features.add(stage) self.features.add(nn.AveragePooling2D( pool_size=8, strides=1, data_format=data_format, name="final_pool")) self.output1 = SimpleSequential(name="output1") if dropout_rate > 0.0: self.output1.add(nn.Dropout( rate=dropout_rate, name="output1/dropout")) self.output1.add(nn.Dense( units=classes, input_dim=1536, name="output1/fc")) def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_inceptionv4(model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create InceptionV4 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ net = InceptionV4(**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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def inceptionv4(**kwargs): """ InceptionV4 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,' https://arxiv.org/abs/1602.07261. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_inceptionv4(model_name="inceptionv4", bn_eps=1e-3, **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ inceptionv4, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 299, 299) if is_channels_first(data_format) else (batch, 299, 299, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != inceptionv4 or weight_count == 42679816) if __name__ == "__main__": _test()
23,613
31.303694
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/regnet.py
""" RegNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678. """ __all__ = ['RegNet', 'regnetx002', 'regnetx004', 'regnetx006', 'regnetx008', 'regnetx016', 'regnetx032', 'regnetx040', 'regnetx064', 'regnetx080', 'regnetx120', 'regnetx160', 'regnetx320', 'regnety002', 'regnety004', 'regnety006', 'regnety008', 'regnety016', 'regnety032', 'regnety040', 'regnety064', 'regnety080', 'regnety120', 'regnety160', 'regnety320'] import os import numpy as np import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1_block, conv3x3_block, SEBlock, SimpleSequential, is_channels_first class RegNetBottleneck(nn.Layer): """ RegNet bottleneck block for residual path in RegNet 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. groups : int Number of groups. use_se : bool Whether to use SE-module. bottleneck_factor : int, default 1 Bottleneck factor. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, groups, use_se, bottleneck_factor=1, data_format="channels_last", **kwargs): super(RegNetBottleneck, self).__init__(**kwargs) self.use_se = use_se mid_channels = out_channels // bottleneck_factor mid_groups = mid_channels // groups self.conv1 = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=mid_channels, out_channels=mid_channels, strides=strides, groups=mid_groups, data_format=data_format, name="conv2") if self.use_se: self.se = SEBlock( channels=mid_channels, mid_channels=(in_channels // 4), data_format=data_format, name="se") self.conv3 = conv1x1_block( in_channels=mid_channels, out_channels=out_channels, activation=None, data_format=data_format, name="conv3") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) if self.use_se: x = self.se(x) x = self.conv3(x, training=training) return x class RegNetUnit(nn.Layer): """ RegNet 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. groups : int Number of groups. use_se : bool Whether to use SE-module. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, groups, use_se, data_format="channels_last", **kwargs): super(RegNetUnit, self).__init__(**kwargs) self.resize_identity = (in_channels != out_channels) or (strides != 1) self.body = RegNetBottleneck( in_channels=in_channels, out_channels=out_channels, strides=strides, groups=groups, use_se=use_se, data_format=data_format, name="body") if self.resize_identity: self.identity_conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, strides=strides, activation=None, data_format=data_format, name="identity_conv") self.activ = nn.ReLU() def call(self, x, training=None): if self.resize_identity: identity = self.identity_conv(x, training=training) else: identity = x x = self.body(x, training=training) x = x + identity x = self.activ(x) return x class RegNet(tf.keras.Model): """ 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. groups : list of int Number of groups for each stage. use_se : bool Whether to use SE-module. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, groups, use_se, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(RegNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(conv3x3_block( in_channels=in_channels, out_channels=init_block_channels, strides=2, padding=1, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, (channels_per_stage, groups_per_stage) in enumerate(zip(channels, groups)): stage = SimpleSequential(name="stage{}".format(i + 1)) for j, out_channels in enumerate(channels_per_stage): stride = 2 if (j == 0) else 1 stage.add(RegNetUnit( in_channels=in_channels, out_channels=out_channels, strides=stride, groups=groups_per_stage, use_se=use_se, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(nn.GlobalAvgPool2D( data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = self.output1(x) return x def get_regnet(channels_init, channels_slope, channels_mult, depth, groups, use_se=False, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "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. groups : int Number of groups. depth : int Depth value. use_se : bool, default False Whether to use SE-module. 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. root : str, default '~/.tensorflow/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) # Adjusts the compatibility of channels/widths and groups: groups_per_stage = [min(groups, c) for c in channels_per_stage] channels_per_stage = [int(round(c / g) * g) for c, g in zip(channels_per_stage, groups_per_stage)] channels = [[ci] * li for (ci, li) in zip(channels_per_stage, layers)] init_block_channels = 32 net = RegNet( channels=channels, init_block_channels=init_block_channels, groups=groups_per_stage, 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def regnetx002(**kwargs): """ RegNetX-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=24, channels_slope=36.44, channels_mult=2.49, depth=13, groups=8, model_name="regnetx002", **kwargs) def regnetx004(**kwargs): """ RegNetX-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=24, channels_slope=24.48, channels_mult=2.54, depth=22, groups=16, model_name="regnetx004", **kwargs) def regnetx006(**kwargs): """ RegNetX-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=48, channels_slope=36.97, channels_mult=2.24, depth=16, groups=24, model_name="regnetx006", **kwargs) def regnetx008(**kwargs): """ RegNetX-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=56, channels_slope=35.73, channels_mult=2.28, depth=16, groups=16, model_name="regnetx008", **kwargs) def regnetx016(**kwargs): """ RegNetX-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=80, channels_slope=34.01, channels_mult=2.25, depth=18, groups=24, model_name="regnetx016", **kwargs) def regnetx032(**kwargs): """ RegNetX-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=88, channels_slope=26.31, channels_mult=2.25, depth=25, groups=48, model_name="regnetx032", **kwargs) def regnetx040(**kwargs): """ RegNetX-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=96, channels_slope=38.65, channels_mult=2.43, depth=23, groups=40, model_name="regnetx040", **kwargs) def regnetx064(**kwargs): """ RegNetX-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=184, channels_slope=60.83, channels_mult=2.07, depth=17, groups=56, model_name="regnetx064", **kwargs) def regnetx080(**kwargs): """ RegNetX-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=80, channels_slope=49.56, channels_mult=2.88, depth=23, groups=120, model_name="regnetx080", **kwargs) def regnetx120(**kwargs): """ RegNetX-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=168, channels_slope=73.36, channels_mult=2.37, depth=19, groups=112, model_name="regnetx120", **kwargs) def regnetx160(**kwargs): """ RegNetX-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=216, channels_slope=55.59, channels_mult=2.1, depth=22, groups=128, model_name="regnetx160", **kwargs) def regnetx320(**kwargs): """ RegNetX-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=320, channels_slope=69.86, channels_mult=2.0, depth=23, groups=168, model_name="regnetx320", **kwargs) def regnety002(**kwargs): """ RegNetY-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=24, channels_slope=36.44, channels_mult=2.49, depth=13, groups=8, use_se=True, model_name="regnety002", **kwargs) def regnety004(**kwargs): """ RegNetY-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=48, channels_slope=27.89, channels_mult=2.09, depth=16, groups=8, use_se=True, model_name="regnety004", **kwargs) def regnety006(**kwargs): """ RegNetY-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=48, channels_slope=32.54, channels_mult=2.32, depth=15, groups=16, use_se=True, model_name="regnety006", **kwargs) def regnety008(**kwargs): """ RegNetY-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=56, channels_slope=38.84, channels_mult=2.4, depth=14, groups=16, use_se=True, model_name="regnety008", **kwargs) def regnety016(**kwargs): """ RegNetY-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=48, channels_slope=20.71, channels_mult=2.65, depth=27, groups=24, use_se=True, model_name="regnety016", **kwargs) def regnety032(**kwargs): """ RegNetY-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=80, channels_slope=42.63, channels_mult=2.66, depth=21, groups=24, use_se=True, model_name="regnety032", **kwargs) def regnety040(**kwargs): """ RegNetY-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=96, channels_slope=31.41, channels_mult=2.24, depth=22, groups=64, use_se=True, model_name="regnety040", **kwargs) def regnety064(**kwargs): """ RegNetY-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=112, channels_slope=33.22, channels_mult=2.27, depth=25, groups=72, use_se=True, model_name="regnety064", **kwargs) def regnety080(**kwargs): """ RegNetY-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=192, channels_slope=76.82, channels_mult=2.19, depth=17, groups=56, use_se=True, model_name="regnety080", **kwargs) def regnety120(**kwargs): """ RegNetY-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=168, channels_slope=73.36, channels_mult=2.37, depth=19, groups=112, use_se=True, model_name="regnety120", **kwargs) def regnety160(**kwargs): """ RegNetY-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=200, channels_slope=106.23, channels_mult=2.48, depth=18, groups=112, use_se=True, model_name="regnety160", **kwargs) def regnety320(**kwargs): """ RegNetY-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_regnet(channels_init=232, channels_slope=115.89, channels_mult=2.53, depth=20, groups=232, use_se=True, model_name="regnety320", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" pretrained = False models = [ regnetx002, regnetx004, regnetx006, regnetx008, regnetx016, regnetx032, regnetx040, regnetx064, regnetx080, regnetx120, regnetx160, regnetx320, regnety002, regnety004, regnety006, regnety008, regnety016, regnety032, regnety040, regnety064, regnety080, regnety120, regnety160, regnety320, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 size = 224 x = tf.random.normal((batch, 3, size, size) if is_channels_first(data_format) else (batch, size, size, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != regnetx002 or weight_count == 2684792) assert (model != regnetx004 or weight_count == 5157512) assert (model != regnetx006 or weight_count == 6196040) assert (model != regnetx008 or weight_count == 7259656) assert (model != regnetx016 or weight_count == 9190136) assert (model != regnetx032 or weight_count == 15296552) assert (model != regnetx040 or weight_count == 22118248) assert (model != regnetx064 or weight_count == 26209256) assert (model != regnetx080 or weight_count == 39572648) assert (model != regnetx120 or weight_count == 46106056) assert (model != regnetx160 or weight_count == 54278536) assert (model != regnetx320 or weight_count == 107811560) assert (model != regnety002 or weight_count == 3162996) assert (model != regnety004 or weight_count == 4344144) assert (model != regnety006 or weight_count == 6055160) assert (model != regnety008 or weight_count == 6263168) assert (model != regnety016 or weight_count == 11202430) assert (model != regnety032 or weight_count == 19436338) assert (model != regnety040 or weight_count == 20646656) assert (model != regnety064 or weight_count == 30583252) assert (model != regnety080 or weight_count == 39180068) assert (model != regnety120 or weight_count == 51822544) assert (model != regnety160 or weight_count == 83590140) assert (model != regnety320 or weight_count == 145046770) if __name__ == "__main__": _test()
25,743
33.978261
118
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/icnet.py
""" ICNet for image segmentation, implemented in TensorFlow. Original paper: 'ICNet for Real-Time Semantic Segmentation on High-Resolution Images,' https://arxiv.org/abs/1704.08545. """ __all__ = ['ICNet', 'icnet_resnetd50b_cityscapes'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1, conv1x1_block, conv3x3_block, InterpolationBlock, MultiOutputSequential, is_channels_first from .pspnet import PyramidPooling from .resnetd import resnetd50b class ICInitBlock(nn.Layer): """ ICNet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(ICInitBlock, self).__init__(**kwargs) mid_channels = out_channels // 2 self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels, strides=2, data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=mid_channels, out_channels=mid_channels, strides=2, data_format=data_format, name="conv2") self.conv3 = conv3x3_block( in_channels=mid_channels, out_channels=out_channels, strides=2, data_format=data_format, name="conv3") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.conv3(x, training=training) return x class PSPBlock(nn.Layer): """ ICNet specific PSPNet reduced head block. 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. bottleneck_factor : int Bottleneck factor. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, upscale_out_size, bottleneck_factor, data_format="channels_last", **kwargs): super(PSPBlock, self).__init__(**kwargs) assert (in_channels % bottleneck_factor == 0) mid_channels = in_channels // bottleneck_factor self.pool = PyramidPooling( in_channels=in_channels, upscale_out_size=upscale_out_size, data_format=data_format, name="pool") self.conv = conv3x3_block( in_channels=4096, out_channels=mid_channels, data_format=data_format, name="conv") self.dropout = nn.Dropout( rate=0.1, name="dropout") def call(self, x, training=None): x = self.pool(x, training=training) x = self.conv(x, training=training) x = self.dropout(x, training=training) return x class CFFBlock(nn.Layer): """ Cascade Feature Fusion block. Parameters: ---------- in_channels_low : int Number of input channels (low input). in_channels_high : int Number of input channels (low high). out_channels : int Number of output channels. classes : int Number of classification classes. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels_low, in_channels_high, out_channels, classes, data_format="channels_last", **kwargs): super(CFFBlock, self).__init__(**kwargs) self.up = InterpolationBlock( scale_factor=2, data_format=data_format, name="up") self.conv_low = conv3x3_block( in_channels=in_channels_low, out_channels=out_channels, padding=2, dilation=2, activation=None, data_format=data_format, name="conv_low") self.conv_hign = conv1x1_block( in_channels=in_channels_high, out_channels=out_channels, activation=None, data_format=data_format, name="conv_hign") self.activ = nn.ReLU() self.conv_cls = conv1x1( in_channels=out_channels, out_channels=classes, data_format=data_format, name="conv_cls") def call(self, xl, xh, training=None): xl = self.up(xl) xl = self.conv_low(xl, training=training) xh = self.conv_hign(xh, training=training) x = xl + xh x = self.activ(x) x_cls = self.conv_cls(xl) return x, x_cls class ICHeadBlock(nn.Layer): """ ICNet head block. Parameters: ---------- classes : int Number of classification classes. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, classes, data_format="channels_last", **kwargs): super(ICHeadBlock, self).__init__(**kwargs) self.cff_12 = CFFBlock( in_channels_low=128, in_channels_high=64, out_channels=128, classes=classes, data_format=data_format, name="cff_12") self.cff_24 = CFFBlock( in_channels_low=256, in_channels_high=256, out_channels=128, classes=classes, data_format=data_format, name="cff_24") self.up_x2 = InterpolationBlock( scale_factor=2, data_format=data_format, name="up_x2") self.up_x8 = InterpolationBlock( scale_factor=4, data_format=data_format, name="up_x8") self.conv_cls = conv1x1( in_channels=128, out_channels=classes, data_format=data_format, name="conv_cls") def call(self, x1, x2, x4, training=None): outputs = [] x_cff_24, x_24_cls = self.cff_24(x4, x2, training=training) outputs.append(x_24_cls) x_cff_12, x_12_cls = self.cff_12(x_cff_24, x1, training=training) outputs.append(x_12_cls) up_x2 = self.up_x2(x_cff_12) up_x2 = self.conv_cls(up_x2) outputs.append(up_x2) up_x8 = self.up_x8(up_x2) outputs.append(up_x8) # 1 -> 1/4 -> 1/8 -> 1/16 outputs.reverse() return tuple(outputs) class ICNet(tf.keras.Model): """ ICNet model from 'ICNet for Real-Time Semantic Segmentation on High-Resolution Images,' https://arxiv.org/abs/1704.08545. Parameters: ---------- backbones : tuple of nn.Sequential Feature extractors. backbones_out_channels : tuple of int Number of output channels form each feature extractor. classes : tuple of int Number of output channels for each branch. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, backbones, backbones_out_channels, channels, aux=False, fixed_size=True, in_channels=3, in_size=(480, 480), classes=21, data_format="channels_last", **kwargs): super(ICNet, 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 self.data_format = data_format psp_pool_out_size = (self.in_size[0] // 32, self.in_size[1] // 32) if fixed_size else None psp_head_out_channels = 512 self.branch1 = ICInitBlock( in_channels=in_channels, out_channels=channels[0], data_format=data_format, name="branch1") self.branch2 = MultiOutputSequential(name="branch2") self.branch2.add(InterpolationBlock( scale_factor=2, up=False, data_format=data_format, name="down1")) backbones[0].do_output = True self.branch2.add(backbones[0]) self.branch2.add(InterpolationBlock( scale_factor=2, up=False, data_format=data_format, name="down2")) self.branch2.add(backbones[1]) self.branch2.add(PSPBlock( in_channels=backbones_out_channels[1], upscale_out_size=psp_pool_out_size, bottleneck_factor=4, data_format=data_format, name="psp")) self.branch2.add(conv1x1_block( in_channels=psp_head_out_channels, out_channels=channels[2], data_format=data_format, name="final_block")) self.conv_y2 = conv1x1_block( in_channels=backbones_out_channels[0], out_channels=channels[1], data_format=data_format, name="conv_y2") self.final_block = ICHeadBlock( classes=classes, data_format=data_format, name="final_block") def call(self, x, training=None): y1 = self.branch1(x, training=training) y3, y2 = self.branch2(x, training=training) y2 = self.conv_y2(y2, training=training) x = self.final_block(y1, y2, y3, training=training) if self.aux: return x else: return x[0] def get_icnet(backbones, backbones_out_channels, classes, aux=False, model_name=None, data_format="channels_last", pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create ICNet model with specific parameters. Parameters: ---------- backbones : tuple of nn.Sequential Feature extractors. backbones_out_channels : tuple of int Number of output channels form each 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ channels = (64, 256, 256) backbones[0].multi_output = False backbones[1].multi_output = False net = ICNet( backbones=backbones, backbones_out_channels=backbones_out_channels, channels=channels, classes=classes, aux=aux, data_format=data_format, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root), by_name=True, skip_mismatch=True) return net def icnet_resnetd50b_cityscapes(pretrained_backbone=False, classes=19, aux=True, data_format="channels_last", **kwargs): """ ICNet model on the base of ResNet(D)-50b for Cityscapes from 'ICNet for Real-Time Semantic Segmentation on High-Resolution Images,' https://arxiv.org/abs/1704.08545. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone1 = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=None, data_format=data_format).features for i in range(len(backbone1) - 3): # backbone1.children.pop() del backbone1.children[-1] backbone2 = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=None, data_format=data_format).features # backbone2.children.pop() del backbone2.children[-1] for i in range(3): # backbone2.children.pop(0) del backbone2.children[0] backbones = (backbone1, backbone2) backbones_out_channels = (512, 2048) return get_icnet(backbones=backbones, backbones_out_channels=backbones_out_channels, classes=classes, aux=aux, model_name="icnet_resnetd50b_cityscapes", data_format=data_format, **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" in_size = (480, 480) aux = False fixed_size = False pretrained = False models = [ (icnet_resnetd50b_cityscapes, 19), ] for model, classes in models: net = model(pretrained=pretrained, in_size=in_size, aux=aux, fixed_size=fixed_size, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, in_size[0], in_size[1]) if is_channels_first(data_format) else (batch, in_size[0], in_size[1], 3)) ys = net(x) y = ys[0] if aux else ys assert (y.shape[0] == x.shape[0]) if is_channels_first(data_format): assert ((y.shape[1] == classes) and (y.shape[2] == x.shape[2]) and (y.shape[3] == x.shape[3])) else: assert ((y.shape[3] == classes) and (y.shape[1] == x.shape[1]) and (y.shape[2] == x.shape[2])) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != icnet_resnetd50b_cityscapes or weight_count == 47489184) if __name__ == "__main__": _test()
15,700
31.985294
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/mobilenetb.py
""" MobileNet(B) with simplified depthwise separable convolution block for ImageNet-1K, implemented in TensorFlow. Original paper: 'MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications,' https://arxiv.org/abs/1704.04861. """ __all__ = ['mobilenetb_w1', 'mobilenetb_w3d4', 'mobilenetb_wd2', 'mobilenetb_wd4'] from .mobilenet import get_mobilenet def mobilenetb_w1(**kwargs): """ 1.0 MobileNet(B)-224 model with simplified depthwise separable convolution block 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mobilenet(width_scale=1.0, dws_simplified=True, model_name="mobilenetb_w1", **kwargs) def mobilenetb_w3d4(**kwargs): """ 0.75 MobileNet(B)-224 model with simplified depthwise separable convolution block 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mobilenet(width_scale=0.75, dws_simplified=True, model_name="mobilenetb_w3d4", **kwargs) def mobilenetb_wd2(**kwargs): """ 0.5 MobileNet(B)-224 model with simplified depthwise separable convolution block 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mobilenet(width_scale=0.5, dws_simplified=True, model_name="mobilenetb_wd2", **kwargs) def mobilenetb_wd4(**kwargs): """ 0.25 MobileNet(B)-224 model with simplified depthwise separable convolution block 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mobilenet(width_scale=0.25, dws_simplified=True, model_name="mobilenetb_wd4", **kwargs) def _test(): import numpy as np import tensorflow as tf import tensorflow.keras.backend as K pretrained = False models = [ mobilenetb_w1, mobilenetb_w3d4, mobilenetb_wd2, mobilenetb_wd4, ] for model in models: net = model(pretrained=pretrained) batch = 14 x = tf.random.normal((batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != mobilenetb_w1 or weight_count == 4222056) assert (model != mobilenetb_w3d4 or weight_count == 2578120) assert (model != mobilenetb_wd2 or weight_count == 1326632) assert (model != mobilenetb_wd4 or weight_count == 467592) if __name__ == "__main__": _test()
3,684
34.095238
114
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/inceptionresnetv1.py
""" InceptionResNetV1 for ImageNet-1K, implemented in TensorFlow. Original paper: 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,' https://arxiv.org/abs/1602.07261. """ __all__ = ['InceptionResNetV1', 'inceptionresnetv1', 'InceptionAUnit', 'InceptionBUnit', 'InceptionCUnit', 'ReductionAUnit', 'ReductionBUnit'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import MaxPool2d, BatchNorm, conv1x1, conv1x1_block, conv3x3_block, Concurrent, flatten,\ is_channels_first, SimpleSequential from .inceptionv3 import MaxPoolBranch, Conv1x1Branch, ConvSeqBranch class InceptionAUnit(nn.Layer): """ InceptionResNetV1 type Inception-A unit. Parameters: ---------- in_channels : int Number of input channels. out_channels_list : list of int List for numbers of output channels. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels_list, bn_eps, data_format="channels_last", **kwargs): super(InceptionAUnit, self).__init__(**kwargs) self.scale = 0.17 self.branches = Concurrent( data_format=data_format, name="branches") self.branches.children.append(Conv1x1Branch( in_channels=in_channels, out_channels=out_channels_list[0], bn_eps=bn_eps, data_format=data_format, name="branch1")) self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=out_channels_list[1:3], kernel_size_list=(1, 3), strides_list=(1, 1), padding_list=(0, 1), bn_eps=bn_eps, data_format=data_format, name="branch2")) self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=out_channels_list[3:6], kernel_size_list=(1, 3, 3), strides_list=(1, 1, 1), padding_list=(0, 1, 1), bn_eps=bn_eps, data_format=data_format, name="branch3")) conv_in_channels = out_channels_list[0] + out_channels_list[2] + out_channels_list[5] self.conv = conv1x1( in_channels=conv_in_channels, out_channels=in_channels, use_bias=True, data_format=data_format, name="conv") self.activ = nn.ReLU() def call(self, x, training=None): identity = x x = self.branches(x, training=training) x = self.conv(x, training=training) x = self.scale * x + identity x = self.activ(x) return x class InceptionBUnit(nn.Layer): """ InceptionResNetV1 type Inception-B unit. Parameters: ---------- in_channels : int Number of input channels. out_channels_list : list of int List for numbers of output channels. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels_list, bn_eps, data_format="channels_last", **kwargs): super(InceptionBUnit, self).__init__(**kwargs) self.scale = 0.10 self.branches = Concurrent( data_format=data_format, name="branches") self.branches.children.append(Conv1x1Branch( in_channels=in_channels, out_channels=out_channels_list[0], bn_eps=bn_eps, data_format=data_format, name="branch1")) self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=out_channels_list[1:4], kernel_size_list=(1, (1, 7), (7, 1)), strides_list=(1, 1, 1), padding_list=(0, (0, 3), (3, 0)), bn_eps=bn_eps, data_format=data_format, name="branch2")) conv_in_channels = out_channels_list[0] + out_channels_list[3] self.conv = conv1x1( in_channels=conv_in_channels, out_channels=in_channels, use_bias=True, data_format=data_format, name="conv") self.activ = nn.ReLU() def call(self, x, training=None): identity = x x = self.branches(x, training=training) x = self.conv(x, training=training) x = self.scale * x + identity x = self.activ(x) return x class InceptionCUnit(nn.Layer): """ InceptionResNetV1 type Inception-C unit. Parameters: ---------- in_channels : int Number of input channels. out_channels_list : list of int List for numbers of output channels. bn_eps : float Small float added to variance in Batch norm. scale : float, default 1.0 Scale value for residual branch. activate : bool, default True Whether activate the convolution block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels_list, bn_eps, scale=0.2, activate=True, data_format="channels_last", **kwargs): super(InceptionCUnit, self).__init__(**kwargs) self.activate = activate self.scale = scale self.branches = Concurrent( data_format=data_format, name="branches") self.branches.children.append(Conv1x1Branch( in_channels=in_channels, out_channels=out_channels_list[0], bn_eps=bn_eps, data_format=data_format, name="branch1")) self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=out_channels_list[1:4], kernel_size_list=(1, (1, 3), (3, 1)), strides_list=(1, 1, 1), padding_list=(0, (0, 1), (1, 0)), bn_eps=bn_eps, data_format=data_format, name="branch2")) conv_in_channels = out_channels_list[0] + out_channels_list[3] self.conv = conv1x1( in_channels=conv_in_channels, out_channels=in_channels, use_bias=True, data_format=data_format, name="conv") if self.activate: self.activ = nn.ReLU() def call(self, x, training=None): identity = x x = self.branches(x, training=training) x = self.conv(x, training=training) x = self.scale * x + identity if self.activate: x = self.activ(x) return x class ReductionAUnit(nn.Layer): """ InceptionResNetV1 type Reduction-A unit. Parameters: ---------- in_channels : int Number of input channels. out_channels_list : list of int List for numbers of output channels. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels_list, bn_eps, data_format="channels_last", **kwargs): super(ReductionAUnit, self).__init__(**kwargs) self.branches = Concurrent( data_format=data_format, name="branches") self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=out_channels_list[0:1], kernel_size_list=(3,), strides_list=(2,), padding_list=(0,), bn_eps=bn_eps, data_format=data_format, name="branch1")) self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=out_channels_list[1:4], kernel_size_list=(1, 3, 3), strides_list=(1, 1, 2), padding_list=(0, 1, 0), bn_eps=bn_eps, data_format=data_format, name="branch2")) self.branches.children.append(MaxPoolBranch( data_format=data_format, name="branch3")) def call(self, x, training=None): x = self.branches(x, training=training) return x class ReductionBUnit(nn.Layer): """ InceptionResNetV1 type Reduction-B unit. Parameters: ---------- in_channels : int Number of input channels. out_channels_list : list of int List for numbers of output channels. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels_list, bn_eps, data_format="channels_last", **kwargs): super(ReductionBUnit, self).__init__(**kwargs) self.branches = Concurrent( data_format=data_format, name="branches") self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=out_channels_list[0:2], kernel_size_list=(1, 3), strides_list=(1, 2), padding_list=(0, 0), bn_eps=bn_eps, data_format=data_format, name="branch1")) self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=out_channels_list[2:4], kernel_size_list=(1, 3), strides_list=(1, 2), padding_list=(0, 0), bn_eps=bn_eps, data_format=data_format, name="branch2")) self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=out_channels_list[4:7], kernel_size_list=(1, 3, 3), strides_list=(1, 1, 2), padding_list=(0, 1, 0), bn_eps=bn_eps, data_format=data_format, name="branch3")) self.branches.children.append(MaxPoolBranch( data_format=data_format, name="branch4")) def call(self, x, training=None): x = self.branches(x, training=training) return x class InceptInitBlock(nn.Layer): """ InceptionResNetV1 specific initial block. Parameters: ---------- in_channels : int Number of input channels. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, bn_eps, in_channels, data_format="channels_last", **kwargs): super(InceptInitBlock, self).__init__(**kwargs) self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=32, strides=2, padding=0, bn_eps=bn_eps, data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=32, out_channels=32, strides=1, padding=0, bn_eps=bn_eps, data_format=data_format, name="conv2") self.conv3 = conv3x3_block( in_channels=32, out_channels=64, strides=1, padding=1, bn_eps=bn_eps, data_format=data_format, name="conv3") self.pool = MaxPool2d( pool_size=3, strides=2, padding=0, data_format=data_format, name="pool") self.conv4 = conv1x1_block( in_channels=64, out_channels=80, strides=1, padding=0, bn_eps=bn_eps, data_format=data_format, name="conv4") self.conv5 = conv3x3_block( in_channels=80, out_channels=192, strides=1, padding=0, bn_eps=bn_eps, data_format=data_format, name="conv5") self.conv6 = conv3x3_block( in_channels=192, out_channels=256, strides=2, padding=0, bn_eps=bn_eps, data_format=data_format, name="conv6") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.conv3(x, training=training) x = self.pool(x) x = self.conv4(x, training=training) x = self.conv5(x, training=training) x = self.conv6(x, training=training) return x class InceptHead(nn.Layer): """ InceptionResNetV1 specific classification block. Parameters: ---------- in_channels : int Number of input channels. bn_eps : float Small float added to variance in Batch norm. dropout_rate : float Fraction of the input units to drop. Must be a number between 0 and 1. classes : int Number of classification classes. """ def __init__(self, in_channels, bn_eps, dropout_rate, classes, data_format="channels_last", **kwargs): super(InceptHead, self).__init__(**kwargs) self.data_format = data_format self.use_dropout = (dropout_rate != 0.0) if dropout_rate > 0.0: self.dropout = nn.Dropout( rate=dropout_rate, name="dropout") self.fc1 = nn.Dense( units=512, input_dim=in_channels, use_bias=False, name="fc1") self.bn = BatchNorm( epsilon=bn_eps, data_format=data_format, name="bn") self.fc2 = nn.Dense( units=classes, input_dim=512, name="fc2") def call(self, x, training=None): x = flatten(x, self.data_format) if self.use_dropout: x = self.dropout(x, training=training) x = self.fc1(x) x = self.bn(x, training=training) x = self.fc2(x) return x class InceptionResNetV1(tf.keras.Model): """ InceptionResNetV1 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,' https://arxiv.org/abs/1602.07261. Parameters: ---------- dropout_rate : float, default 0.0 Fraction of the input units to drop. Must be a number between 0 and 1. bn_eps : float, default 1e-5 Small float added to variance in Batch norm. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, dropout_rate=0.0, bn_eps=1e-5, in_channels=3, in_size=(299, 299), classes=1000, data_format="channels_last", **kwargs): super(InceptionResNetV1, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format layers = [5, 11, 7] in_channels_list = [256, 896, 1792] normal_out_channels_list = [[32, 32, 32, 32, 32, 32], [128, 128, 128, 128], [192, 192, 192, 192]] reduction_out_channels_list = [[384, 192, 192, 256], [256, 384, 256, 256, 256, 256, 256]] normal_units = [InceptionAUnit, InceptionBUnit, InceptionCUnit] reduction_units = [ReductionAUnit, ReductionBUnit] self.features = SimpleSequential(name="features") self.features.add(InceptInitBlock( in_channels=in_channels, bn_eps=bn_eps, data_format=data_format, name="init_block")) in_channels = in_channels_list[0] for i, layers_per_stage in enumerate(layers): stage = SimpleSequential(name="stage{}".format(i + 1)) for j in range(layers_per_stage): if (j == 0) and (i != 0): unit = reduction_units[i - 1] out_channels_list_per_stage = reduction_out_channels_list[i - 1] else: unit = normal_units[i] out_channels_list_per_stage = normal_out_channels_list[i] if (i == len(layers) - 1) and (j == layers_per_stage - 1): unit_kwargs = {"scale": 1.0, "activate": False} else: unit_kwargs = {} stage.add(unit( in_channels=in_channels, out_channels_list=out_channels_list_per_stage, bn_eps=bn_eps, data_format=data_format, name="unit{}".format(j + 1), **unit_kwargs)) if (j == 0) and (i != 0): in_channels = in_channels_list[i] self.features.add(stage) self.features.add(nn.AveragePooling2D( pool_size=8, strides=1, data_format=data_format, name="final_pool")) self.output1 = InceptHead( in_channels=in_channels, bn_eps=bn_eps, dropout_rate=dropout_rate, classes=classes, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = self.output1(x, training=training) return x def get_inceptionresnetv1(model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create InceptionResNetV1 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ net = InceptionResNetV1(**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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def inceptionresnetv1(**kwargs): """ InceptionResNetV1 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,' https://arxiv.org/abs/1602.07261. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_inceptionresnetv1(model_name="inceptionresnetv1", bn_eps=1e-3, **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ inceptionresnetv1, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 299, 299) if is_channels_first(data_format) else (batch, 299, 299, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != inceptionresnetv1 or weight_count == 23995624) if __name__ == "__main__": _test()
20,969
32.127962
117
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/scnet.py
""" SCNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'Improving Convolutional Networks with Self-Calibrated Convolutions,' http://mftp.mmcheng.net/Papers/20cvprSCNet.pdf. """ __all__ = ['SCNet', 'scnet50', 'scnet101', 'scneta50', 'scneta101'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1_block, conv3x3_block, AvgPool2d, InterpolationBlock, SimpleSequential, get_channel_axis,\ get_im_size, is_channels_first from .resnet import ResInitBlock from .senet import SEInitBlock from .resnesta import ResNeStADownBlock class ScDownBlock(nn.Layer): """ SCNet specific convolutional downscale block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. pool_size: int or list/tuple of 2 ints, default 2 Size of the average pooling windows. """ def __init__(self, in_channels, out_channels, pool_size=2, data_format="channels_last", **kwargs): super(ScDownBlock, self).__init__(**kwargs) self.pool = AvgPool2d( pool_size=pool_size, strides=pool_size, data_format=data_format, name="pool") self.conv = conv3x3_block( in_channels=in_channels, out_channels=out_channels, activation=None, data_format=data_format, name="conv") def call(self, x, training=None): x = self.pool(x) x = self.conv(x, training=training) return x class ScConv(nn.Layer): """ Self-calibrated convolutional 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. scale_factor : int Scale factor. """ def __init__(self, in_channels, out_channels, strides, scale_factor, data_format="channels_last", **kwargs): super(ScConv, self).__init__(**kwargs) self.data_format = data_format self.down = ScDownBlock( in_channels=in_channels, out_channels=out_channels, pool_size=scale_factor, data_format=data_format, name="down") self.up = InterpolationBlock( scale_factor=scale_factor, interpolation="nearest", data_format=data_format, name="up") self.sigmoid = tf.nn.sigmoid self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=in_channels, activation=None, data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=in_channels, out_channels=out_channels, strides=strides, data_format=data_format, name="conv2") def call(self, x, training=None): in_size = get_im_size(x, data_format=self.data_format) w = self.sigmoid(x + self.up(self.down(x, training=training), size=in_size)) x = self.conv1(x, training=training) * w x = self.conv2(x, training=training) return x class ScBottleneck(nn.Layer): """ SCNet specific bottleneck block for residual path in SCNet 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, default 4 Bottleneck factor. scale_factor : int, default 4 Scale factor. avg_downsample : bool, default False Whether to use average downsampling. """ def __init__(self, in_channels, out_channels, strides, bottleneck_factor=4, scale_factor=4, avg_downsample=False, data_format="channels_last", **kwargs): super(ScBottleneck, self).__init__(**kwargs) self.data_format = data_format self.avg_resize = (strides > 1) and avg_downsample mid_channels = out_channels // bottleneck_factor // 2 self.conv1a = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv1a") self.conv2a = conv3x3_block( in_channels=mid_channels, out_channels=mid_channels, strides=(1 if self.avg_resize else strides), data_format=data_format, name="conv2a") self.conv1b = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv1b") self.conv2b = ScConv( in_channels=mid_channels, out_channels=mid_channels, strides=(1 if self.avg_resize else strides), scale_factor=scale_factor, data_format=data_format, name="conv2b") if self.avg_resize: self.pool = AvgPool2d( pool_size=3, strides=strides, padding=1, data_format=data_format, name="pool") self.conv3 = conv1x1_block( in_channels=(2 * mid_channels), out_channels=out_channels, activation=None, data_format=data_format, name="conv3") def call(self, x, training=None): y = self.conv1a(x, training=training) y = self.conv2a(y, training=training) z = self.conv1b(x, training=training) z = self.conv2b(z, training=training) if self.avg_resize: y = self.pool(y) z = self.pool(z) x = tf.concat([y, z], axis=get_channel_axis(self.data_format)) x = self.conv3(x) return x class ScUnit(nn.Layer): """ SCNet 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. avg_downsample : bool, default False Whether to use average downsampling. """ def __init__(self, in_channels, out_channels, strides, avg_downsample=False, data_format="channels_last", **kwargs): super(ScUnit, self).__init__(**kwargs) self.resize_identity = (in_channels != out_channels) or (strides != 1) self.body = ScBottleneck( in_channels=in_channels, out_channels=out_channels, strides=strides, avg_downsample=avg_downsample, data_format=data_format, name="body") if self.resize_identity: if avg_downsample: self.identity_block = ResNeStADownBlock( in_channels=in_channels, out_channels=out_channels, strides=strides, data_format=data_format, name="identity_block") else: self.identity_block = conv1x1_block( in_channels=in_channels, out_channels=out_channels, strides=strides, activation=None, data_format=data_format, name="identity_block") self.activ = nn.ReLU() def call(self, x, training=None): if self.resize_identity: identity = self.identity_block(x, training=training) else: identity = x x = self.body(x, training=training) x = x + identity x = self.activ(x) return x class SCNet(tf.keras.Model): """ SCNet model from 'Improving Convolutional Networks with Self-Calibrated Convolutions,' http://mftp.mmcheng.net/Papers/20cvprSCNet.pdf. 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. se_init_block : bool, default False SENet-like initial block. avg_downsample : bool, default False Whether to use average downsampling. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, se_init_block=False, avg_downsample=False, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(SCNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") init_block_class = SEInitBlock if se_init_block else ResInitBlock self.features.add(init_block_class( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(ScUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, avg_downsample=avg_downsample, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(nn.GlobalAvgPool2D( data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = self.output1(x) return x def get_scnet(blocks, width_scale=1.0, se_init_block=False, avg_downsample=False, init_block_channels_scale=1, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create SCNet model with specific parameters. Parameters: ---------- blocks : int Number of blocks. width_scale : float, default 1.0 Scale factor for width of layers. se_init_block : bool, default False SENet-like initial block. avg_downsample : bool, default False Whether to use average downsampling. init_block_channels_scale : int, default 1 Scale factor for number of output channels in the initial unit. 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. root : str, default '~/.tensorflow/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] elif blocks == 152: layers = [3, 8, 36, 3] elif blocks == 200: layers = [3, 24, 36, 3] else: raise ValueError("Unsupported SCNet with number of blocks: {}".format(blocks)) assert (sum(layers) * 3 + 2 == blocks) init_block_channels = 64 channels_per_layers = [64, 128, 256, 512] init_block_channels *= init_block_channels_scale 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 = SCNet( channels=channels, init_block_channels=init_block_channels, se_init_block=se_init_block, avg_downsample=avg_downsample, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def scnet50(**kwargs): """ SCNet-50 model from 'Improving Convolutional Networks with Self-Calibrated Convolutions,' http://mftp.mmcheng.net/Papers/20cvprSCNet.pdf. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_scnet(blocks=50, model_name="scnet50", **kwargs) def scnet101(**kwargs): """ SCNet-101 model from 'Improving Convolutional Networks with Self-Calibrated Convolutions,' http://mftp.mmcheng.net/Papers/20cvprSCNet.pdf. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_scnet(blocks=101, model_name="scnet101", **kwargs) def scneta50(**kwargs): """ SCNet(A)-50 with average downsampling model from 'Improving Convolutional Networks with Self-Calibrated Convolutions,' http://mftp.mmcheng.net/Papers/20cvprSCNet.pdf. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_scnet(blocks=50, se_init_block=True, avg_downsample=True, model_name="scneta50", **kwargs) def scneta101(**kwargs): """ SCNet(A)-101 with average downsampling model from 'Improving Convolutional Networks with Self-Calibrated Convolutions,' http://mftp.mmcheng.net/Papers/20cvprSCNet.pdf. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_scnet(blocks=101, se_init_block=True, avg_downsample=True, init_block_channels_scale=2, model_name="scneta101", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" pretrained = False models = [ scnet50, scnet101, scneta50, scneta101, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != scnet50 or weight_count == 25564584) assert (model != scnet101 or weight_count == 44565416) assert (model != scneta50 or weight_count == 25583816) assert (model != scneta101 or weight_count == 44689192) if __name__ == "__main__": _test()
17,161
31.751908
117
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/igcv3.py
""" IGCV3 for ImageNet-1K, implemented in TensorFlow. Original paper: 'IGCV3: Interleaved Low-Rank Group Convolutions for Efficient Deep Neural Networks,' https://arxiv.org/abs/1806.00178. """ __all__ = ['IGCV3', 'igcv3_w1', 'igcv3_w3d4', 'igcv3_wd2', 'igcv3_wd4'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1_block, conv3x3_block, dwconv3x3_block, ChannelShuffle, ReLU6, SimpleSequential, flatten class InvResUnit(nn.Layer): """ So-called 'Inverted Residual Unit' layer. 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. expansion : bool Whether do expansion of channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, expansion, data_format="channels_last", **kwargs): super(InvResUnit, self).__init__(**kwargs) self.residual = (in_channels == out_channels) and (strides == 1) mid_channels = in_channels * 6 if expansion else in_channels groups = 2 self.conv1 = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, groups=groups, activation=None, data_format=data_format, name="conv1") self.c_shuffle = ChannelShuffle( channels=mid_channels, groups=groups, data_format=data_format, name="c_shuffle") self.conv2 = dwconv3x3_block( in_channels=mid_channels, out_channels=mid_channels, strides=strides, activation=ReLU6(), data_format=data_format, name="conv2") self.conv3 = conv1x1_block( in_channels=mid_channels, out_channels=out_channels, groups=groups, activation=None, data_format=data_format, name="conv3") def call(self, x, training=None): if self.residual: identity = x x = self.conv1(x, training=training) x = self.c_shuffle(x) x = self.conv2(x, training=training) x = self.conv3(x, training=training) if self.residual: x = x + identity return x class IGCV3(tf.keras.Model): """ IGCV3 model from 'IGCV3: Interleaved Low-Rank Group Convolutions for Efficient Deep Neural Networks,' https://arxiv.org/abs/1806.00178. 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, final_block_channels, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(IGCV3, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(conv3x3_block( in_channels=in_channels, out_channels=init_block_channels, strides=2, activation=ReLU6(), data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) for j, out_channels in enumerate(channels_per_stage): strides = 2 if (j == 0) and (i != 0) else 1 expansion = (i != 0) or (j != 0) stage.add(InvResUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, expansion=expansion, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(conv1x1_block( in_channels=in_channels, out_channels=final_block_channels, activation=ReLU6(), data_format=data_format, name="final_block")) in_channels = final_block_channels self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_igcv3(width_scale, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create IGCV3-D 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ init_block_channels = 32 final_block_channels = 1280 layers = [1, 4, 6, 8, 6, 6, 1] downsample = [0, 1, 1, 1, 0, 1, 0] channels_per_layers = [16, 24, 32, 64, 96, 160, 320] from functools import reduce channels = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]], zip(channels_per_layers, layers, downsample), [[]]) if width_scale != 1.0: def make_even(x): return x if (x % 2 == 0) else x + 1 channels = [[make_even(int(cij * width_scale)) for cij in ci] for ci in channels] init_block_channels = make_even(int(init_block_channels * width_scale)) if width_scale > 1.0: final_block_channels = make_even(int(final_block_channels * width_scale)) net = IGCV3( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def igcv3_w1(**kwargs): """ IGCV3-D 1.0x model from 'IGCV3: Interleaved Low-Rank Group Convolutions for Efficient Deep Neural Networks,' https://arxiv.org/abs/1806.00178. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_igcv3(width_scale=1.0, model_name="igcv3_w1", **kwargs) def igcv3_w3d4(**kwargs): """ IGCV3-D 0.75x model from 'IGCV3: Interleaved Low-Rank Group Convolutions for Efficient Deep Neural Networks,' https://arxiv.org/abs/1806.00178. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_igcv3(width_scale=0.75, model_name="igcv3_w3d4", **kwargs) def igcv3_wd2(**kwargs): """ IGCV3-D 0.5x model from 'IGCV3: Interleaved Low-Rank Group Convolutions for Efficient Deep Neural Networks,' https://arxiv.org/abs/1806.00178. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_igcv3(width_scale=0.5, model_name="igcv3_wd2", **kwargs) def igcv3_wd4(**kwargs): """ IGCV3-D 0.25x model from 'IGCV3: Interleaved Low-Rank Group Convolutions for Efficient Deep Neural Networks,' https://arxiv.org/abs/1806.00178. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_igcv3(width_scale=0.25, model_name="igcv3_wd4", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K pretrained = False models = [ igcv3_w1, igcv3_w3d4, igcv3_wd2, igcv3_wd4, ] for model in models: net = model(pretrained=pretrained) batch = 14 x = tf.random.normal((batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != igcv3_w1 or weight_count == 3491688) assert (model != igcv3_w3d4 or weight_count == 2638084) assert (model != igcv3_wd2 or weight_count == 1985528) assert (model != igcv3_wd4 or weight_count == 1534020) if __name__ == "__main__": _test()
10,739
32.667712
115
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/seresnet_cifar.py
""" SE-ResNet for CIFAR/SVHN, implemented in TensorFlow. Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. """ __all__ = ['CIFARSEResNet', 'seresnet20_cifar10', 'seresnet20_cifar100', 'seresnet20_svhn', 'seresnet56_cifar10', 'seresnet56_cifar100', 'seresnet56_svhn', 'seresnet110_cifar10', 'seresnet110_cifar100', 'seresnet110_svhn', 'seresnet164bn_cifar10', 'seresnet164bn_cifar100', 'seresnet164bn_svhn', 'seresnet272bn_cifar10', 'seresnet272bn_cifar100', 'seresnet272bn_svhn', 'seresnet542bn_cifar10', 'seresnet542bn_cifar100', 'seresnet542bn_svhn', 'seresnet1001_cifar10', 'seresnet1001_cifar100', 'seresnet1001_svhn', 'seresnet1202_cifar10', 'seresnet1202_cifar100', 'seresnet1202_svhn'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv3x3_block, SimpleSequential, flatten, is_channels_first from .seresnet import SEResUnit class CIFARSEResNet(tf.keras.Model): """ SE-ResNet model for CIFAR 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, bottleneck, in_channels=3, in_size=(32, 32), classes=10, data_format="channels_last", **kwargs): super(CIFARSEResNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(conv3x3_block( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(SEResUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, bottleneck=bottleneck, conv1_stride=False, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(nn.AveragePooling2D( pool_size=8, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_seresnet_cifar(classes, blocks, bottleneck, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create SE-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. root : str, default '~/.tensorflow/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 = CIFARSEResNet( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def seresnet20_cifar10(classes=10, **kwargs): """ SE-ResNet-20 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="seresnet20_cifar10", **kwargs) def seresnet20_cifar100(classes=100, **kwargs): """ SE-ResNet-20 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="seresnet20_cifar100", **kwargs) def seresnet20_svhn(classes=10, **kwargs): """ SE-ResNet-20 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="seresnet20_svhn", **kwargs) def seresnet56_cifar10(classes=10, **kwargs): """ SE-ResNet-56 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name="seresnet56_cifar10", **kwargs) def seresnet56_cifar100(classes=100, **kwargs): """ SE-ResNet-56 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name="seresnet56_cifar100", **kwargs) def seresnet56_svhn(classes=10, **kwargs): """ SE-ResNet-56 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name="seresnet56_svhn", **kwargs) def seresnet110_cifar10(classes=10, **kwargs): """ SE-ResNet-110 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name="seresnet110_cifar10", **kwargs) def seresnet110_cifar100(classes=100, **kwargs): """ SE-ResNet-110 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name="seresnet110_cifar100", **kwargs) def seresnet110_svhn(classes=10, **kwargs): """ SE-ResNet-110 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name="seresnet110_svhn", **kwargs) def seresnet164bn_cifar10(classes=10, **kwargs): """ SE-ResNet-164(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name="seresnet164bn_cifar10", **kwargs) def seresnet164bn_cifar100(classes=100, **kwargs): """ SE-ResNet-164(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name="seresnet164bn_cifar100", **kwargs) def seresnet164bn_svhn(classes=10, **kwargs): """ SE-ResNet-164(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name="seresnet164bn_svhn", **kwargs) def seresnet272bn_cifar10(classes=10, **kwargs): """ SE-ResNet-272(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name="seresnet272bn_cifar10", **kwargs) def seresnet272bn_cifar100(classes=100, **kwargs): """ SE-ResNet-272(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name="seresnet272bn_cifar100", **kwargs) def seresnet272bn_svhn(classes=10, **kwargs): """ SE-ResNet-272(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name="seresnet272bn_svhn", **kwargs) def seresnet542bn_cifar10(classes=10, **kwargs): """ SE-ResNet-542(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name="seresnet542bn_cifar10", **kwargs) def seresnet542bn_cifar100(classes=100, **kwargs): """ SE-ResNet-542(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name="seresnet542bn_cifar100", **kwargs) def seresnet542bn_svhn(classes=10, **kwargs): """ SE-ResNet-542(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name="seresnet542bn_svhn", **kwargs) def seresnet1001_cifar10(classes=10, **kwargs): """ SE-ResNet-1001 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="seresnet1001_cifar10", **kwargs) def seresnet1001_cifar100(classes=100, **kwargs): """ SE-ResNet-1001 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="seresnet1001_cifar100", **kwargs) def seresnet1001_svhn(classes=10, **kwargs): """ SE-ResNet-1001 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="seresnet1001_svhn", **kwargs) def seresnet1202_cifar10(classes=10, **kwargs): """ SE-ResNet-1202 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name="seresnet1202_cifar10", **kwargs) def seresnet1202_cifar100(classes=100, **kwargs): """ SE-ResNet-1202 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name="seresnet1202_cifar100", **kwargs) def seresnet1202_svhn(classes=10, **kwargs): """ SE-ResNet-1202 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name="seresnet1202_svhn", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" pretrained = False models = [ (seresnet20_cifar10, 10), (seresnet20_cifar100, 100), (seresnet20_svhn, 10), (seresnet56_cifar10, 10), (seresnet56_cifar100, 100), (seresnet56_svhn, 10), (seresnet110_cifar10, 10), (seresnet110_cifar100, 100), (seresnet110_svhn, 10), (seresnet164bn_cifar10, 10), (seresnet164bn_cifar100, 100), (seresnet164bn_svhn, 10), (seresnet272bn_cifar10, 10), (seresnet272bn_cifar100, 100), (seresnet272bn_svhn, 10), (seresnet542bn_cifar10, 10), (seresnet542bn_cifar100, 100), (seresnet542bn_svhn, 10), (seresnet1001_cifar10, 10), (seresnet1001_cifar100, 100), (seresnet1001_svhn, 10), (seresnet1202_cifar10, 10), (seresnet1202_cifar100, 100), (seresnet1202_svhn, 10), ] for model, classes in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 32, 32) if is_channels_first(data_format) else (batch, 32, 32, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, classes)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != seresnet20_cifar10 or weight_count == 274847) assert (model != seresnet20_cifar100 or weight_count == 280697) assert (model != seresnet20_svhn or weight_count == 274847) assert (model != seresnet56_cifar10 or weight_count == 862889) assert (model != seresnet56_cifar100 or weight_count == 868739) assert (model != seresnet56_svhn or weight_count == 862889) assert (model != seresnet110_cifar10 or weight_count == 1744952) assert (model != seresnet110_cifar100 or weight_count == 1750802) assert (model != seresnet110_svhn or weight_count == 1744952) assert (model != seresnet164bn_cifar10 or weight_count == 1906258) assert (model != seresnet164bn_cifar100 or weight_count == 1929388) assert (model != seresnet164bn_svhn or weight_count == 1906258) assert (model != seresnet272bn_cifar10 or weight_count == 3153826) assert (model != seresnet272bn_cifar100 or weight_count == 3176956) assert (model != seresnet272bn_svhn or weight_count == 3153826) assert (model != seresnet542bn_cifar10 or weight_count == 6272746) assert (model != seresnet542bn_cifar100 or weight_count == 6295876) assert (model != seresnet542bn_svhn or weight_count == 6272746) assert (model != seresnet1001_cifar10 or weight_count == 11574910) assert (model != seresnet1001_cifar100 or weight_count == 11598040) assert (model != seresnet1001_svhn or weight_count == 11574910) assert (model != seresnet1202_cifar10 or weight_count == 19582226) assert (model != seresnet1202_cifar100 or weight_count == 19588076) assert (model != seresnet1202_svhn or weight_count == 19582226) if __name__ == "__main__": _test()
23,745
36.692063
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/resnetd.py
""" ResNet(D) with dilation for ImageNet-1K, implemented in TensorFlow. Original paper: 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. """ __all__ = ['ResNetD', 'resnetd50b', 'resnetd101b', 'resnetd152b'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import MultiOutputSequential, SimpleSequential, is_channels_first from .resnet import ResUnit, ResInitBlock from .senet import SEInitBlock class ResNetD(tf.keras.Model): """ ResNet(D) with dilation 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. ordinary_init : bool, default False Whether to use original initial block or SENet one. bends : tuple of int, default None Numbers of bends for multiple output. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, bottleneck, conv1_stride, ordinary_init=False, bends=None, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(ResNetD, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.multi_output = (bends is not None) self.data_format = data_format self.features = MultiOutputSequential(name="features") if ordinary_init: self.features.add(ResInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) else: init_block_channels = 2 * init_block_channels self.features.add(SEInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) for j, out_channels in enumerate(channels_per_stage): strides = 2 if ((j == 0) and (i != 0) and (i < 2)) else 1 dilation = (2 ** max(0, i - 1 - int(j == 0))) stage.add(ResUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, padding=dilation, dilation=dilation, bottleneck=bottleneck, conv1_stride=conv1_stride, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels if self.multi_output and ((i + 1) in bends): stage.do_output = True self.features.add(stage) self.features.add(nn.GlobalAvgPool2D( data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): outs = self.features(x, training=training) x = outs[0] x = self.output1(x) if self.multi_output: return [x] + outs[1:] else: return x def get_resnetd(blocks, conv1_stride=True, width_scale=1.0, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create ResNet(D) with dilation 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. 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if blocks == 10: layers = [1, 1, 1, 1] elif blocks == 12: layers = [2, 1, 1, 1] elif blocks == 14: layers = [2, 2, 1, 1] elif blocks == 16: layers = [2, 2, 2, 1] elif 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 ResNet(D) 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)] 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 = ResNetD( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def resnetd50b(**kwargs): """ ResNet(D)-50 with dilation 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnetd(blocks=50, conv1_stride=False, model_name="resnetd50b", **kwargs) def resnetd101b(**kwargs): """ ResNet(D)-101 with dilation 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnetd(blocks=101, conv1_stride=False, model_name="resnetd101b", **kwargs) def resnetd152b(**kwargs): """ ResNet(D)-152 with dilation 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnetd(blocks=152, conv1_stride=False, model_name="resnetd152b", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" ordinary_init = False bends = None pretrained = False models = [ resnetd50b, resnetd101b, resnetd152b, ] for model in models: net = model( pretrained=pretrained, ordinary_init=ordinary_init, bends=bends, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) if bends is not None: y = y[0] assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) if ordinary_init: assert (model != resnetd50b or weight_count == 25557032) assert (model != resnetd101b or weight_count == 44549160) assert (model != resnetd152b or weight_count == 60192808) else: assert (model != resnetd50b or weight_count == 25680808) assert (model != resnetd101b or weight_count == 44672936) assert (model != resnetd152b or weight_count == 60316584) if __name__ == "__main__": _test()
10,194
34.034364
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/quartznet.py
""" QuartzNet for ASR, implemented in TensorFlow. Original paper: 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable Convolutions,' https://arxiv.org/abs/1910.10261. """ __all__ = ['quartznet5x5_en_ls', 'quartznet15x5_en', 'quartznet15x5_en_nr', 'quartznet15x5_fr', 'quartznet15x5_de', 'quartznet15x5_it', 'quartznet15x5_es', 'quartznet15x5_ca', 'quartznet15x5_pl', 'quartznet15x5_ru', 'quartznet15x5_ru34'] from .jasper import get_jasper from .common import is_channels_first def quartznet5x5_en_ls(classes=29, **kwargs): """ QuartzNet 5x5 model for English language (trained on LibriSpeech dataset) from 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable Convolutions,' https://arxiv.org/abs/1910.10261. Parameters: ---------- classes : int, default 29 Number of classification classes (number of graphemes). pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ vocabulary = [' ', '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', "'"] return get_jasper(classes=classes, version=("quartznet", "5x5"), use_dw=True, vocabulary=vocabulary, model_name="quartznet5x5_en_ls", **kwargs) def quartznet15x5_en(classes=29, **kwargs): """ QuartzNet 15x5 model for English language from 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable Convolutions,' https://arxiv.org/abs/1910.10261. Parameters: ---------- classes : int, default 29 Number of classification classes (number of graphemes). pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ vocabulary = [' ', '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', "'"] return get_jasper(classes=classes, version=("quartznet", "15x5"), use_dw=True, vocabulary=vocabulary, model_name="quartznet15x5_en", **kwargs) def quartznet15x5_en_nr(classes=29, **kwargs): """ QuartzNet 15x5 model for English language (with presence of noise) from 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable Convolutions,' https://arxiv.org/abs/1910.10261. Parameters: ---------- classes : int, default 29 Number of classification classes (number of graphemes). pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ vocabulary = [' ', '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', "'"] return get_jasper(classes=classes, version=("quartznet", "15x5"), use_dw=True, vocabulary=vocabulary, model_name="quartznet15x5_en_nr", **kwargs) def quartznet15x5_fr(classes=43, **kwargs): """ QuartzNet 15x5 model for French language from 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable Convolutions,' https://arxiv.org/abs/1910.10261. Parameters: ---------- classes : int, default 43 Number of classification classes (number of graphemes). pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ vocabulary = [' ', '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', "'", 'ç', 'é', 'â', 'ê', 'î', 'ô', 'û', 'à', 'è', 'ù', 'ë', 'ï', 'ü', 'ÿ'] return get_jasper(classes=classes, version=("quartznet", "15x5"), use_dw=True, vocabulary=vocabulary, model_name="quartznet15x5_fr", **kwargs) def quartznet15x5_de(classes=32, **kwargs): """ QuartzNet 15x5 model for German language from 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable Convolutions,' https://arxiv.org/abs/1910.10261. Parameters: ---------- classes : int, default 32 Number of classification classes (number of graphemes). pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ vocabulary = [' ', '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', 'ä', 'ö', 'ü', 'ß'] return get_jasper(classes=classes, version=("quartznet", "15x5"), use_dw=True, vocabulary=vocabulary, model_name="quartznet15x5_de", **kwargs) def quartznet15x5_it(classes=39, **kwargs): """ QuartzNet 15x5 model for Italian language from 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable Convolutions,' https://arxiv.org/abs/1910.10261. Parameters: ---------- classes : int, default 39 Number of classification classes (number of graphemes). pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ vocabulary = [' ', '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', "'", 'à', 'é', 'è', 'í', 'ì', 'î', 'ó', 'ò', 'ú', 'ù'] return get_jasper(classes=classes, version=("quartznet", "15x5"), use_dw=True, vocabulary=vocabulary, model_name="quartznet15x5_it", **kwargs) def quartznet15x5_es(classes=36, **kwargs): """ QuartzNet 15x5 model for Spanish language from 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable Convolutions,' https://arxiv.org/abs/1910.10261. Parameters: ---------- classes : int, default 36 Number of classification classes (number of graphemes). pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ vocabulary = [' ', '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', "'", 'á', 'é', 'í', 'ó', 'ú', 'ñ', 'ü'] return get_jasper(classes=classes, version=("quartznet", "15x5"), use_dw=True, vocabulary=vocabulary, model_name="quartznet15x5_es", **kwargs) def quartznet15x5_ca(classes=39, **kwargs): """ QuartzNet 15x5 model for Spanish language from 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable Convolutions,' https://arxiv.org/abs/1910.10261. Parameters: ---------- classes : int, default 39 Number of classification classes (number of graphemes). pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ vocabulary = [' ', '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', "'", 'à', 'é', 'è', 'í', 'ï', 'ó', 'ò', 'ú', 'ü', 'ŀ'] return get_jasper(classes=classes, version=("quartznet", "15x5"), use_dw=True, vocabulary=vocabulary, model_name="quartznet15x5_ca", **kwargs) def quartznet15x5_pl(classes=34, **kwargs): """ QuartzNet 15x5 model for Spanish language from 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable Convolutions,' https://arxiv.org/abs/1910.10261. Parameters: ---------- classes : int, default 34 Number of classification classes (number of graphemes). pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ vocabulary = [' ', 'a', 'ą', 'b', 'c', 'ć', 'd', 'e', 'ę', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'ł', 'm', 'n', 'ń', 'o', 'ó', 'p', 'r', 's', 'ś', 't', 'u', 'w', 'y', 'z', 'ź', 'ż'] return get_jasper(classes=classes, version=("quartznet", "15x5"), use_dw=True, vocabulary=vocabulary, model_name="quartznet15x5_pl", **kwargs) def quartznet15x5_ru(classes=35, **kwargs): """ QuartzNet 15x5 model for Russian language from 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable Convolutions,' https://arxiv.org/abs/1910.10261. Parameters: ---------- classes : int, default 35 Number of classification classes (number of graphemes). pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ vocabulary = [' ', 'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я'] return get_jasper(classes=classes, version=("quartznet", "15x5"), use_dw=True, vocabulary=vocabulary, model_name="quartznet15x5_ru", **kwargs) def quartznet15x5_ru34(classes=34, **kwargs): """ QuartzNet 15x5 model for Russian language (32 graphemes) from 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable Convolutions,' https://arxiv.org/abs/1910.10261. Parameters: ---------- classes : int, default 34 Number of classification classes (number of graphemes). pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' Location for keeping the model parameters. """ vocabulary = [' ', 'а', 'б', 'в', 'г', 'д', 'е', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я'] return get_jasper(classes=classes, version=("quartznet", "15x5"), use_dw=True, vocabulary=vocabulary, model_name="quartznet15x5_ru34", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K import tensorflow as tf data_format = "channels_last" # data_format = "channels_first" pretrained = False from_audio = True audio_features = 64 models = [ quartznet5x5_en_ls, quartznet15x5_en, quartznet15x5_en_nr, quartznet15x5_fr, quartznet15x5_de, quartznet15x5_it, quartznet15x5_es, quartznet15x5_ca, quartznet15x5_pl, quartznet15x5_ru, quartznet15x5_ru34, ] for model in models: net = model( in_channels=audio_features, from_audio=from_audio, pretrained=pretrained, data_format=data_format) 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) if is_channels_first(data_format) else (batch, seq_len_max, audio_features)) x = tf.random.normal(shape=x_shape) x_len = tf.convert_to_tensor(seq_len.astype(np.long)) y, y_len = net(x, x_len) assert (y.shape.as_list()[0] == batch) classes_id = 1 if is_channels_first(data_format) else 2 seq_id = 2 if is_channels_first(data_format) else 1 assert (y.shape.as_list()[classes_id] == net.classes) if from_audio: assert (y.shape.as_list()[seq_id] in range(seq_len_max // aud_scale * 2, seq_len_max // aud_scale * 2 + 9)) else: assert (y.shape.as_list()[seq_id] in [seq_len_max // 2, seq_len_max // 2 + 1]) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != quartznet5x5_en_ls or weight_count == 6713181) assert (model != quartznet15x5_en or weight_count == 18924381) assert (model != quartznet15x5_en_nr or weight_count == 18924381) assert (model != quartznet15x5_fr or weight_count == 18938731) assert (model != quartznet15x5_de or weight_count == 18927456) assert (model != quartznet15x5_it or weight_count == 18934631) assert (model != quartznet15x5_es or weight_count == 18931556) assert (model != quartznet15x5_ca or weight_count == 18934631) assert (model != quartznet15x5_pl or weight_count == 18929506) assert (model != quartznet15x5_ru or weight_count == 18930531) assert (model != quartznet15x5_ru34 or weight_count == 18929506) if __name__ == "__main__": _test()
13,642
43.439739
119
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/preresnet.py
""" PreResNet for ImageNet-1K, implemented in TensorFlow. Original papers: 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. """ __all__ = ['PreResNet', 'preresnet10', 'preresnet12', 'preresnet14', 'preresnetbc14b', 'preresnet16', 'preresnet18_wd4', 'preresnet18_wd2', 'preresnet18_w3d4', 'preresnet18', 'preresnet26', 'preresnetbc26b', 'preresnet34', 'preresnetbc38b', 'preresnet50', 'preresnet50b', 'preresnet101', 'preresnet101b', 'preresnet152', 'preresnet152b', 'preresnet200', 'preresnet200b', 'preresnet269b', 'PreResBlock', 'PreResBottleneck', 'PreResUnit', 'PreResInitBlock', 'PreResActivation'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import Conv2d, pre_conv1x1_block, pre_conv3x3_block, conv1x1, MaxPool2d, BatchNorm, SimpleSequential,\ flatten class PreResBlock(nn.Layer): """ Simple PreResNet 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. use_bias : bool, default False Whether the layer uses a bias vector. use_bn : bool, default True Whether to use BatchNorm layer. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, use_bias=False, use_bn=True, data_format="channels_last", **kwargs): super(PreResBlock, self).__init__(**kwargs) self.conv1 = pre_conv3x3_block( in_channels=in_channels, out_channels=out_channels, strides=strides, use_bias=use_bias, use_bn=use_bn, return_preact=True, data_format=data_format, name="conv1") self.conv2 = pre_conv3x3_block( in_channels=out_channels, out_channels=out_channels, use_bias=use_bias, use_bn=use_bn, data_format=data_format, name="conv2") def call(self, x, training=None): x, x_pre_activ = self.conv1(x, training=training) x = self.conv2(x, training=training) return x, x_pre_activ class PreResBottleneck(nn.Layer): """ 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. conv1_stride : bool Whether to use stride in the first or the second convolution layer of the block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, conv1_stride, data_format="channels_last", **kwargs): super(PreResBottleneck, self).__init__(**kwargs) mid_channels = out_channels // 4 self.conv1 = pre_conv1x1_block( in_channels=in_channels, out_channels=mid_channels, strides=(strides if conv1_stride else 1), return_preact=True, data_format=data_format, name="conv1") self.conv2 = pre_conv3x3_block( in_channels=mid_channels, out_channels=mid_channels, strides=(1 if conv1_stride else strides), data_format=data_format, name="conv2") self.conv3 = pre_conv1x1_block( in_channels=mid_channels, out_channels=out_channels, data_format=data_format, name="conv3") def call(self, x, training=None): x, x_pre_activ = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.conv3(x, training=training) return x, x_pre_activ class PreResUnit(nn.Layer): """ 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. use_bias : bool, default False Whether the layer uses a bias vector. use_bn : bool, default True Whether to use BatchNorm layer. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, use_bias=False, use_bn=True, bottleneck=True, conv1_stride=False, data_format="channels_last", **kwargs): super(PreResUnit, self).__init__(**kwargs) self.resize_identity = (in_channels != out_channels) or (strides != 1) if bottleneck: self.body = PreResBottleneck( in_channels=in_channels, out_channels=out_channels, strides=strides, conv1_stride=conv1_stride, data_format=data_format, name="body") else: self.body = PreResBlock( in_channels=in_channels, out_channels=out_channels, strides=strides, use_bias=use_bias, use_bn=use_bn, data_format=data_format, name="body") if self.resize_identity: self.identity_conv = conv1x1( in_channels=in_channels, out_channels=out_channels, strides=strides, use_bias=use_bias, data_format=data_format, name="identity_conv") def call(self, x, training=None): identity = x x, x_pre_activ = self.body(x, training=training) if self.resize_identity: identity = self.identity_conv(x_pre_activ, training=training) x = x + identity return x class PreResInitBlock(nn.Layer): """ PreResNet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(PreResInitBlock, self).__init__(**kwargs) self.conv = Conv2d( in_channels=in_channels, out_channels=out_channels, kernel_size=7, strides=2, padding=3, use_bias=False, data_format=data_format, name="conv") self.bn = BatchNorm( data_format=data_format, name="bn") self.activ = nn.ReLU() self.pool = MaxPool2d( pool_size=3, strides=2, padding=1, name="pool") def call(self, x, training=None): x = self.conv(x) x = self.bn(x, training=training) x = self.activ(x) x = self.pool(x) return x class PreResActivation(nn.Layer): """ PreResNet pure pre-activation block without convolution layer. It's used by itself as the final block. Parameters: ---------- in_channels : int Number of input channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, data_format="channels_last", **kwargs): super(PreResActivation, self).__init__(**kwargs) assert (in_channels is not None) self.bn = BatchNorm( data_format=data_format, name="bn") self.activ = nn.ReLU() def call(self, x, training=None): x = self.bn(x, training=training) x = self.activ(x) return x class PreResNet(tf.keras.Model): """ PreResNet model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, bottleneck, conv1_stride, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(PreResNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(PreResInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(PreResUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, bottleneck=bottleneck, conv1_stride=conv1_stride, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(PreResActivation( in_channels=in_channels, data_format=data_format, name="post_activ")) self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_preresnet(blocks, bottleneck=None, conv1_stride=True, width_scale=1.0, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create 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. root : str, default '~/.tensorflow/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 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 = PreResNet( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def preresnet10(**kwargs): """ PreResNet-10 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=10, model_name="preresnet10", **kwargs) def preresnet12(**kwargs): """ PreResNet-12 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=12, model_name="preresnet12", **kwargs) def preresnet14(**kwargs): """ PreResNet-14 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=14, model_name="preresnet14", **kwargs) def preresnetbc14b(**kwargs): """ PreResNet-BC-14b model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. It's an experimental model (bottleneck compressed). Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=14, bottleneck=True, conv1_stride=False, model_name="preresnetbc14b", **kwargs) def preresnet16(**kwargs): """ PreResNet-16 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=16, model_name="preresnet16", **kwargs) def preresnet18_wd4(**kwargs): """ PreResNet-18 model with 0.25 width scale from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=18, width_scale=0.25, model_name="preresnet18_wd4", **kwargs) def preresnet18_wd2(**kwargs): """ PreResNet-18 model with 0.5 width scale from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=18, width_scale=0.5, model_name="preresnet18_wd2", **kwargs) def preresnet18_w3d4(**kwargs): """ PreResNet-18 model with 0.75 width scale from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=18, width_scale=0.75, model_name="preresnet18_w3d4", **kwargs) def preresnet18(**kwargs): """ PreResNet-18 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=18, model_name="preresnet18", **kwargs) def preresnet26(**kwargs): """ PreResNet-26 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=26, bottleneck=False, model_name="preresnet26", **kwargs) def preresnetbc26b(**kwargs): """ PreResNet-BC-26b model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. It's an experimental model (bottleneck compressed). Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=26, bottleneck=True, conv1_stride=False, model_name="preresnetbc26b", **kwargs) def preresnet34(**kwargs): """ PreResNet-34 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=34, model_name="preresnet34", **kwargs) def preresnetbc38b(**kwargs): """ PreResNet-BC-38b model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. It's an experimental model (bottleneck compressed). Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=38, bottleneck=True, conv1_stride=False, model_name="preresnetbc38b", **kwargs) def preresnet50(**kwargs): """ PreResNet-50 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=50, model_name="preresnet50", **kwargs) def preresnet50b(**kwargs): """ PreResNet-50 model with stride at the second convolution in bottleneck block from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=50, conv1_stride=False, model_name="preresnet50b", **kwargs) def preresnet101(**kwargs): """ PreResNet-101 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=101, model_name="preresnet101", **kwargs) def preresnet101b(**kwargs): """ PreResNet-101 model with stride at the second convolution in bottleneck block from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=101, conv1_stride=False, model_name="preresnet101b", **kwargs) def preresnet152(**kwargs): """ PreResNet-152 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=152, model_name="preresnet152", **kwargs) def preresnet152b(**kwargs): """ PreResNet-152 model with stride at the second convolution in bottleneck block from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=152, conv1_stride=False, model_name="preresnet152b", **kwargs) def preresnet200(**kwargs): """ PreResNet-200 model from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=200, model_name="preresnet200", **kwargs) def preresnet200b(**kwargs): """ PreResNet-200 model with stride at the second convolution in bottleneck block from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=200, conv1_stride=False, model_name="preresnet200b", **kwargs) def preresnet269b(**kwargs): """ PreResNet-269 model with stride at the second convolution in bottleneck block from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet(blocks=269, conv1_stride=False, model_name="preresnet269b", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K pretrained = False models = [ preresnet10, preresnet12, preresnet14, preresnetbc14b, preresnet16, preresnet18_wd4, preresnet18_wd2, preresnet18_w3d4, preresnet18, preresnet26, preresnetbc26b, preresnet34, preresnetbc38b, preresnet50, preresnet50b, preresnet101, preresnet101b, preresnet152, preresnet152b, preresnet200, preresnet200b, preresnet269b, ] for model in models: net = model(pretrained=pretrained) batch = 14 x = tf.random.normal((batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != preresnet10 or weight_count == 5417128) assert (model != preresnet12 or weight_count == 5491112) assert (model != preresnet14 or weight_count == 5786536) assert (model != preresnetbc14b or weight_count == 10057384) assert (model != preresnet16 or weight_count == 6967208) assert (model != preresnet18_wd4 or weight_count == 3935960) assert (model != preresnet18_wd2 or weight_count == 5802440) assert (model != preresnet18_w3d4 or weight_count == 8473784) assert (model != preresnet18 or weight_count == 11687848) assert (model != preresnet26 or weight_count == 17958568) assert (model != preresnetbc26b or weight_count == 15987624) assert (model != preresnet34 or weight_count == 21796008) assert (model != preresnetbc38b or weight_count == 21917864) assert (model != preresnet50 or weight_count == 25549480) assert (model != preresnet50b or weight_count == 25549480) assert (model != preresnet101 or weight_count == 44541608) assert (model != preresnet101b or weight_count == 44541608) assert (model != preresnet152 or weight_count == 60185256) assert (model != preresnet152b or weight_count == 60185256) assert (model != preresnet200 or weight_count == 64666280) assert (model != preresnet200b or weight_count == 64666280) assert (model != preresnet269b or weight_count == 102065832) if __name__ == "__main__": _test()
28,922
33.107311
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/lednet.py
""" LEDNet for image segmentation, implemented in TensorFlow. Original paper: 'LEDNet: A Lightweight Encoder-Decoder Network for Real-Time Semantic Segmentation,' https://arxiv.org/abs/1905.02423. """ __all__ = ['LEDNet', 'lednet_cityscapes'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv3x3, conv1x1_block, conv3x3_block, conv5x5_block, conv7x7_block, ConvBlock, NormActivation,\ ChannelShuffle, InterpolationBlock, Hourglass, BreakBlock, SimpleSequential, MaxPool2d, is_channels_first,\ get_channel_axis, get_im_size class AsymConvBlock(nn.Layer): """ Asymmetric separable convolution block. Parameters: ---------- channels : int Number of input/output channels. kernel_size : int Convolution window size. 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. lw_use_bn : bool, default True Whether to use BatchNorm layer (leftwise convolution block). rw_use_bn : bool, default True Whether to use BatchNorm layer (rightwise convolution block). bn_eps : float, default 1e-5 Small float added to variance in Batch norm. lw_activation : function or str or None, default 'relu' Activation function after the leftwise convolution block. rw_activation : function or str or None, default 'relu' Activation function after the rightwise convolution block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, kernel_size, padding, dilation=1, groups=1, use_bias=False, lw_use_bn=True, rw_use_bn=True, bn_eps=1e-5, lw_activation="relu", rw_activation="relu", data_format="channels_last", **kwargs): super(AsymConvBlock, self).__init__(**kwargs) self.lw_conv = ConvBlock( in_channels=channels, out_channels=channels, kernel_size=(kernel_size, 1), strides=1, padding=(padding, 0), dilation=(dilation, 1), groups=groups, use_bias=use_bias, use_bn=lw_use_bn, bn_eps=bn_eps, activation=lw_activation, data_format=data_format, name="lw_conv") self.rw_conv = ConvBlock( in_channels=channels, out_channels=channels, kernel_size=(1, kernel_size), strides=1, padding=(0, padding), dilation=(1, dilation), groups=groups, use_bias=use_bias, use_bn=rw_use_bn, bn_eps=bn_eps, activation=rw_activation, data_format=data_format, name="rw_conv") def call(self, x, training=None): x = self.lw_conv(x, training=training) x = self.rw_conv(x, training=training) return x def asym_conv3x3_block(padding=1, **kwargs): """ 3x3 asymmetric separable convolution block. Parameters: ---------- channels : int Number of input/output channels. padding : int, default 1 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. lw_use_bn : bool, default True Whether to use BatchNorm layer (leftwise convolution block). rw_use_bn : bool, default True Whether to use BatchNorm layer (rightwise convolution block). bn_eps : float, default 1e-5 Small float added to variance in Batch norm. lw_activation : function or str or None, default 'relu' Activation function after the leftwise convolution block. rw_activation : function or str or None, default 'relu' Activation function after the rightwise convolution block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ return AsymConvBlock( kernel_size=3, padding=padding, **kwargs) class LEDDownBlock(nn.Layer): """ LEDNet specific downscale block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. correct_size_mistmatch : bool Whether to correct downscaled sizes of images. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, correct_size_mismatch, bn_eps, data_format="channels_last", **kwargs): super(LEDDownBlock, self).__init__(**kwargs) self.correct_size_mismatch = correct_size_mismatch self.data_format = data_format self.axis = get_channel_axis(data_format) self.pool = MaxPool2d( pool_size=2, strides=2, data_format=data_format, name="pool") self.conv = conv3x3( in_channels=in_channels, out_channels=(out_channels - in_channels), strides=2, use_bias=True, data_format=data_format, name="conv") self.norm_activ = NormActivation( in_channels=out_channels, bn_eps=bn_eps, data_format=data_format, name="norm_activ") def call(self, x, training=None): y1 = self.pool(x) y2 = self.conv(x) if self.correct_size_mismatch: if self.data_format == "channels_last": diff_h = y2.size()[1] - y1.size()[1] diff_w = y2.size()[2] - y1.size()[2] else: diff_h = y2.size()[2] - y1.size()[2] diff_w = y2.size()[3] - y1.size()[3] y1 = nn.ZeroPadding2D( padding=((diff_w // 2, diff_w - diff_w // 2), (diff_h // 2, diff_h - diff_h // 2)), data_format=self.data_format)(y1) x = tf.concat([y2, y1], axis=self.axis) x = self.norm_activ(x, training=training) return x class LEDBranch(nn.Layer): """ LEDNet encoder branch. Parameters: ---------- channels : int Number of input/output channels. dilation : int Dilation value for convolution layer. dropout_rate : float Parameter of Dropout layer. Faction of the input units to drop. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, dilation, dropout_rate, bn_eps, data_format="channels_last", **kwargs): super(LEDBranch, self).__init__(**kwargs) self.use_dropout = (dropout_rate != 0.0) self.conv1 = asym_conv3x3_block( channels=channels, use_bias=True, lw_use_bn=False, bn_eps=bn_eps, data_format=data_format, name="conv1") self.conv2 = asym_conv3x3_block( channels=channels, padding=dilation, dilation=dilation, use_bias=True, lw_use_bn=False, bn_eps=bn_eps, rw_activation=None, data_format=data_format, name="conv2") if self.use_dropout: self.dropout = nn.Dropout( rate=dropout_rate, name="dropout") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) if self.use_dropout: x = self.dropout(x, training=training) return x class LEDUnit(nn.Layer): """ LEDNet encoder unit (Split-Shuffle-non-bottleneck). Parameters: ---------- channels : int Number of input/output channels. dilation : int Dilation value for convolution layer. dropout_rate : float Parameter of Dropout layer. Faction of the input units to drop. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, dilation, dropout_rate, bn_eps, data_format="channels_last", **kwargs): super(LEDUnit, self).__init__(**kwargs) self.axis = get_channel_axis(data_format) mid_channels = channels // 2 self.left_branch = LEDBranch( channels=mid_channels, dilation=dilation, dropout_rate=dropout_rate, bn_eps=bn_eps, data_format=data_format, name="left_branch") self.right_branch = LEDBranch( channels=mid_channels, dilation=dilation, dropout_rate=dropout_rate, bn_eps=bn_eps, data_format=data_format, name="right_branch") self.activ = nn.ReLU() self.shuffle = ChannelShuffle( channels=channels, groups=2, data_format=data_format, name="shuffle") def call(self, x, training=None): identity = x x1, x2 = tf.split(x, num_or_size_splits=2, axis=self.axis) x1 = self.left_branch(x1, training=training) x2 = self.right_branch(x2, training=training) x = tf.concat([x1, x2], axis=self.axis) x = x + identity x = self.activ(x) x = self.shuffle(x) return x class PoolingBranch(nn.Layer): """ Pooling 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. bn_eps : float Small float added to variance in Batch norm. in_size : tuple of 2 int or None Spatial size of input image. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, use_bias, bn_eps, in_size, data_format="channels_last", **kwargs): super(PoolingBranch, self).__init__(**kwargs) self.in_size = in_size self.data_format = data_format self.pool = nn.GlobalAveragePooling2D( data_format=data_format, name="pool") self.conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, use_bias=use_bias, bn_eps=bn_eps, data_format=data_format, name="conv") self.up = InterpolationBlock( scale_factor=None, out_size=in_size, data_format=data_format, name="up") def call(self, x, training=None): in_size = self.in_size if self.in_size is not None else get_im_size(x, data_format=self.data_format) x = self.pool(x) axis = -1 if is_channels_first(self.data_format) else 1 x = tf.expand_dims(tf.expand_dims(x, axis=axis), axis=axis) x = self.conv(x, training=training) x = self.up(x, size=in_size) return x class APN(nn.Layer): """ Attention pyramid network block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. bn_eps : float Small float added to variance in Batch norm. in_size : tuple of 2 int or None Spatial size of input image. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, bn_eps, in_size, data_format="channels_last", **kwargs): super(APN, self).__init__(**kwargs) self.in_size = in_size att_out_channels = 1 self.pool_branch = PoolingBranch( in_channels=in_channels, out_channels=out_channels, use_bias=True, bn_eps=bn_eps, in_size=in_size, data_format=data_format, name="pool_branch") self.body = conv1x1_block( in_channels=in_channels, out_channels=out_channels, use_bias=True, bn_eps=bn_eps, data_format=data_format, name="body") down_seq = SimpleSequential(name="down_seq") down_seq.add(conv7x7_block( in_channels=in_channels, out_channels=att_out_channels, strides=2, use_bias=True, bn_eps=bn_eps, data_format=data_format, name="down1")) down_seq.add(conv5x5_block( in_channels=att_out_channels, out_channels=att_out_channels, strides=2, use_bias=True, bn_eps=bn_eps, data_format=data_format, name="down2")) down3_subseq = SimpleSequential(name="down3") down3_subseq.add(conv3x3_block( in_channels=att_out_channels, out_channels=att_out_channels, strides=2, use_bias=True, bn_eps=bn_eps, data_format=data_format, name="conv1")) down3_subseq.add(conv3x3_block( in_channels=att_out_channels, out_channels=att_out_channels, use_bias=True, bn_eps=bn_eps, data_format=data_format, name="conv2")) down_seq.add(down3_subseq) up_seq = SimpleSequential(name="up_seq") up_seq.add(InterpolationBlock( scale_factor=2, data_format=data_format, name="up1")) up_seq.add(InterpolationBlock( scale_factor=2, data_format=data_format, name="up2")) up_seq.add(InterpolationBlock( scale_factor=2, data_format=data_format, name="up3")) skip_seq = SimpleSequential(name="skip_seq") skip_seq.add(BreakBlock(name="skip1")) skip_seq.add(conv7x7_block( in_channels=att_out_channels, out_channels=att_out_channels, use_bias=True, bn_eps=bn_eps, data_format=data_format, name="skip2")) skip_seq.add(conv5x5_block( in_channels=att_out_channels, out_channels=att_out_channels, use_bias=True, bn_eps=bn_eps, data_format=data_format, name="skip3")) self.hg = Hourglass( down_seq=down_seq, up_seq=up_seq, skip_seq=skip_seq, data_format=data_format, name="hg") def call(self, x, training=None): y = self.pool_branch(x, training=training) w = self.hg(x, training=training) x = self.body(x, training=training) x = x * w x = x + y return x class LEDNet(tf.keras.Model): """ LEDNet model from 'LEDNet: A Lightweight Encoder-Decoder Network for Real-Time Semantic Segmentation,' https://arxiv.org/abs/1905.02423. Parameters: ---------- channels : list of int Number of output channels for each unit. dilations : list of int Dilations for units. dropout_rates : list of list of int Dropout rates for each unit in encoder. correct_size_mistmatch : bool Whether to correct downscaled sizes of images in encoder. bn_eps : float, default 1e-5 Small float added to variance in Batch norm. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, dilations, dropout_rates, correct_size_mismatch=False, bn_eps=1e-5, aux=False, fixed_size=False, in_channels=3, in_size=(1024, 2048), classes=19, data_format="channels_last", **kwargs): super(LEDNet, 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 self.encoder = SimpleSequential(name="encoder") for i, dilations_per_stage in enumerate(dilations): out_channels = channels[i] dropout_rate = dropout_rates[i] stage = SimpleSequential(name="stage{}".format(i + 1)) for j, dilation in enumerate(dilations_per_stage): if j == 0: stage.add(LEDDownBlock( in_channels=in_channels, out_channels=out_channels, correct_size_mismatch=correct_size_mismatch, bn_eps=bn_eps, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels else: stage.add(LEDUnit( channels=in_channels, dilation=dilation, dropout_rate=dropout_rate, bn_eps=bn_eps, data_format=data_format, name="unit{}".format(j + 1))) self.encoder.add(stage) self.apn = APN( in_channels=in_channels, out_channels=classes, bn_eps=bn_eps, in_size=(in_size[0] // 8, in_size[1] // 8) if fixed_size else None, data_format=data_format, name="apn") self.up = InterpolationBlock( scale_factor=8, data_format=data_format, name="up") def call(self, x, training=None): x = self.encoder(x, training=training) x = self.apn(x, training=training) x = self.up(x, training=training) return x def get_lednet(model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create LEDNet 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ channels = [32, 64, 128] dilations = [[0, 1, 1, 1], [0, 1, 1], [0, 1, 2, 5, 9, 2, 5, 9, 17]] dropout_rates = [0.03, 0.03, 0.3] bn_eps = 1e-3 net = LEDNet( channels=channels, dilations=dilations, dropout_rates=dropout_rates, bn_eps=bn_eps, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root), by_name=True, skip_mismatch=True) return net def lednet_cityscapes(classes=19, **kwargs): """ LEDNet model for Cityscapes from 'LEDNet: A Lightweight Encoder-Decoder Network for Real-Time Semantic Segmentation,' https://arxiv.org/abs/1905.02423. Parameters: ---------- classes : int, default 19 Number of segmentation classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_lednet(classes=classes, model_name="lednet_cityscapes", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" pretrained = False fixed_size = True correct_size_mismatch = False in_size = (1024, 2048) classes = 19 models = [ lednet_cityscapes, ] for model in models: net = model(pretrained=pretrained, in_size=in_size, fixed_size=fixed_size, correct_size_mismatch=correct_size_mismatch, data_format=data_format) batch = 4 x = tf.random.normal((batch, 3, in_size[0], in_size[1]) if is_channels_first(data_format) else (batch, in_size[0], in_size[1], 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, classes, in_size[0], in_size[1]) if is_channels_first(data_format) else tuple(y.shape.as_list()) == (batch, in_size[0], in_size[1], classes)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != lednet_cityscapes or weight_count == 922821) if __name__ == "__main__": _test()
22,964
31.94835
118
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/ibndensenet.py
""" IBN-DenseNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'Two at Once: Enhancing Learning and Generalization Capacities via IBN-Net,' https://arxiv.org/abs/1807.09441. """ __all__ = ['IBNDenseNet', 'ibn_densenet121', 'ibn_densenet161', 'ibn_densenet169', 'ibn_densenet201'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import Conv2d, BatchNorm, pre_conv3x3_block, IBN, SimpleSequential, flatten, is_channels_first,\ get_channel_axis from .preresnet import PreResInitBlock, PreResActivation from .densenet import TransitionBlock class IBNPreConvBlock(nn.Layer): """ IBN-Net specific convolution block with BN/IBN 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. use_ibn : bool, default False Whether use Instance-Batch Normalization. return_preact : bool, default False Whether return pre-activation. It's used by PreResNet. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, strides, padding, use_ibn=False, return_preact=False, data_format="channels_last", **kwargs): super(IBNPreConvBlock, self).__init__(**kwargs) self.use_ibn = use_ibn self.return_preact = return_preact if self.use_ibn: self.ibn = IBN( channels=in_channels, first_fraction=0.6, inst_first=False, data_format=data_format, name="ibn") else: self.bn = BatchNorm( data_format=data_format, name="bn") self.activ = nn.ReLU() self.conv = Conv2d( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, strides=strides, padding=padding, use_bias=False, data_format=data_format, name="conv") def call(self, x, training=None): if self.use_ibn: x = self.ibn(x, training=training) else: x = self.bn(x, training=training) x = self.activ(x) if self.return_preact: x_pre_activ = x x = self.conv(x, training=training) if self.return_preact: return x, x_pre_activ else: return x def ibn_pre_conv1x1_block(in_channels, out_channels, strides=1, use_ibn=False, return_preact=False, data_format="channels_last", **kwargs): """ 1x1 version of the IBN-Net specific 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_ibn : bool, default False Whether use Instance-Batch Normalization. return_preact : bool, default False Whether return pre-activation. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ return IBNPreConvBlock( in_channels=in_channels, out_channels=out_channels, kernel_size=1, strides=strides, padding=0, use_ibn=use_ibn, return_preact=return_preact, data_format=data_format, **kwargs) class IBNDenseUnit(nn.Layer): """ IBN-DenseNet unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. dropout_rate : float Parameter of Dropout layer. Faction of the input units to drop. conv1_ibn : bool Whether to use IBN normalization in the first convolution layer of the block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, dropout_rate, conv1_ibn, data_format="channels_last", **kwargs): super(IBNDenseUnit, self).__init__(**kwargs) self.data_format = data_format self.use_dropout = (dropout_rate != 0.0) bn_size = 4 inc_channels = out_channels - in_channels mid_channels = inc_channels * bn_size self.conv1 = ibn_pre_conv1x1_block( in_channels=in_channels, out_channels=mid_channels, use_ibn=conv1_ibn, data_format=data_format, name="conv1") self.conv2 = pre_conv3x3_block( in_channels=mid_channels, out_channels=inc_channels, data_format=data_format, name="conv2") if self.use_dropout: self.dropout = nn.Dropout( rate=dropout_rate, name="dropout") def call(self, x, training=None): identity = x x = self.conv1(x, training=training) x = self.conv2(x, training=training) if self.use_dropout: x = self.dropout(x, training=training) x = tf.concat([identity, x], axis=get_channel_axis(self.data_format)) return x class IBNDenseNet(tf.keras.Model): """ IBN-DenseNet 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. 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 (224, 224) Spatial size of the expected input image. classes : int, default 1000 Number of classification classes. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, dropout_rate=0.0, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(IBNDenseNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(PreResInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) if i != 0: stage.add(TransitionBlock( in_channels=in_channels, out_channels=(in_channels // 2), data_format=data_format, name="trans{}".format(i + 1))) in_channels = in_channels // 2 for j, out_channels in enumerate(channels_per_stage): conv1_ibn = (i < 3) and (j % 3 == 0) stage.add(IBNDenseUnit( in_channels=in_channels, out_channels=out_channels, dropout_rate=dropout_rate, conv1_ibn=conv1_ibn, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(PreResActivation( in_channels=in_channels, data_format=data_format, name="post_activ")) self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_ibndensenet(num_layers, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create IBN-DenseNet model with specific parameters. Parameters: ---------- num_layers : int Number 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if num_layers == 121: init_block_channels = 64 growth_rate = 32 layers = [6, 12, 24, 16] elif num_layers == 161: init_block_channels = 96 growth_rate = 48 layers = [6, 12, 36, 24] elif num_layers == 169: init_block_channels = 64 growth_rate = 32 layers = [6, 12, 32, 32] elif num_layers == 201: init_block_channels = 64 growth_rate = 32 layers = [6, 12, 48, 32] else: raise ValueError("Unsupported IBN-DenseNet version with number of layers {}".format(num_layers)) 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 = IBNDenseNet( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def ibn_densenet121(**kwargs): """ IBN-DenseNet-121 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_ibndensenet(num_layers=121, model_name="ibn_densenet121", **kwargs) def ibn_densenet161(**kwargs): """ IBN-DenseNet-161 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_ibndensenet(num_layers=161, model_name="ibn_densenet161", **kwargs) def ibn_densenet169(**kwargs): """ IBN-DenseNet-169 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_ibndensenet(num_layers=169, model_name="ibn_densenet169", **kwargs) def ibn_densenet201(**kwargs): """ IBN-DenseNet-201 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_ibndensenet(num_layers=201, model_name="ibn_densenet201", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ ibn_densenet121, ibn_densenet161, ibn_densenet169, ibn_densenet201, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != ibn_densenet121 or weight_count == 7978856) assert (model != ibn_densenet161 or weight_count == 28681000) assert (model != ibn_densenet169 or weight_count == 14149480) assert (model != ibn_densenet201 or weight_count == 20013928) if __name__ == "__main__": _test()
14,434
32.414352
115
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/hardnet.py
""" HarDNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'HarDNet: A Low Memory Traffic Network,' https://arxiv.org/abs/1909.00948. """ __all__ = ['HarDNet', 'hardnet39ds', 'hardnet68ds', 'hardnet68', 'hardnet85'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv_block, MaxPool2d, SimpleSequential,\ flatten, get_channel_axis, is_channels_first class InvDwsConvBlock(nn.Layer): """ Inverse 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. use_bn : bool, default True Whether to use BatchNorm layer. bn_eps : float, default 1e-5 Small float added to variance in Batch norm. pw_activation : function or str or None, default 'relu' Activation function after the pointwise convolution block. dw_activation : function or str or None, default 'relu' Activation function after the depthwise convolution block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, strides, padding, dilation=1, use_bias=False, use_bn=True, bn_eps=1e-5, pw_activation="relu", dw_activation="relu", data_format="channels_last", **kwargs): super(InvDwsConvBlock, self).__init__(**kwargs) self.pw_conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, use_bias=use_bias, use_bn=use_bn, bn_eps=bn_eps, activation=pw_activation, data_format=data_format, name="pw_conv") self.dw_conv = dwconv_block( in_channels=out_channels, out_channels=out_channels, kernel_size=kernel_size, strides=strides, padding=padding, dilation=dilation, use_bias=use_bias, use_bn=use_bn, bn_eps=bn_eps, activation=dw_activation, data_format=data_format, name="dw_conv") def call(self, x, training=None): x = self.pw_conv(x, training=training) x = self.dw_conv(x, training=training) return x def invdwsconv3x3_block(in_channels, out_channels, strides=1, padding=1, dilation=1, use_bias=False, use_bn=True, bn_eps=1e-5, pw_activation="relu", dw_activation="relu", data_format="channels_last", **kwargs): """ 3x3 inverse 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_eps : float, default 1e-5 Small float added to variance in Batch norm. pw_activation : function or str or None, default 'relu' Activation function after the pointwise convolution block. dw_activation : function or str or None, default 'relu' Activation function after the depthwise convolution block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ return InvDwsConvBlock( in_channels=in_channels, out_channels=out_channels, kernel_size=3, strides=strides, padding=padding, dilation=dilation, use_bias=use_bias, use_bn=use_bn, bn_eps=bn_eps, pw_activation=pw_activation, dw_activation=dw_activation, data_format=data_format, **kwargs) class HarDUnit(nn.Layer): """ HarDNet unit. Parameters: ---------- in_channels_list : list of int Number of input channels for each block. out_channels_list : list of int Number of output channels for each block. links_list : list of list of int List of indices for each layer. use_deptwise : bool Whether to use depthwise downsampling. use_dropout : bool Whether to use dropout module. downsampling : bool Whether to downsample input. activation : str Name of activation function. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels_list, out_channels_list, links_list, use_deptwise, use_dropout, downsampling, activation, data_format="channels_last", **kwargs): super(HarDUnit, self).__init__(**kwargs) self.data_format = data_format self.links_list = links_list self.use_dropout = use_dropout self.downsampling = downsampling self.blocks = SimpleSequential(name="blocks") for i in range(len(links_list)): in_channels = in_channels_list[i] out_channels = out_channels_list[i] if use_deptwise: unit = invdwsconv3x3_block( in_channels=in_channels, out_channels=out_channels, pw_activation=activation, dw_activation=None, data_format=data_format, name="block{}".format(i + 1)) else: unit = conv3x3_block( in_channels=in_channels, out_channels=out_channels, data_format=data_format, name="block{}".format(i + 1)) self.blocks.add(unit) if self.use_dropout: self.dropout = nn.Dropout( rate=0.1, name="dropout") self.conv = conv1x1_block( in_channels=in_channels_list[-1], out_channels=out_channels_list[-1], activation=activation, data_format=data_format, name="conv") if self.downsampling: if use_deptwise: self.downsample = dwconv3x3_block( in_channels=out_channels_list[-1], out_channels=out_channels_list[-1], strides=2, activation=None, data_format=data_format, name="downsample") else: self.downsample = MaxPool2d( pool_size=2, strides=2, data_format=data_format, name="downsample") def call(self, x, training=None): axis = get_channel_axis(self.data_format) layer_outs = [x] for links_i, layer_i in zip(self.links_list, self.blocks.children): layer_in = [] for idx_ij in links_i: layer_in.append(layer_outs[idx_ij]) if len(layer_in) > 1: x = tf.concat(layer_in, axis=axis) else: x = layer_in[0] out = layer_i(x, training=training) layer_outs.append(out) outs = [] for i, layer_out_i in enumerate(layer_outs): if (i == len(layer_outs) - 1) or (i % 2 == 1): outs.append(layer_out_i) x = tf.concat(outs, axis=axis) if self.use_dropout: x = self.dropout(x, training=training) x = self.conv(x, training=training) if self.downsampling: x = self.downsample(x, training=training) return x class HarDInitBlock(nn.Layer): """ HarDNet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. use_deptwise : bool Whether to use depthwise downsampling. activation : str Name of activation function. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, use_deptwise, activation, data_format="channels_last", **kwargs): super(HarDInitBlock, self).__init__(**kwargs) mid_channels = out_channels // 2 self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels, strides=2, activation=activation, data_format=data_format, name="conv1") conv2_block_class = conv1x1_block if use_deptwise else conv3x3_block self.conv2 = conv2_block_class( in_channels=mid_channels, out_channels=out_channels, activation=activation, data_format=data_format, name="conv2") if use_deptwise: self.downsample = dwconv3x3_block( in_channels=out_channels, out_channels=out_channels, strides=2, activation=None, data_format=data_format, name="downsample") else: self.downsample = MaxPool2d( pool_size=3, strides=2, padding=1, data_format=data_format, name="downsample") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.downsample(x, training=training) return x class HarDNet(tf.keras.Model): """ HarDNet model from 'HarDNet: A Low Memory Traffic Network,' https://arxiv.org/abs/1909.00948. Parameters: ---------- init_block_channels : int Number of output channels for the initial unit. unit_in_channels : list of list of list of int Number of input channels for each layer in each stage. unit_out_channels : list list of of list of int Number of output channels for each layer in each stage. unit_links : list of list of list of int List of indices for each layer in each stage. use_deptwise : bool Whether to use depthwise downsampling. use_last_dropout : bool Whether to use dropouts in the last unit. output_dropout_rate : float Parameter of Dropout layer before classifier. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, init_block_channels, unit_in_channels, unit_out_channels, unit_links, use_deptwise, use_last_dropout, output_dropout_rate, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(HarDNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format activation = "relu6" self.features = SimpleSequential(name="features") self.features.add(HarDInitBlock( in_channels=in_channels, out_channels=init_block_channels, use_deptwise=use_deptwise, activation=activation, data_format=data_format, name="init_block")) for i, (in_channels_list_i, out_channels_list_i) in enumerate(zip(unit_in_channels, unit_out_channels)): stage = SimpleSequential(name="stage{}".format(i + 1)) for j, (in_channels_list_ij, out_channels_list_ij) in enumerate(zip(in_channels_list_i, out_channels_list_i)): use_dropout = ((j == len(in_channels_list_i) - 1) and (i == len(unit_in_channels) - 1) and use_last_dropout) downsampling = ((j == len(in_channels_list_i) - 1) and (i != len(unit_in_channels) - 1)) stage.add(HarDUnit( in_channels_list=in_channels_list_ij, out_channels_list=out_channels_list_ij, links_list=unit_links[i][j], use_deptwise=use_deptwise, use_dropout=use_dropout, downsampling=downsampling, activation=activation, data_format=data_format, name="unit{}".format(j + 1))) self.features.add(stage) in_channels = unit_out_channels[-1][-1][-1] self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = SimpleSequential(name="output1") self.output1.add(nn.Dropout( rate=output_dropout_rate, name="dropout")) self.output1.add(nn.Dense( units=classes, input_dim=in_channels, name="fc")) def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_hardnet(blocks, use_deptwise=True, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create HarDNet model with specific parameters. Parameters: ---------- blocks : int Number of blocks. use_deepwise : bool, default True Whether to use depthwise separable version of the 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if blocks == 39: init_block_channels = 48 growth_factor = 1.6 dropout_rate = 0.05 if use_deptwise else 0.1 layers = [4, 16, 8, 4] channels_per_layers = [96, 320, 640, 1024] growth_rates = [16, 20, 64, 160] downsamples = [1, 1, 1, 0] use_dropout = False elif blocks == 68: init_block_channels = 64 growth_factor = 1.7 dropout_rate = 0.05 if use_deptwise else 0.1 layers = [8, 16, 16, 16, 4] channels_per_layers = [128, 256, 320, 640, 1024] growth_rates = [14, 16, 20, 40, 160] downsamples = [1, 0, 1, 1, 0] use_dropout = False elif blocks == 85: init_block_channels = 96 growth_factor = 1.7 dropout_rate = 0.05 if use_deptwise else 0.2 layers = [8, 16, 16, 16, 16, 4] channels_per_layers = [192, 256, 320, 480, 720, 1280] growth_rates = [24, 24, 28, 36, 48, 256] downsamples = [1, 0, 1, 0, 1, 0] use_dropout = True else: raise ValueError("Unsupported HarDNet version with number of layers {}".format(blocks)) assert (downsamples[-1] == 0) def calc_stage_params(): def calc_unit_params(): def calc_blocks_params(layer_idx, base_channels, growth_rate): if layer_idx == 0: return base_channels, 0, [] out_channels_ij = growth_rate links_ij = [] for k in range(10): dv = 2 ** k if layer_idx % dv == 0: t = layer_idx - dv links_ij.append(t) if k > 0: out_channels_ij *= growth_factor out_channels_ij = int(int(out_channels_ij + 1) / 2) * 2 in_channels_ij = 0 for t in links_ij: out_channels_ik, _, _ = calc_blocks_params( layer_idx=t, base_channels=base_channels, growth_rate=growth_rate) in_channels_ij += out_channels_ik return out_channels_ij, in_channels_ij, links_ij unit_out_channels = [] unit_in_channels = [] unit_links = [] for num_layers, growth_rate, base_channels, channels_per_layers_i in zip( layers, growth_rates, [init_block_channels] + channels_per_layers[:-1], channels_per_layers): stage_out_channels_i = 0 unit_out_channels_i = [] unit_in_channels_i = [] unit_links_i = [] for j in range(num_layers): out_channels_ij, in_channels_ij, links_ij = calc_blocks_params( layer_idx=(j + 1), base_channels=base_channels, growth_rate=growth_rate) unit_out_channels_i.append(out_channels_ij) unit_in_channels_i.append(in_channels_ij) unit_links_i.append(links_ij) if (j % 2 == 0) or (j == num_layers - 1): stage_out_channels_i += out_channels_ij unit_in_channels_i.append(stage_out_channels_i) unit_out_channels_i.append(channels_per_layers_i) unit_out_channels.append(unit_out_channels_i) unit_in_channels.append(unit_in_channels_i) unit_links.append(unit_links_i) return unit_out_channels, unit_in_channels, unit_links unit_out_channels, unit_in_channels, unit_links = calc_unit_params() stage_out_channels = [] stage_in_channels = [] stage_links = [] stage_out_channels_k = None for i in range(len(layers)): if stage_out_channels_k is None: stage_out_channels_k = [] stage_in_channels_k = [] stage_links_k = [] stage_out_channels_k.append(unit_out_channels[i]) stage_in_channels_k.append(unit_in_channels[i]) stage_links_k.append(unit_links[i]) if (downsamples[i] == 1) or (i == len(layers) - 1): stage_out_channels.append(stage_out_channels_k) stage_in_channels.append(stage_in_channels_k) stage_links.append(stage_links_k) stage_out_channels_k = None return stage_out_channels, stage_in_channels, stage_links stage_out_channels, stage_in_channels, stage_links = calc_stage_params() net = HarDNet( init_block_channels=init_block_channels, unit_in_channels=stage_in_channels, unit_out_channels=stage_out_channels, unit_links=stage_links, use_deptwise=use_deptwise, use_last_dropout=use_dropout, output_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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def hardnet39ds(**kwargs): """ HarDNet-39DS (Depthwise Separable) model from 'HarDNet: A Low Memory Traffic Network,' https://arxiv.org/abs/1909.00948. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_hardnet(blocks=39, use_deptwise=True, model_name="hardnet39ds", **kwargs) def hardnet68ds(**kwargs): """ HarDNet-68DS (Depthwise Separable) model from 'HarDNet: A Low Memory Traffic Network,' https://arxiv.org/abs/1909.00948. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_hardnet(blocks=68, use_deptwise=True, model_name="hardnet68ds", **kwargs) def hardnet68(**kwargs): """ HarDNet-68 model from 'HarDNet: A Low Memory Traffic Network,' https://arxiv.org/abs/1909.00948. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_hardnet(blocks=68, use_deptwise=False, model_name="hardnet68", **kwargs) def hardnet85(**kwargs): """ HarDNet-85 model from 'HarDNet: A Low Memory Traffic Network,' https://arxiv.org/abs/1909.00948. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_hardnet(blocks=85, use_deptwise=False, model_name="hardnet85", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ hardnet39ds, hardnet68ds, hardnet68, hardnet85, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != hardnet39ds or weight_count == 3488228) assert (model != hardnet68ds or weight_count == 4180602) assert (model != hardnet68 or weight_count == 17565348) assert (model != hardnet85 or weight_count == 36670212) if __name__ == "__main__": _test()
24,226
35.213752
115
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/sinet.py
""" SINet for image segmentation, implemented in TensorFlow. Original paper: 'SINet: Extreme Lightweight Portrait Segmentation Networks with Spatial Squeeze Modules and Information Blocking Decoder,' https://arxiv.org/abs/1911.09099. """ __all__ = ['SINet', 'sinet_cityscapes'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import PReLU2, BatchNorm, AvgPool2d, conv1x1, get_activation_layer, conv1x1_block, conv3x3_block,\ round_channels, dwconv_block, InterpolationBlock, ChannelShuffle, SimpleSequential, Concurrent, get_channel_axis,\ is_channels_first class SEBlock(nn.Layer): """ SINet version of 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. round_mid : bool, default False Whether to round middle channel number (make divisible by 8). activation : function, or str, or nn.Module, default 'relu' Activation function after the first convolution. out_activation : function, or str, or nn.Module, default 'sigmoid' Activation function after the last convolution. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, reduction=16, round_mid=False, mid_activation="relu", out_activation="sigmoid", data_format="channels_last", **kwargs): super(SEBlock, self).__init__(**kwargs) self.data_format = data_format self.use_conv2 = (reduction > 1) mid_channels = channels // reduction if not round_mid else round_channels(float(channels) / reduction) self.pool = nn.GlobalAveragePooling2D( data_format=data_format, name="pool") self.fc1 = nn.Dense( units=mid_channels, input_dim=channels, name="fc1") if self.use_conv2: self.activ = get_activation_layer(mid_activation, name="activ") self.fc2 = nn.Dense( units=channels, input_dim=mid_channels, name="fc2") self.sigmoid = get_activation_layer(out_activation, name="sigmoid") def call(self, x, training=None): w = self.pool(x) w = self.fc1(w) if self.use_conv2: w = self.activ(w) w = self.fc2(w) w = self.sigmoid(w) axis = -1 if is_channels_first(self.data_format) else 1 w = tf.expand_dims(tf.expand_dims(w, axis=axis), axis=axis) x = x * w return x class DwsConvBlock(nn.Layer): """ SINet version of 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_eps : float, default 1e-5 Small float added to variance in Batch norm. dw_activation : function or str or None, default 'relu' Activation function after the depthwise convolution block. pw_activation : function or str or None, default 'relu' Activation function after the pointwise convolution block. se_reduction : int, default 0 Squeeze reduction value (0 means no-se). data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ 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_eps=1e-5, dw_activation="relu", pw_activation="relu", se_reduction=0, data_format="channels_last", **kwargs): super(DwsConvBlock, self).__init__(**kwargs) self.use_se = (se_reduction > 0) 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_eps=bn_eps, activation=dw_activation, data_format=data_format, name="dw_conv") if self.use_se: self.se = SEBlock( channels=in_channels, reduction=se_reduction, round_mid=False, mid_activation=(lambda: PReLU2(in_channels // se_reduction, data_format=data_format, name="activ")), out_activation=(lambda: PReLU2(in_channels, data_format=data_format, name="sigmoid")), data_format=data_format, name="se") self.pw_conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, use_bias=use_bias, use_bn=pw_use_bn, bn_eps=bn_eps, activation=pw_activation, data_format=data_format, name="pw_conv") def call(self, x, training=None): x = self.dw_conv(x, training=None) if self.use_se: x = self.se(x, training=None) x = self.pw_conv(x, training=None) return x def dwsconv3x3_block(in_channels, out_channels, strides=1, padding=1, dilation=1, use_bias=False, dw_use_bn=True, pw_use_bn=True, bn_eps=1e-5, dw_activation="relu", pw_activation="relu", se_reduction=0, data_format="channels_last", **kwargs): """ 3x3 depthwise separable version of the standard convolution block (SINet version). 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. 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_eps : float, default 1e-5 Small float added to variance in Batch norm. dw_activation : function or str or None, default 'relu' Activation function after the depthwise convolution block. pw_activation : function or str or None, default 'relu' Activation function after the pointwise convolution block. se_reduction : int, default 0 Squeeze reduction value (0 means no-se). data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ return DwsConvBlock( in_channels=in_channels, out_channels=out_channels, kernel_size=3, strides=strides, padding=padding, dilation=dilation, use_bias=use_bias, dw_use_bn=dw_use_bn, pw_use_bn=pw_use_bn, bn_eps=bn_eps, dw_activation=dw_activation, pw_activation=pw_activation, se_reduction=se_reduction, data_format=data_format, **kwargs) def dwconv3x3_block(in_channels, out_channels, strides=1, padding=1, dilation=1, use_bias=False, bn_eps=1e-5, activation="relu", data_format="channels_last", **kwargs): """ 3x3 depthwise version of the standard convolution block (SINet version). 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_eps : float, default 1e-5 Small float added to variance in Batch norm. activation : function or str or None, default 'relu' Activation function or name of activation function. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ 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_eps=bn_eps, activation=activation, data_format=data_format, **kwargs) class FDWConvBlock(nn.Layer): """ Factorized 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 Convolution window size. strides : int or tuple/list of 2 int Strides of the convolution. padding : 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_eps : float, default 1e-5 Small float added to variance in Batch norm. activation : function or str or None, default 'relu' Activation function after the each convolution block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, strides, padding, dilation=1, use_bias=False, use_bn=True, bn_eps=1e-5, activation="relu", data_format="channels_last", **kwargs): super(FDWConvBlock, self).__init__(**kwargs) assert use_bn self.activate = (activation is not None) self.v_conv = dwconv_block( in_channels=in_channels, out_channels=out_channels, kernel_size=(kernel_size, 1), strides=strides, padding=(padding, 0), dilation=dilation, use_bias=use_bias, use_bn=use_bn, bn_eps=bn_eps, activation=None, data_format=data_format, name="v_conv") self.h_conv = dwconv_block( in_channels=in_channels, out_channels=out_channels, kernel_size=(1, kernel_size), strides=strides, padding=(0, padding), dilation=dilation, use_bias=use_bias, use_bn=use_bn, bn_eps=bn_eps, activation=None, data_format=data_format, name="h_conv") if self.activate: self.act = get_activation_layer(activation, name="act") def call(self, x, training=None): x = self.v_conv(x, training=None) + self.h_conv(x, training=None) if self.activate: x = self.act(x) return x def fdwconv3x3_block(in_channels, out_channels, strides=1, padding=1, dilation=1, use_bias=False, use_bn=True, bn_eps=1e-5, activation="relu", data_format="channels_last", **kwargs): """ 3x3 factorized 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, 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. use_bn : bool, default True Whether to use BatchNorm layer. bn_eps : float, default 1e-5 Small float added to variance in Batch norm. activation : function or str or None, default 'relu' Activation function or name of activation function. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ return FDWConvBlock( in_channels=in_channels, out_channels=out_channels, kernel_size=3, strides=strides, padding=padding, dilation=dilation, use_bias=use_bias, use_bn=use_bn, bn_eps=bn_eps, activation=activation, data_format=data_format, **kwargs) def fdwconv5x5_block(in_channels, out_channels, strides=1, padding=2, dilation=1, use_bias=False, use_bn=True, bn_eps=1e-5, activation="relu", data_format="channels_last", **kwargs): """ 5x5 factorized 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, 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. use_bn : bool, default True Whether to use BatchNorm layer. bn_eps : float, default 1e-5 Small float added to variance in Batch norm. activation : function or str or None, default 'relu' Activation function or name of activation function. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ return FDWConvBlock( in_channels=in_channels, out_channels=out_channels, kernel_size=5, strides=strides, padding=padding, dilation=dilation, use_bias=use_bias, use_bn=use_bn, bn_eps=bn_eps, activation=activation, data_format=data_format, **kwargs) class SBBlock(nn.Layer): """ SB-block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int Convolution window size for a factorized depthwise separable convolution block. scale_factor : int Scale factor. size : tuple of 2 int Spatial size of the output tensor for the bilinear upsampling operation. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, scale_factor, size, bn_eps, data_format="channels_last", **kwargs): super(SBBlock, self).__init__(**kwargs) self.use_scale = (scale_factor > 1) if self.use_scale: self.down_scale = AvgPool2d( pool_size=scale_factor, strides=scale_factor, data_format=data_format, name="down_scale") self.up_scale = InterpolationBlock( scale_factor=scale_factor, out_size=size, data_format=data_format, name="up_scale") use_fdw = (scale_factor > 0) if use_fdw: fdwconv3x3_class = fdwconv3x3_block if kernel_size == 3 else fdwconv5x5_block self.conv1 = fdwconv3x3_class( in_channels=in_channels, out_channels=in_channels, bn_eps=bn_eps, activation=(lambda: PReLU2(in_channels, data_format=data_format, name="activ")), data_format=data_format, name="conv1") else: self.conv1 = dwconv3x3_block( in_channels=in_channels, out_channels=in_channels, bn_eps=bn_eps, activation=(lambda: PReLU2(in_channels, data_format=data_format, name="activ")), data_format=data_format, name="conv1") self.conv2 = conv1x1( in_channels=in_channels, out_channels=out_channels, data_format=data_format, name="conv2") self.bn = BatchNorm( epsilon=bn_eps, data_format=data_format, name="bn") def call(self, x, training=None): if self.use_scale: x = self.down_scale(x) x = self.conv1(x, training=None) x = self.conv2(x, training=None) if self.use_scale: x = self.up_scale(x) x = self.bn(x, training=None) return x class PreActivation(nn.Layer): """ PreResNet like pure pre-activation block without convolution layer. Parameters: ---------- in_channels : int Number of input channels. bn_eps : float, default 1e-5 Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, bn_eps=1e-5, data_format="channels_last", **kwargs): super(PreActivation, self).__init__(**kwargs) assert (in_channels is not None) self.bn = BatchNorm( epsilon=bn_eps, data_format=data_format, name="bn") self.activ = PReLU2(in_channels, data_format=data_format, name="activ") def call(self, x, training=None): x = self.bn(x, training=None) x = self.activ(x) return x class ESPBlock(nn.Layer): """ ESP block, which is based on the following principle: Reduce ---> Split ---> Transform --> Merge. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_sizes : list of int Convolution window size for branches. scale_factors : list of int Scale factor for branches. use_residual : bool Whether to use residual connection. in_size : tuple of 2 int Spatial size of the output tensor for the bilinear upsampling operation. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_sizes, scale_factors, use_residual, in_size, bn_eps, data_format="channels_last", **kwargs): super(ESPBlock, self).__init__(**kwargs) self.use_residual = use_residual groups = len(kernel_sizes) mid_channels = int(out_channels / groups) res_channels = out_channels - groups * mid_channels self.conv = conv1x1( in_channels=in_channels, out_channels=mid_channels, groups=groups, data_format=data_format, name="conv") self.c_shuffle = ChannelShuffle( channels=mid_channels, groups=groups, data_format=data_format, name="c_shuffle") self.branches = Concurrent( data_format=data_format, name="branches") for i in range(groups): out_channels_i = (mid_channels + res_channels) if i == 0 else mid_channels self.branches.add(SBBlock( in_channels=mid_channels, out_channels=out_channels_i, kernel_size=kernel_sizes[i], scale_factor=scale_factors[i], size=in_size, bn_eps=bn_eps, data_format=data_format, name="branch{}".format(i + 1))) self.preactiv = PreActivation( in_channels=out_channels, bn_eps=bn_eps, data_format=data_format, name="preactiv") def call(self, x, training=None): if self.use_residual: identity = x x = self.conv(x) x = self.c_shuffle(x) x = self.branches(x, training=None) if self.use_residual: x = identity + x x = self.preactiv(x, training=None) return x class SBStage(nn.Layer): """ SB stage. Parameters: ---------- in_channels : int Number of input channels. down_channels : int Number of output channels for a downscale block. channels_list : list of int Number of output channels for all residual block. kernel_sizes_list : list of int Convolution window size for branches. scale_factors_list : list of int Scale factor for branches. use_residual_list : list of int List of flags for using residual in each ESP-block. se_reduction : int Squeeze reduction value (0 means no-se). in_size : tuple of 2 int Spatial size of the output tensor for the bilinear upsampling operation. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, down_channels, channels_list, kernel_sizes_list, scale_factors_list, use_residual_list, se_reduction, in_size, bn_eps, data_format="channels_last", **kwargs): super(SBStage, self).__init__(**kwargs) self.data_format = data_format self.down_conv = dwsconv3x3_block( in_channels=in_channels, out_channels=down_channels, strides=2, dw_use_bn=False, bn_eps=bn_eps, dw_activation=None, pw_activation=(lambda: PReLU2(down_channels, data_format=data_format, name="activ")), se_reduction=se_reduction, data_format=data_format, name="down_conv") in_channels = down_channels self.main_branch = SimpleSequential(name="main_branch") for i, out_channels in enumerate(channels_list): use_residual = (use_residual_list[i] == 1) kernel_sizes = kernel_sizes_list[i] scale_factors = scale_factors_list[i] self.main_branch.add(ESPBlock( in_channels=in_channels, out_channels=out_channels, kernel_sizes=kernel_sizes, scale_factors=scale_factors, use_residual=use_residual, in_size=((in_size[0] // 2, in_size[1] // 2) if in_size else None), bn_eps=bn_eps, data_format=data_format, name="block{}".format(i + 1))) in_channels = out_channels self.preactiv = PreActivation( in_channels=(down_channels + in_channels), bn_eps=bn_eps, data_format=data_format, name="preactiv") def call(self, x, training=None): x = self.down_conv(x, training=None) y = self.main_branch(x, training=None) x = tf.concat([x, y], axis=get_channel_axis(self.data_format)) x = self.preactiv(x, training=None) return x, y class SBEncoderInitBlock(nn.Layer): """ SB encoder specific initial block. Parameters: ---------- in_channels : int Number of input channels. mid_channels : int Number of middle channels. out_channels : int Number of output channels. bn_eps : float, default 1e-5 Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, mid_channels, out_channels, bn_eps, data_format="channels_last", **kwargs): super(SBEncoderInitBlock, self).__init__(**kwargs) self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels, strides=2, bn_eps=bn_eps, activation=(lambda: PReLU2(mid_channels, data_format=data_format, name="activ")), data_format=data_format, name="conv1") self.conv2 = dwsconv3x3_block( in_channels=mid_channels, out_channels=out_channels, strides=2, dw_use_bn=False, bn_eps=bn_eps, dw_activation=None, pw_activation=(lambda: PReLU2(out_channels, data_format=data_format, name="activ")), se_reduction=1, data_format=data_format, name="conv2") def call(self, x, training=None): x = self.conv1(x, training=None) x = self.conv2(x, training=None) return x class SBEncoder(nn.Layer): """ SB encoder for SINet. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of input channels. init_block_channels : list int Number of output channels for convolutions in the initial block. down_channels_list : list of int Number of downsample channels for each residual block. channels_list : list of list of int Number of output channels for all residual block. kernel_sizes_list : list of list of int Convolution window size for each residual block. scale_factors_list : list of list of int Scale factor for each residual block. use_residual_list : list of list of int List of flags for using residual in each residual block. in_size : tuple of 2 int Spatial size of the output tensor for the bilinear upsampling operation. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, init_block_channels, down_channels_list, channels_list, kernel_sizes_list, scale_factors_list, use_residual_list, in_size, bn_eps, data_format="channels_last", **kwargs): super(SBEncoder, self).__init__(**kwargs) self.init_block = SBEncoderInitBlock( in_channels=in_channels, mid_channels=init_block_channels[0], out_channels=init_block_channels[1], bn_eps=bn_eps, data_format=data_format, name="init_block") in_channels = init_block_channels[1] self.stage1 = SBStage( in_channels=in_channels, down_channels=down_channels_list[0], channels_list=channels_list[0], kernel_sizes_list=kernel_sizes_list[0], scale_factors_list=scale_factors_list[0], use_residual_list=use_residual_list[0], se_reduction=1, in_size=((in_size[0] // 4, in_size[1] // 4) if in_size else None), bn_eps=bn_eps, data_format=data_format, name="stage1") in_channels = down_channels_list[0] + channels_list[0][-1] self.stage2 = SBStage( in_channels=in_channels, down_channels=down_channels_list[1], channels_list=channels_list[1], kernel_sizes_list=kernel_sizes_list[1], scale_factors_list=scale_factors_list[1], use_residual_list=use_residual_list[1], se_reduction=2, in_size=((in_size[0] // 8, in_size[1] // 8) if in_size else None), bn_eps=bn_eps, data_format=data_format, name="stage2") in_channels = down_channels_list[1] + channels_list[1][-1] self.output_conv = conv1x1( in_channels=in_channels, out_channels=out_channels, data_format=data_format, name="output") def call(self, x, training=None): y1 = self.init_block(x, training=None) x, y2 = self.stage1(y1, training=None) x, _ = self.stage2(x, training=None) x = self.output_conv(x) return x, y2, y1 class SBDecodeBlock(nn.Layer): """ SB decoder block for SINet. Parameters: ---------- channels : int Number of output classes. out_size : tuple of 2 int Spatial size of the output tensor for the bilinear upsampling operation. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, out_size, bn_eps, data_format="channels_last", **kwargs): super(SBDecodeBlock, self).__init__(**kwargs) assert (channels is not None) self.data_format = data_format self.up = InterpolationBlock( scale_factor=2, out_size=out_size, data_format=data_format, name="up") self.bn = BatchNorm( epsilon=bn_eps, data_format=data_format, name="bn") def call(self, x, y, training=None): x = self.up(x) x = self.bn(x, training=None) w_conf = tf.nn.softmax(x) axis = get_channel_axis(self.data_format) w_max = tf.broadcast_to(tf.expand_dims(tf.reduce_max(w_conf, axis=axis), axis=axis), shape=x.shape) x = y * (1 - w_max) + x return x class SBDecoder(nn.Layer): """ SB decoder for SINet. Parameters: ---------- dim2 : int Size of dimension #2. classes : int Number of segmentation classes. out_size : tuple of 2 int Spatial size of the output tensor for the bilinear upsampling operation. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, dim2, classes, out_size, bn_eps, data_format="channels_last", **kwargs): super(SBDecoder, self).__init__(**kwargs) self.decode1 = SBDecodeBlock( channels=classes, out_size=((out_size[0] // 8, out_size[1] // 8) if out_size else None), bn_eps=bn_eps, data_format=data_format, name="decode1") self.decode2 = SBDecodeBlock( channels=classes, out_size=((out_size[0] // 4, out_size[1] // 4) if out_size else None), bn_eps=bn_eps, data_format=data_format, name="decode2") self.conv3c = conv1x1_block( in_channels=dim2, out_channels=classes, bn_eps=bn_eps, activation=(lambda: PReLU2(classes, data_format=data_format, name="activ")), data_format=data_format, name="conv3c") self.output_conv = nn.Conv2DTranspose( filters=classes, kernel_size=2, strides=2, padding="valid", output_padding=0, use_bias=False, data_format=data_format, name="output_conv") self.up = InterpolationBlock( scale_factor=2, out_size=out_size, data_format=data_format, name="up") def call(self, y3, y2, y1, training=None): y2 = self.conv3c(y2, training=None) x = self.decode1(y3, y2, training=None) x = self.decode2(x, y1, training=None) x = self.output_conv(x, training=None) x = self.up(x) return x class SINet(tf.keras.Model): """ SINet model from 'SINet: Extreme Lightweight Portrait Segmentation Networks with Spatial Squeeze Modules and Information Blocking Decoder,' https://arxiv.org/abs/1911.09099. Parameters: ---------- down_channels_list : list of int Number of downsample channels for each residual block. channels_list : list of list of int Number of output channels for all residual block. kernel_sizes_list : list of list of int Convolution window size for each residual block. scale_factors_list : list of list of int Scale factor for each residual block. use_residual_list : list of list of int List of flags for using residual in each residual block. dim2 : int Size of dimension #2. bn_eps : float Small float added to variance in Batch norm. 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 (1024, 2048) Spatial size of the expected input image. classes : int, default 21 Number of segmentation classes. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, down_channels_list, channels_list, kernel_sizes_list, scale_factors_list, use_residual_list, dim2, bn_eps, aux=False, fixed_size=True, in_channels=3, in_size=(1024, 2048), classes=21, data_format="channels_last", **kwargs): super(SINet, self).__init__(**kwargs) assert (fixed_size is not None) assert (in_channels > 0) assert ((in_size[0] % 64 == 0) and (in_size[1] % 64 == 0)) self.in_size = in_size self.classes = classes self.data_format = data_format self.aux = aux init_block_channels = [16, classes] out_channels = classes self.encoder = SBEncoder( in_channels=in_channels, out_channels=out_channels, init_block_channels=init_block_channels, down_channels_list=down_channels_list, channels_list=channels_list, kernel_sizes_list=kernel_sizes_list, scale_factors_list=scale_factors_list, use_residual_list=use_residual_list, in_size=(in_size if fixed_size else None), bn_eps=bn_eps, data_format=data_format, name="encoder") self.decoder = SBDecoder( dim2=dim2, classes=classes, out_size=(in_size if fixed_size else None), bn_eps=bn_eps, data_format=data_format, name="decoder") def call(self, x, training=None): y3, y2, y1 = self.encoder(x, training=None) x = self.decoder(y3, y2, y1, training=None) if self.aux: return x, y3 else: return x def get_sinet(model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create SINet 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ kernel_sizes_list = [ [[3, 5], [3, 3], [3, 3]], [[3, 5], [3, 3], [5, 5], [3, 5], [3, 5], [3, 5], [3, 3], [5, 5], [3, 5], [3, 5]]] scale_factors_list = [ [[1, 1], [0, 1], [0, 1]], [[1, 1], [0, 1], [1, 4], [2, 8], [1, 1], [1, 1], [0, 1], [1, 8], [2, 4], [0, 2]]] chnn = 4 dims = [24] + [24 * (i + 2) + 4 * (chnn - 1) for i in range(3)] dim1 = dims[0] dim2 = dims[1] dim3 = dims[2] dim4 = dims[3] p = len(kernel_sizes_list[0]) q = len(kernel_sizes_list[1]) channels_list = [[dim2] * p, ([dim3] * (q // 2)) + ([dim4] * (q - q // 2))] use_residual_list = [[0] + ([1] * (p - 1)), [0] + ([1] * (q // 2 - 1)) + [0] + ([1] * (q - q // 2 - 1))] down_channels_list = [dim1, dim2] net = SINet( down_channels_list=down_channels_list, channels_list=channels_list, kernel_sizes_list=kernel_sizes_list, scale_factors_list=scale_factors_list, use_residual_list=use_residual_list, dim2=dims[1], **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def sinet_cityscapes(classes=19, **kwargs): """ SINet model for Cityscapes from 'SINet: Extreme Lightweight Portrait Segmentation Networks with Spatial Squeeze Modules and Information Blocking Decoder,' https://arxiv.org/abs/1911.09099. Parameters: ---------- classes : int, default 19 Number of segmentation classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sinet(classes=classes, bn_eps=1e-3, model_name="sinet_cityscapes", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" in_size = (1024, 2048) aux = False fixed_size = False pretrained = False models = [ sinet_cityscapes, ] for model in models: net = model(pretrained=pretrained, in_size=in_size, aux=aux, fixed_size=fixed_size) batch = 14 x = tf.random.normal((batch, 3, in_size[0], in_size[1]) if is_channels_first(data_format) else (batch, in_size[0], in_size[1], 3)) ys = net(x) y = ys[0] if aux else ys assert (y.shape[0] == x.shape[0]) if is_channels_first(data_format): assert ((y.shape[1] == 19) and (y.shape[2] == x.shape[2]) and (y.shape[3] == x.shape[3])) else: assert ((y.shape[3] == 19) and (y.shape[1] == x.shape[1]) and (y.shape[2] == x.shape[2])) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != sinet_cityscapes or weight_count == 119418) if __name__ == "__main__": _test()
41,973
33.014587
118
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/shufflenetv2b.py
""" ShuffleNet V2 for ImageNet-1K, implemented in TensorFlow. The alternative version. Original paper: 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,' https://arxiv.org/abs/1807.11164. """ __all__ = ['ShuffleNetV2b', 'shufflenetv2b_wd2', 'shufflenetv2b_w1', 'shufflenetv2b_w3d2', 'shufflenetv2b_w2'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1_block, conv3x3_block, dwconv3x3_block, ChannelShuffle, ChannelShuffle2, SEBlock, MaxPool2d,\ SimpleSequential, get_channel_axis, flatten class ShuffleUnit(nn.Layer): """ ShuffleNetV2(b) unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. downsample : bool Whether do downsample. use_se : bool Whether to use SE block. use_residual : bool Whether to use residual connection. shuffle_group_first : bool Whether to use channel shuffle in group first mode. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, downsample, use_se, use_residual, shuffle_group_first, data_format="channels_last", **kwargs): super(ShuffleUnit, self).__init__(**kwargs) self.data_format = data_format self.downsample = downsample self.use_se = use_se self.use_residual = use_residual mid_channels = out_channels // 2 in_channels2 = in_channels // 2 assert (in_channels % 2 == 0) y2_in_channels = (in_channels if downsample else in_channels2) y2_out_channels = out_channels - y2_in_channels self.conv1 = conv1x1_block( in_channels=y2_in_channels, out_channels=mid_channels, data_format=data_format, name="conv1") self.dconv = dwconv3x3_block( in_channels=mid_channels, out_channels=mid_channels, strides=(2 if self.downsample else 1), activation=None, data_format=data_format, name="dconv") self.conv2 = conv1x1_block( in_channels=mid_channels, out_channels=y2_out_channels, data_format=data_format, name="conv2") if self.use_se: self.se = SEBlock( channels=y2_out_channels, data_format=data_format, name="se") if downsample: self.shortcut_dconv = dwconv3x3_block( in_channels=in_channels, out_channels=in_channels, strides=2, activation=None, data_format=data_format, name="shortcut_dconv") self.shortcut_conv = conv1x1_block( in_channels=in_channels, out_channels=in_channels, data_format=data_format, name="shortcut_conv") if shuffle_group_first: self.c_shuffle = ChannelShuffle( channels=out_channels, groups=2, data_format=data_format, name="c_shuffle") else: self.c_shuffle = ChannelShuffle2( channels=out_channels, groups=2, data_format=data_format, name="c_shuffle") def call(self, x, training=None): if self.downsample: y1 = self.shortcut_dconv(x, training=training) y1 = self.shortcut_conv(y1, training=training) x2 = x else: y1, x2 = tf.split(x, num_or_size_splits=2, axis=get_channel_axis(self.data_format)) y2 = self.conv1(x2, training=training) y2 = self.dconv(y2, training=training) y2 = self.conv2(y2, training=training) if self.use_se: y2 = self.se(y2) if self.use_residual and not self.downsample: y2 = y2 + x2 x = tf.concat([y1, y2], axis=get_channel_axis(self.data_format)) x = self.c_shuffle(x) return x class ShuffleInitBlock(nn.Layer): """ ShuffleNetV2(b) specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(ShuffleInitBlock, self).__init__(**kwargs) self.conv = conv3x3_block( in_channels=in_channels, out_channels=out_channels, strides=2, data_format=data_format, name="conv") self.pool = MaxPool2d( pool_size=3, strides=2, padding=1, ceil_mode=False, data_format=data_format, name="pool") def call(self, x, training=None): x = self.conv(x, training=training) x = self.pool(x) return x class ShuffleNetV2b(tf.keras.Model): """ ShuffleNetV2(b) model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,' https://arxiv.org/abs/1807.11164. 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. use_se : bool, default False Whether to use SE block. use_residual : bool, default False Whether to use residual connections. shuffle_group_first : bool, default True Whether to use channel shuffle in group first 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, final_block_channels, use_se=False, use_residual=False, shuffle_group_first=True, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(ShuffleNetV2b, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(ShuffleInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) for j, out_channels in enumerate(channels_per_stage): downsample = (j == 0) stage.add(ShuffleUnit( in_channels=in_channels, out_channels=out_channels, downsample=downsample, use_se=use_se, use_residual=use_residual, shuffle_group_first=shuffle_group_first, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(conv1x1_block( in_channels=in_channels, out_channels=final_block_channels, data_format=data_format, name="final_block")) in_channels = final_block_channels self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_shufflenetv2b(width_scale, shuffle_group_first=True, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create ShuffleNetV2(b) model with specific parameters. Parameters: ---------- width_scale : float Scale factor for width of layers. shuffle_group_first : bool, default True Whether to use channel shuffle in group first mode. 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ init_block_channels = 24 final_block_channels = 1024 layers = [4, 8, 4] channels_per_layers = [116, 232, 464] 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] if width_scale > 1.5: final_block_channels = int(final_block_channels * width_scale) net = ShuffleNetV2b( channels=channels, init_block_channels=init_block_channels, final_block_channels=final_block_channels, shuffle_group_first=shuffle_group_first, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def shufflenetv2b_wd2(**kwargs): """ ShuffleNetV2(b) 0.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,' https://arxiv.org/abs/1807.11164. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_shufflenetv2b( width_scale=(12.0 / 29.0), shuffle_group_first=True, model_name="shufflenetv2b_wd2", **kwargs) def shufflenetv2b_w1(**kwargs): """ ShuffleNetV2(b) 1x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,' https://arxiv.org/abs/1807.11164. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_shufflenetv2b( width_scale=1.0, shuffle_group_first=True, model_name="shufflenetv2b_w1", **kwargs) def shufflenetv2b_w3d2(**kwargs): """ ShuffleNetV2(b) 1.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,' https://arxiv.org/abs/1807.11164. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_shufflenetv2b( width_scale=(44.0 / 29.0), shuffle_group_first=True, model_name="shufflenetv2b_w3d2", **kwargs) def shufflenetv2b_w2(**kwargs): """ ShuffleNetV2(b) 2x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,' https://arxiv.org/abs/1807.11164. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_shufflenetv2b( width_scale=(61.0 / 29.0), shuffle_group_first=True, model_name="shufflenetv2b_w2", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K pretrained = False models = [ shufflenetv2b_wd2, shufflenetv2b_w1, shufflenetv2b_w3d2, shufflenetv2b_w2, ] for model in models: net = model(pretrained=pretrained) batch = 14 x = tf.random.normal((batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != shufflenetv2b_wd2 or weight_count == 1366792) assert (model != shufflenetv2b_w1 or weight_count == 2279760) assert (model != shufflenetv2b_w3d2 or weight_count == 4410194) assert (model != shufflenetv2b_w2 or weight_count == 7611290) if __name__ == "__main__": _test()
14,161
32.559242
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/menet.py
""" MENet for ImageNet-1K, implemented in TensorFlow. Original paper: 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,' https://arxiv.org/abs/1803.09127. """ __all__ = ['MENet', 'menet108_8x1_g3', 'menet128_8x1_g4', 'menet160_8x1_g8', 'menet228_12x1_g3', 'menet256_12x1_g4', 'menet348_12x1_g3', 'menet352_12x1_g8', 'menet456_24x1_g3'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1, conv3x3, depthwise_conv3x3, ChannelShuffle, Conv2d, BatchNorm, AvgPool2d,\ MaxPool2d, SimpleSequential, get_channel_axis, flatten class MEUnit(nn.Layer): """ MENet unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. side_channels : int Number of side 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, side_channels, groups, downsample, ignore_group, data_format="channels_last", **kwargs): super(MEUnit, self).__init__(**kwargs) self.data_format = data_format self.downsample = downsample mid_channels = out_channels // 4 if downsample: out_channels -= in_channels # residual branch self.compress_conv1 = conv1x1( in_channels=in_channels, out_channels=mid_channels, groups=(1 if ignore_group else groups), data_format=data_format, name="compress_conv1") self.compress_bn1 = BatchNorm( # in_channels=mid_channels, data_format=data_format, name="compress_bn1") self.c_shuffle = ChannelShuffle( channels=mid_channels, groups=groups, data_format=data_format, name="c_shuffle") self.dw_conv2 = depthwise_conv3x3( channels=mid_channels, strides=(2 if self.downsample else 1), data_format=data_format, name="dw_conv2") self.dw_bn2 = BatchNorm( # in_channels=mid_channels, data_format=data_format, name="dw_bn2") self.expand_conv3 = conv1x1( in_channels=mid_channels, out_channels=out_channels, groups=groups, data_format=data_format, name="expand_conv3") self.expand_bn3 = BatchNorm( # in_channels=out_channels, data_format=data_format, name="expand_bn3") if downsample: self.avgpool = AvgPool2d( pool_size=3, strides=2, padding=1, data_format=data_format, name="avgpool") self.activ = nn.ReLU() # fusion branch self.s_merge_conv = conv1x1( in_channels=mid_channels, out_channels=side_channels, data_format=data_format, name="s_merge_conv") self.s_merge_bn = BatchNorm( # in_channels=side_channels, data_format=data_format, name="s_merge_bn") self.s_conv = conv3x3( in_channels=side_channels, out_channels=side_channels, strides=(2 if self.downsample else 1), data_format=data_format, name="s_conv") self.s_conv_bn = BatchNorm( # in_channels=side_channels, data_format=data_format, name="s_conv_bn") self.s_evolve_conv = conv1x1( in_channels=side_channels, out_channels=mid_channels, data_format=data_format, name="s_evolve_conv") self.s_evolve_bn = BatchNorm( # in_channels=mid_channels, data_format=data_format, name="s_evolve_bn") def call(self, x, training=None): identity = x # pointwise group convolution 1 x = self.compress_conv1(x) x = self.compress_bn1(x, training=training) x = self.activ(x) x = self.c_shuffle(x) # merging y = self.s_merge_conv(x) y = self.s_merge_bn(y, training=training) y = self.activ(y) # depthwise convolution (bottleneck) x = self.dw_conv2(x) x = self.dw_bn2(x, training=training) # evolution y = self.s_conv(y) y = self.s_conv_bn(y, training=training) y = self.activ(y) y = self.s_evolve_conv(y) y = self.s_evolve_bn(y, training=training) y = tf.nn.sigmoid(y) x = x * y # pointwise group convolution 2 x = self.expand_conv3(x) x = self.expand_bn3(x, training=training) # identity branch if self.downsample: identity = self.avgpool(identity) x = tf.concat([x, identity], axis=get_channel_axis(self.data_format)) else: x = x + identity x = self.activ(x) return x class MEInitBlock(nn.Layer): """ MENet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(MEInitBlock, self).__init__(**kwargs) self.conv = Conv2d( in_channels=in_channels, out_channels=out_channels, kernel_size=3, strides=2, padding=1, use_bias=False, data_format=data_format, name="conv") self.bn = BatchNorm( # in_channels=out_channels, data_format=data_format, name="bn") self.activ = nn.ReLU() self.pool = MaxPool2d( pool_size=3, strides=2, padding=1, data_format=data_format, name="pool") def call(self, x, training=None): x = self.conv(x) x = self.bn(x, training=training) x = self.activ(x) x = self.pool(x) return x class MENet(tf.keras.Model): """ MENet model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,' https://arxiv.org/abs/1803.09127. 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. side_channels : int Number of side channels in a ME-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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, side_channels, groups, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(MENet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(MEInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) for j, out_channels in enumerate(channels_per_stage): downsample = (j == 0) ignore_group = (i == 0) and (j == 0) stage.add(MEUnit( in_channels=in_channels, out_channels=out_channels, side_channels=side_channels, groups=groups, downsample=downsample, ignore_group=ignore_group, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_menet(first_stage_channels, side_channels, groups, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create MENet model with specific parameters. Parameters: ---------- first_stage_channels : int Number of output channels at the first stage. side_channels : int Number of side channels in a ME-unit. groups : int Number of groups in convolution 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ layers = [4, 8, 4] if first_stage_channels == 108: init_block_channels = 12 channels_per_layers = [108, 216, 432] elif first_stage_channels == 128: init_block_channels = 12 channels_per_layers = [128, 256, 512] elif first_stage_channels == 160: init_block_channels = 16 channels_per_layers = [160, 320, 640] elif first_stage_channels == 228: init_block_channels = 24 channels_per_layers = [228, 456, 912] elif first_stage_channels == 256: init_block_channels = 24 channels_per_layers = [256, 512, 1024] elif first_stage_channels == 348: init_block_channels = 24 channels_per_layers = [348, 696, 1392] elif first_stage_channels == 352: init_block_channels = 24 channels_per_layers = [352, 704, 1408] elif first_stage_channels == 456: init_block_channels = 48 channels_per_layers = [456, 912, 1824] else: raise ValueError("The {} of `first_stage_channels` is not supported".format(first_stage_channels)) channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)] net = MENet( channels=channels, init_block_channels=init_block_channels, side_channels=side_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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def menet108_8x1_g3(**kwargs): """ 108-MENet-8x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,' https://arxiv.org/abs/1803.09127. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_menet(first_stage_channels=108, side_channels=8, groups=3, model_name="menet108_8x1_g3", **kwargs) def menet128_8x1_g4(**kwargs): """ 128-MENet-8x1 (g=4) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,' https://arxiv.org/abs/1803.09127. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_menet(first_stage_channels=128, side_channels=8, groups=4, model_name="menet128_8x1_g4", **kwargs) def menet160_8x1_g8(**kwargs): """ 160-MENet-8x1 (g=8) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,' https://arxiv.org/abs/1803.09127. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_menet(first_stage_channels=160, side_channels=8, groups=8, model_name="menet160_8x1_g8", **kwargs) def menet228_12x1_g3(**kwargs): """ 228-MENet-12x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,' https://arxiv.org/abs/1803.09127. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_menet(first_stage_channels=228, side_channels=12, groups=3, model_name="menet228_12x1_g3", **kwargs) def menet256_12x1_g4(**kwargs): """ 256-MENet-12x1 (g=4) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,' https://arxiv.org/abs/1803.09127. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_menet(first_stage_channels=256, side_channels=12, groups=4, model_name="menet256_12x1_g4", **kwargs) def menet348_12x1_g3(**kwargs): """ 348-MENet-12x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,' https://arxiv.org/abs/1803.09127. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_menet(first_stage_channels=348, side_channels=12, groups=3, model_name="menet348_12x1_g3", **kwargs) def menet352_12x1_g8(**kwargs): """ 352-MENet-12x1 (g=8) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,' https://arxiv.org/abs/1803.09127. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_menet(first_stage_channels=352, side_channels=12, groups=8, model_name="menet352_12x1_g8", **kwargs) def menet456_24x1_g3(**kwargs): """ 456-MENet-24x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,' https://arxiv.org/abs/1803.09127. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_menet(first_stage_channels=456, side_channels=24, groups=3, model_name="menet456_24x1_g3", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K pretrained = False models = [ menet108_8x1_g3, menet128_8x1_g4, menet160_8x1_g8, menet228_12x1_g3, menet256_12x1_g4, menet348_12x1_g3, menet352_12x1_g8, menet456_24x1_g3, ] for model in models: net = model(pretrained=pretrained) batch = 14 x = tf.random.normal((batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != menet108_8x1_g3 or weight_count == 654516) assert (model != menet128_8x1_g4 or weight_count == 750796) assert (model != menet160_8x1_g8 or weight_count == 850120) assert (model != menet228_12x1_g3 or weight_count == 1806568) assert (model != menet256_12x1_g4 or weight_count == 1888240) assert (model != menet348_12x1_g3 or weight_count == 3368128) assert (model != menet352_12x1_g8 or weight_count == 2272872) assert (model != menet456_24x1_g3 or weight_count == 5304784) if __name__ == "__main__": _test()
18,147
33.112782
116
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/voca.py
""" VOCA for speech-driven facial animation, implemented in TensorFlow. Original paper: 'Capture, Learning, and Synthesis of 3D Speaking Styles,' https://arxiv.org/abs/1905.03079. """ __all__ = ['VOCA', 'voca8flame'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import BatchNorm, ConvBlock, SimpleSequential, flatten, get_channel_axis, is_channels_first class VocaEncoder(nn.Layer): """ VOCA encoder. Parameters: ---------- audio_features : int Number of audio features (characters/sounds). audio_window_size : int Size of audio window (for time related audio features). base_persons : int Number of base persons (subjects). encoder_features : int Number of encoder features. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, audio_features, audio_window_size, base_persons, encoder_features, data_format="channels_last", **kwargs): super(VocaEncoder, self).__init__(**kwargs) self.audio_window_size = audio_window_size self.data_format = data_format channels = (32, 32, 64, 64) fc1_channels = 128 self.bn = BatchNorm( epsilon=1e-5, data_format=data_format, name="bn") in_channels = audio_features + base_persons self.branch = SimpleSequential(name="branch") for i, out_channels in enumerate(channels): self.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, data_format=data_format, name="conv{}".format(i + 1))) in_channels = out_channels in_channels += base_persons self.fc1 = nn.Dense( units=fc1_channels, input_dim=in_channels, name="fc1") self.fc2 = nn.Dense( units=encoder_features, input_dim=fc1_channels, name="fc2") def call(self, x, pid, training=None): x = self.bn(x, training=training) if is_channels_first(self.data_format): x = tf.transpose(x, perm=(0, 3, 2, 1)) y = tf.expand_dims(tf.expand_dims(pid, -1), -1) y = tf.tile(y, multiples=(1, 1, self.audio_window_size, 1)) else: x = tf.transpose(x, perm=(0, 1, 3, 2)) y = tf.expand_dims(tf.expand_dims(pid, 1), 1) y = tf.tile(y, multiples=(1, self.audio_window_size, 1, 1)) x = tf.concat([x, y], axis=get_channel_axis(self.data_format)) x = self.branch(x) x = flatten(x, self.data_format) x = tf.concat([x, pid], axis=1) x = self.fc1(x) x = tf.math.tanh(x) x = self.fc2(x) return x class VOCA(tf.keras.Model): """ VOCA model from 'Capture, Learning, and Synthesis of 3D Speaking Styles,' https://arxiv.org/abs/1905.03079. 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). base_persons : int, default 8 Number of base persons (subjects). encoder_features : int, default 50 Number of encoder features. vertices : int, default 5023 Number of 3D geometry vertices. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, audio_features=29, audio_window_size=16, base_persons=8, encoder_features=50, vertices=5023, data_format="channels_last", **kwargs): super(VOCA, self).__init__(**kwargs) self.base_persons = base_persons self.data_format = data_format self.encoder = VocaEncoder( audio_features=audio_features, audio_window_size=audio_window_size, base_persons=base_persons, encoder_features=encoder_features, data_format=data_format, name="encoder") self.decoder = nn.Dense( units=(3 * vertices), input_dim=encoder_features, name="decoder") def call(self, x, pid, training=None): pid = tf.one_hot(pid, depth=self.base_persons) x = self.encoder(x, pid, training=training) x = self.decoder(x) x = tf.reshape(x, shape=(x.get_shape().as_list()[0], 1, -1, 3)) if is_channels_first(self.data_format) else\ tf.reshape(x, shape=(x.get_shape().as_list()[0], -1, 3, 1)) return x def get_voca(base_persons, vertices, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create VOCA model with specific parameters. Parameters: ---------- base_persons : int Number of base persons (subjects). vertices : int Number of 3D geometry vertices. 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ net = VOCA( base_persons=base_persons, vertices=vertices, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def voca8flame(**kwargs): """ VOCA-8-FLAME model for 8 base persons and FLAME topology from 'Capture, Learning, and Synthesis of 3D Speaking Styles,' https://arxiv.org/abs/1905.03079. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_voca(base_persons=8, vertices=5023, model_name="voca8flame", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K # data_format = "channels_first" data_format = "channels_last" pretrained = False models = [ voca8flame, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 audio_features = 29 audio_window_size = 16 vertices = 5023 x = tf.random.normal((batch, 1, audio_window_size, audio_features) if is_channels_first(data_format) else (batch, audio_window_size, audio_features, 1)) pid = tf.fill(dims=(batch,), value=3) y = net(x, pid) if is_channels_first(data_format): assert (y.shape == (batch, 1, vertices, 3)) else: assert (y.shape == (batch, vertices, 3, 1)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != voca8flame or weight_count == 809563) if __name__ == "__main__": _test()
8,094
32.589212
116
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/wrn_cifar.py
""" WRN for CIFAR/SVHN, implemented in TensorFlow. Original paper: 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146. """ __all__ = ['CIFARWRN', 'wrn16_10_cifar10', 'wrn16_10_cifar100', 'wrn16_10_svhn', 'wrn28_10_cifar10', 'wrn28_10_cifar100', 'wrn28_10_svhn', 'wrn40_8_cifar10', 'wrn40_8_cifar100', 'wrn40_8_svhn'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv3x3, SimpleSequential, flatten, is_channels_first from .preresnet import PreResUnit, PreResActivation class CIFARWRN(tf.keras.Model): """ WRN model for CIFAR 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, in_channels=3, in_size=(32, 32), classes=10, data_format="channels_last", **kwargs): super(CIFARWRN, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(conv3x3( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(PreResUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, bottleneck=False, conv1_stride=False, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(PreResActivation( in_channels=in_channels, data_format=data_format, name="post_activ")) self.features.add(nn.AveragePooling2D( pool_size=8, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_wrn_cifar(classes, blocks, width_factor, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create WRN model for CIFAR with specific parameters. Parameters: ---------- classes : int Number of classification classes. blocks : int Number of blocks. width_factor : int 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ assert ((blocks - 4) % 6 == 0) layers = [(blocks - 4) // 6] * 3 channels_per_layers = [16, 32, 64] init_block_channels = 16 channels = [[ci * width_factor] * li for (ci, li) in zip(channels_per_layers, layers)] net = CIFARWRN( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def wrn16_10_cifar10(classes=10, **kwargs): """ WRN-16-10 model for CIFAR-10 from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_wrn_cifar(classes=classes, blocks=16, width_factor=10, model_name="wrn16_10_cifar10", **kwargs) def wrn16_10_cifar100(classes=100, **kwargs): """ WRN-16-10 model for CIFAR-100 from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_wrn_cifar(classes=classes, blocks=16, width_factor=10, model_name="wrn16_10_cifar100", **kwargs) def wrn16_10_svhn(classes=10, **kwargs): """ WRN-16-10 model for SVHN from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_wrn_cifar(classes=classes, blocks=16, width_factor=10, model_name="wrn16_10_svhn", **kwargs) def wrn28_10_cifar10(classes=10, **kwargs): """ WRN-28-10 model for CIFAR-10 from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_wrn_cifar(classes=classes, blocks=28, width_factor=10, model_name="wrn28_10_cifar10", **kwargs) def wrn28_10_cifar100(classes=100, **kwargs): """ WRN-28-10 model for CIFAR-100 from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_wrn_cifar(classes=classes, blocks=28, width_factor=10, model_name="wrn28_10_cifar100", **kwargs) def wrn28_10_svhn(classes=10, **kwargs): """ WRN-28-10 model for SVHN from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_wrn_cifar(classes=classes, blocks=28, width_factor=10, model_name="wrn28_10_svhn", **kwargs) def wrn40_8_cifar10(classes=10, **kwargs): """ WRN-40-8 model for CIFAR-10 from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_wrn_cifar(classes=classes, blocks=40, width_factor=8, model_name="wrn40_8_cifar10", **kwargs) def wrn40_8_cifar100(classes=100, **kwargs): """ WRN-40-8 model for CIFAR-100 from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_wrn_cifar(classes=classes, blocks=40, width_factor=8, model_name="wrn40_8_cifar100", **kwargs) def wrn40_8_svhn(classes=10, **kwargs): """ WRN-40-8 model for SVHN from 'Wide Residual Networks,' https://arxiv.org/abs/1605.07146. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_wrn_cifar(classes=classes, blocks=40, width_factor=8, model_name="wrn40_8_svhn", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" pretrained = False models = [ (wrn16_10_cifar10, 10), (wrn16_10_cifar100, 100), (wrn16_10_svhn, 10), (wrn28_10_cifar10, 10), (wrn28_10_cifar100, 100), (wrn28_10_svhn, 10), (wrn40_8_cifar10, 10), (wrn40_8_cifar100, 100), (wrn40_8_svhn, 10), ] for model, classes in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 32, 32) if is_channels_first(data_format) else (batch, 32, 32, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, classes)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != wrn16_10_cifar10 or weight_count == 17116634) assert (model != wrn16_10_cifar100 or weight_count == 17174324) assert (model != wrn16_10_svhn or weight_count == 17116634) assert (model != wrn28_10_cifar10 or weight_count == 36479194) assert (model != wrn28_10_cifar100 or weight_count == 36536884) assert (model != wrn28_10_svhn or weight_count == 36479194) assert (model != wrn40_8_cifar10 or weight_count == 35748314) assert (model != wrn40_8_cifar100 or weight_count == 35794484) assert (model != wrn40_8_svhn or weight_count == 35748314) if __name__ == "__main__": _test()
11,768
34.342342
115
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/inceptionresnetv2.py
""" InceptionResNetV2 for ImageNet-1K, implemented in TensorFlow. Original paper: 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,' https://arxiv.org/abs/1602.07261. """ __all__ = ['InceptionResNetV2', 'inceptionresnetv2'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import MaxPool2d, conv1x1_block, conv3x3_block, SimpleSequential, Concurrent, flatten, is_channels_first from .inceptionv3 import AvgPoolBranch, Conv1x1Branch, ConvSeqBranch from .inceptionresnetv1 import InceptionAUnit, InceptionBUnit, InceptionCUnit, ReductionAUnit, ReductionBUnit class InceptBlock5b(nn.Layer): """ InceptionResNetV2 type Mixed-5b block. Parameters: ---------- bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, bn_eps, data_format="channels_last", **kwargs): super(InceptBlock5b, self).__init__(**kwargs) in_channels = 192 self.branches = Concurrent( data_format=data_format, name="branches") self.branches.children.append(Conv1x1Branch( in_channels=in_channels, out_channels=96, bn_eps=bn_eps, data_format=data_format, name="branch1")) self.branches.children.append(ConvSeqBranch( in_channels=in_channels, out_channels_list=(48, 64), kernel_size_list=(1, 5), strides_list=(1, 1), padding_list=(0, 2), bn_eps=bn_eps, data_format=data_format, name="branch2")) self.branches.children.append(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_eps=bn_eps, data_format=data_format, name="branch3")) self.branches.children.append(AvgPoolBranch( in_channels=in_channels, out_channels=64, bn_eps=bn_eps, data_format=data_format, name="branch4")) def call(self, x, training=None): x = self.branches(x, training=training) return x class InceptInitBlock(nn.Layer): """ InceptionResNetV2 specific initial block. Parameters: ---------- in_channels : int Number of input channels. bn_eps : float Small float added to variance in Batch norm. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, bn_eps, in_channels, data_format="channels_last", **kwargs): super(InceptInitBlock, self).__init__(**kwargs) self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=32, strides=2, padding=0, bn_eps=bn_eps, data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=32, out_channels=32, strides=1, padding=0, bn_eps=bn_eps, data_format=data_format, name="conv2") self.conv3 = conv3x3_block( in_channels=32, out_channels=64, strides=1, padding=1, bn_eps=bn_eps, data_format=data_format, name="conv3") self.pool1 = MaxPool2d( pool_size=3, strides=2, padding=0, data_format=data_format, name="pool1") self.conv4 = conv1x1_block( in_channels=64, out_channels=80, strides=1, padding=0, bn_eps=bn_eps, data_format=data_format, name="conv4") self.conv5 = conv3x3_block( in_channels=80, out_channels=192, strides=1, padding=0, bn_eps=bn_eps, data_format=data_format, name="conv5") self.pool2 = MaxPool2d( pool_size=3, strides=2, padding=0, data_format=data_format, name="pool2") self.block = InceptBlock5b( bn_eps=bn_eps, data_format=data_format, name="block") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.conv3(x, training=training) x = self.pool1(x) x = self.conv4(x, training=training) x = self.conv5(x, training=training) x = self.pool2(x) x = self.block(x, training=training) return x class InceptionResNetV2(tf.keras.Model): """ InceptionResNetV2 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,' https://arxiv.org/abs/1602.07261. Parameters: ---------- dropout_rate : float, default 0.0 Fraction of the input units to drop. Must be a number between 0 and 1. bn_eps : float, default 1e-5 Small float added to variance in Batch norm. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, dropout_rate=0.0, bn_eps=1e-5, in_channels=3, in_size=(299, 299), classes=1000, data_format="channels_last", **kwargs): super(InceptionResNetV2, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format layers = [10, 21, 11] in_channels_list = [320, 1088, 2080] normal_out_channels_list = [[32, 32, 32, 32, 48, 64], [192, 128, 160, 192], [192, 192, 224, 256]] reduction_out_channels_list = [[384, 256, 256, 384], [256, 384, 256, 288, 256, 288, 320]] normal_units = [InceptionAUnit, InceptionBUnit, InceptionCUnit] reduction_units = [ReductionAUnit, ReductionBUnit] self.features = SimpleSequential(name="features") self.features.add(InceptInitBlock( in_channels=in_channels, bn_eps=bn_eps, data_format=data_format, name="init_block")) in_channels = in_channels_list[0] for i, layers_per_stage in enumerate(layers): stage = SimpleSequential(name="stage{}".format(i + 1)) for j in range(layers_per_stage): if (j == 0) and (i != 0): unit = reduction_units[i - 1] out_channels_list_per_stage = reduction_out_channels_list[i - 1] else: unit = normal_units[i] out_channels_list_per_stage = normal_out_channels_list[i] if (i == len(layers) - 1) and (j == layers_per_stage - 1): unit_kwargs = {"scale": 1.0, "activate": False} else: unit_kwargs = {} stage.add(unit( in_channels=in_channels, out_channels_list=out_channels_list_per_stage, bn_eps=bn_eps, data_format=data_format, name="unit{}".format(j + 1), **unit_kwargs)) if (j == 0) and (i != 0): in_channels = in_channels_list[i] self.features.add(stage) self.features.add(conv1x1_block( in_channels=2080, out_channels=1536, bn_eps=bn_eps, data_format=data_format, name="final_block")) self.features.add(nn.AveragePooling2D( pool_size=8, strides=1, data_format=data_format, name="final_pool")) self.output1 = SimpleSequential(name="output1") if dropout_rate > 0.0: self.output1.add(nn.Dropout( rate=dropout_rate, name="output1/dropout")) self.output1.add(nn.Dense( units=classes, input_dim=1536, name="output1/fc")) def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_inceptionresnetv2(model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create InceptionResNetV2 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ net = InceptionResNetV2(**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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def inceptionresnetv2(**kwargs): """ InceptionResNetV2 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,' https://arxiv.org/abs/1602.07261. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_inceptionresnetv2(model_name="inceptionresnetv2", bn_eps=1e-3, **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ inceptionresnetv2, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 299, 299) if is_channels_first(data_format) else (batch, 299, 299, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != inceptionresnetv2 or weight_count == 55843464) if __name__ == "__main__": _test()
11,470
33.038576
117
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/ghostnet.py
""" GhostNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'GhostNet: More Features from Cheap Operations,' https://arxiv.org/abs/1911.11907. """ __all__ = ['GhostNet', 'ghostnet'] import os import math import tensorflow as tf import tensorflow.keras.layers as nn from .common import round_channels, conv1x1, conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv5x5_block,\ dwsconv3x3_block, SEBlock, SimpleSequential, get_channel_axis, flatten, is_channels_first class GhostHSigmoid(nn.Layer): """ Approximated sigmoid function, specific for GhostNet. """ def __init__(self, **kwargs): super(GhostHSigmoid, self).__init__(**kwargs) def call(self, x, training=None): return tf.clip_by_value(x, 0.0, 1.0) class GhostConvBlock(nn.Layer): """ GhostNet specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. activation : function or str or None, default 'relu' Activation function or name of activation function. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, activation="relu", data_format="channels_last", **kwargs): super(GhostConvBlock, self).__init__(**kwargs) self.data_format = data_format main_out_channels = math.ceil(0.5 * out_channels) cheap_out_channels = out_channels - main_out_channels self.main_conv = conv1x1_block( in_channels=in_channels, out_channels=main_out_channels, activation=activation, data_format=data_format, name="main_conv") self.cheap_conv = dwconv3x3_block( in_channels=main_out_channels, out_channels=cheap_out_channels, activation=activation, data_format=data_format, name="cheap_conv") def call(self, x, training=None): x = self.main_conv(x, training=training) y = self.cheap_conv(x, training=training) return tf.concat([x, y], axis=get_channel_axis(self.data_format)) class GhostExpBlock(nn.Layer): """ GhostNet expansion block for residual path in GhostNet 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_kernel3 : bool Whether to use 3x3 (instead of 5x5) kernel. exp_factor : float Expansion factor. use_se : bool Whether to use SE-module. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, use_kernel3, exp_factor, use_se, data_format="channels_last", **kwargs): super(GhostExpBlock, self).__init__(**kwargs) self.use_dw_conv = (strides != 1) self.use_se = use_se mid_channels = int(math.ceil(exp_factor * in_channels)) self.exp_conv = GhostConvBlock( in_channels=in_channels, out_channels=mid_channels, name="exp_conv") if self.use_dw_conv: dw_conv_class = dwconv3x3_block if use_kernel3 else dwconv5x5_block self.dw_conv = dw_conv_class( in_channels=mid_channels, out_channels=mid_channels, strides=strides, activation=None, data_format=data_format, name="dw_conv") if self.use_se: self.se = SEBlock( channels=mid_channels, reduction=4, out_activation=GhostHSigmoid(), data_format=data_format, name="se") self.pw_conv = GhostConvBlock( in_channels=mid_channels, out_channels=out_channels, activation=None, data_format=data_format, name="pw_conv") def call(self, x, training=None): x = self.exp_conv(x, training=training) if self.use_dw_conv: x = self.dw_conv(x, training=training) if self.use_se: x = self.se(x) x = self.pw_conv(x, training=training) return x class GhostUnit(nn.Layer): """ GhostNet 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 : float Expansion factor. use_se : bool Whether to use SE-module. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, use_kernel3, exp_factor, use_se, data_format="channels_last", **kwargs): super(GhostUnit, self).__init__(**kwargs) self.resize_identity = (in_channels != out_channels) or (strides != 1) self.body = GhostExpBlock( in_channels=in_channels, out_channels=out_channels, strides=strides, use_kernel3=use_kernel3, exp_factor=exp_factor, use_se=use_se, data_format=data_format, name="body") if self.resize_identity: self.identity_conv = dwsconv3x3_block( in_channels=in_channels, out_channels=out_channels, strides=strides, pw_activation=None, data_format=data_format, name="identity_conv") def call(self, x, training=None): if self.resize_identity: identity = self.identity_conv(x, training=training) else: identity = x x = self.body(x, training=training) x = x + identity return x class GhostClassifier(nn.Layer): """ GhostNet classifier. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. mid_channels : int Number of middle channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, mid_channels, data_format="channels_last", **kwargs): super(GhostClassifier, self).__init__(**kwargs) self.conv1 = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv1") self.conv2 = conv1x1( in_channels=mid_channels, out_channels=out_channels, use_bias=True, data_format=data_format, name="conv2") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x) return x class GhostNet(tf.keras.Model): """ GhostNet model from 'GhostNet: More Features from Cheap Operations,' https://arxiv.org/abs/1911.11907. 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. 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. exp_factors : list of list of int Expansion factor 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, final_block_channels, classifier_mid_channels, kernels3, exp_factors, use_se, first_stride, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(GhostNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(conv3x3_block( in_channels=in_channels, out_channels=init_block_channels, strides=2, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) for j, out_channels in enumerate(channels_per_stage): strides = 2 if (j == 0) and ((i != 0) or first_stride) else 1 use_kernel3 = kernels3[i][j] == 1 exp_factor = exp_factors[i][j] use_se_flag = use_se[i][j] == 1 stage.add(GhostUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, use_kernel3=use_kernel3, exp_factor=exp_factor, use_se=use_se_flag, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(conv1x1_block( in_channels=in_channels, out_channels=final_block_channels, data_format=data_format, name="final_block")) in_channels = final_block_channels self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = GhostClassifier( in_channels=in_channels, out_channels=classes, mid_channels=classifier_mid_channels, data_format=data_format, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = self.output1(x, training=training) x = flatten(x, self.data_format) return x def get_ghostnet(width_scale=1.0, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create GhostNet model with specific parameters. Parameters: ---------- 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ init_block_channels = 16 channels = [[16], [24, 24], [40, 40], [80, 80, 80, 80, 112, 112], [160, 160, 160, 160, 160]] kernels3 = [[1], [1, 1], [0, 0], [1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0]] exp_factors = [[1], [3, 3], [3, 3], [6, 2.5, 2.3, 2.3, 6, 6], [6, 6, 6, 6, 6]] use_se = [[0], [0, 0], [1, 1], [0, 0, 0, 0, 1, 1], [1, 0, 1, 0, 1]] final_block_channels = 960 classifier_mid_channels = 1280 first_stride = False if width_scale != 1.0: channels = [[round_channels(cij * width_scale, divisor=4) for cij in ci] for ci in channels] init_block_channels = round_channels(init_block_channels * width_scale, divisor=4) if width_scale > 1.0: final_block_channels = round_channels(final_block_channels * width_scale, divisor=4) net = GhostNet( channels=channels, init_block_channels=init_block_channels, final_block_channels=final_block_channels, classifier_mid_channels=classifier_mid_channels, kernels3=kernels3, exp_factors=exp_factors, use_se=use_se, first_stride=first_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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def ghostnet(**kwargs): """ GhostNet model from 'GhostNet: More Features from Cheap Operations,' https://arxiv.org/abs/1911.11907. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_ghostnet(model_name="ghostnet", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ ghostnet, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != ghostnet or weight_count == 5180840) if __name__ == "__main__": _test()
15,092
32.614699
115
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/efficientnet.py
""" EfficientNet for ImageNet-1K, implemented in TensorFlow. Original papers: - 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946, - 'Adversarial Examples Improve Image Recognition,' https://arxiv.org/abs/1911.09665. """ __all__ = ['EfficientNet', 'calc_tf_padding', 'EffiInvResUnit', 'EffiInitBlock', 'efficientnet_b0', 'efficientnet_b1', 'efficientnet_b2', 'efficientnet_b3', 'efficientnet_b4', 'efficientnet_b5', 'efficientnet_b6', 'efficientnet_b7', 'efficientnet_b8', 'efficientnet_b0b', 'efficientnet_b1b', 'efficientnet_b2b', 'efficientnet_b3b', 'efficientnet_b4b', 'efficientnet_b5b', 'efficientnet_b6b', 'efficientnet_b7b', 'efficientnet_b0c', 'efficientnet_b1c', 'efficientnet_b2c', 'efficientnet_b3c', 'efficientnet_b4c', 'efficientnet_b5c', 'efficientnet_b6c', 'efficientnet_b7c', 'efficientnet_b8c'] import os import math import tensorflow as tf import tensorflow.keras.layers as nn from .common import round_channels, conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv5x5_block, SEBlock,\ SimpleSequential, is_channels_first def calc_tf_padding(x, kernel_size, strides=1, dilation=1, data_format="channels_last"): """ Calculate TF-same like padding size. Parameters: ---------- x : tensor Input tensor. kernel_size : int Convolution window size. strides : int, default 1 Strides of the convolution. dilation : int, default 1 Dilation value for convolution layer. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. Returns: ------- tuple of 4 int The size of the padding. """ height, width = x.shape[2:] oh = math.ceil(height / strides) ow = math.ceil(width / strides) pad_h = max((oh - 1) * strides + (kernel_size - 1) * dilation + 1 - height, 0) pad_w = max((ow - 1) * strides + (kernel_size - 1) * dilation + 1 - width, 0) if is_channels_first(data_format): paddings_tf = [[0, 0], [0, 0], [pad_h // 2, pad_h - pad_h // 2], [pad_w // 2, pad_w - pad_w // 2]] else: paddings_tf = [[0, 0], [pad_h // 2, pad_h - pad_h // 2], [pad_w // 2, pad_w - pad_w // 2], [0, 0]] return paddings_tf class EffiDwsConvUnit(nn.Layer): """ EfficientNet specific depthwise separable convolution block/unit with BatchNorms and activations at each convolution layers. 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_eps : float Small float added to variance in Batch norm. activation : str Name of activation function. tf_mode : bool Whether to use TF-like mode. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, bn_eps, activation, tf_mode, data_format="channels_last", **kwargs): super(EffiDwsConvUnit, self).__init__(**kwargs) self.tf_mode = tf_mode self.data_format = data_format self.residual = (in_channels == out_channels) and (strides == 1) self.dw_conv = dwconv3x3_block( in_channels=in_channels, out_channels=in_channels, padding=(0 if tf_mode else 1), bn_eps=bn_eps, activation=activation, data_format=data_format, name="dw_conv") self.se = SEBlock( channels=in_channels, reduction=4, mid_activation=activation, data_format=data_format, name="se") self.pw_conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, bn_eps=bn_eps, activation=None, data_format=data_format, name="pw_conv") def call(self, x, training=None): if self.residual: identity = x if self.tf_mode: x = tf.pad(x, paddings=calc_tf_padding(x, kernel_size=3, data_format=self.data_format)) x = self.dw_conv(x, training=training) x = self.se(x) x = self.pw_conv(x, training=training) if self.residual: x = x + identity return x class EffiInvResUnit(nn.Layer): """ EfficientNet inverted residual unit. 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 second convolution layer. exp_factor : int Factor for expansion of channels. se_factor : int SE reduction factor for each unit. bn_eps : float Small float added to variance in Batch norm. activation : str Name of activation function. tf_mode : bool Whether to use TF-like mode. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, strides, exp_factor, se_factor, bn_eps, activation, tf_mode, data_format="channels_last", **kwargs): super(EffiInvResUnit, self).__init__(**kwargs) self.kernel_size = kernel_size self.strides = strides self.tf_mode = tf_mode self.data_format = data_format self.residual = (in_channels == out_channels) and (strides == 1) self.use_se = se_factor > 0 mid_channels = in_channels * exp_factor dwconv_block_fn = dwconv3x3_block if kernel_size == 3 else (dwconv5x5_block if kernel_size == 5 else None) self.conv1 = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, bn_eps=bn_eps, activation=activation, data_format=data_format, name="conv1") self.conv2 = dwconv_block_fn( in_channels=mid_channels, out_channels=mid_channels, strides=strides, padding=(0 if tf_mode else (kernel_size // 2)), bn_eps=bn_eps, activation=activation, data_format=data_format, name="conv2") if self.use_se: self.se = SEBlock( channels=mid_channels, reduction=(exp_factor * se_factor), mid_activation=activation, data_format=data_format, name="se") self.conv3 = conv1x1_block( in_channels=mid_channels, out_channels=out_channels, bn_eps=bn_eps, activation=None, data_format=data_format, name="conv3") def call(self, x, training=None): if self.residual: identity = x x = self.conv1(x, training=training) if self.tf_mode: x = tf.pad(x, paddings=calc_tf_padding(x, kernel_size=self.kernel_size, strides=self.strides, data_format=self.data_format)) x = self.conv2(x, training=training) if self.use_se: x = self.se(x) x = self.conv3(x, training=training) if self.residual: x = x + identity return x class EffiInitBlock(nn.Layer): """ EfficientNet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. bn_eps : float Small float added to variance in Batch norm. activation : str Name of activation function. tf_mode : bool Whether to use TF-like mode. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, bn_eps, activation, tf_mode, data_format="channels_last", **kwargs): super(EffiInitBlock, self).__init__(**kwargs) self.tf_mode = tf_mode self.data_format = data_format self.conv = conv3x3_block( in_channels=in_channels, out_channels=out_channels, strides=2, padding=(0 if tf_mode else 1), bn_eps=bn_eps, activation=activation, data_format=data_format, name="conv") def call(self, x, training=None): if self.tf_mode: x = tf.pad(x, paddings=calc_tf_padding(x, kernel_size=3, strides=2, data_format=self.data_format)) x = self.conv(x, training=training) return x class EfficientNet(tf.keras.Model): """ EfficientNet(-B0) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- channels : list of list of int Number of output channels for each unit. init_block_channels : int Number of output channels for initial unit. final_block_channels : int Number of output channels for the final block of the feature extractor. kernel_sizes : list of list of int Number of kernel sizes for each unit. strides_per_stage : list int Stride value for the first unit of each stage. expansion_factors : list of list of int Number of expansion factors for each unit. dropout_rate : float, default 0.2 Fraction of the input units to drop. Must be a number between 0 and 1. tf_mode : bool, default False Whether to use TF-like mode. bn_eps : float, default 1e-5 Small float added to variance in Batch norm. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, final_block_channels, kernel_sizes, strides_per_stage, expansion_factors, dropout_rate=0.2, tf_mode=False, bn_eps=1e-5, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(EfficientNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format activation = "swish" self.features = SimpleSequential(name="features") self.features.add(EffiInitBlock( in_channels=in_channels, out_channels=init_block_channels, bn_eps=bn_eps, activation=activation, tf_mode=tf_mode, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): kernel_sizes_per_stage = kernel_sizes[i] expansion_factors_per_stage = expansion_factors[i] stage = SimpleSequential(name="stage{}".format(i + 1)) for j, out_channels in enumerate(channels_per_stage): kernel_size = kernel_sizes_per_stage[j] expansion_factor = expansion_factors_per_stage[j] strides = strides_per_stage[i] if (j == 0) else 1 if i == 0: stage.add(EffiDwsConvUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, bn_eps=bn_eps, activation=activation, tf_mode=tf_mode, data_format=data_format, name="unit{}".format(j + 1))) else: stage.add(EffiInvResUnit( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, strides=strides, exp_factor=expansion_factor, se_factor=4, bn_eps=bn_eps, activation=activation, tf_mode=tf_mode, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(conv1x1_block( in_channels=in_channels, out_channels=final_block_channels, bn_eps=bn_eps, activation=activation, data_format=data_format, name="final_block")) in_channels = final_block_channels self.features.add(nn.GlobalAvgPool2D( data_format=data_format, name="final_pool")) self.output1 = SimpleSequential(name="output1") if dropout_rate > 0.0: self.output1.add(nn.Dropout( rate=dropout_rate, name="dropout")) self.output1.add(nn.Dense( units=classes, input_dim=in_channels, name="fc")) def call(self, x, training=None): x = self.features(x, training=training) x = self.output1(x) return x def get_efficientnet(version, in_size, tf_mode=False, bn_eps=1e-5, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create EfficientNet model with specific parameters. Parameters: ---------- version : str Version of EfficientNet ('b0'...'b7'). in_size : tuple of two ints Spatial size of the expected input image. tf_mode : bool, default False Whether to use TF-like mode. bn_eps : 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if version == "b0": assert (in_size == (224, 224)) depth_factor = 1.0 width_factor = 1.0 dropout_rate = 0.2 elif version == "b1": assert (in_size == (240, 240)) depth_factor = 1.1 width_factor = 1.0 dropout_rate = 0.2 elif version == "b2": assert (in_size == (260, 260)) depth_factor = 1.2 width_factor = 1.1 dropout_rate = 0.3 elif version == "b3": assert (in_size == (300, 300)) depth_factor = 1.4 width_factor = 1.2 dropout_rate = 0.3 elif version == "b4": assert (in_size == (380, 380)) depth_factor = 1.8 width_factor = 1.4 dropout_rate = 0.4 elif version == "b5": assert (in_size == (456, 456)) depth_factor = 2.2 width_factor = 1.6 dropout_rate = 0.4 elif version == "b6": assert (in_size == (528, 528)) depth_factor = 2.6 width_factor = 1.8 dropout_rate = 0.5 elif version == "b7": assert (in_size == (600, 600)) depth_factor = 3.1 width_factor = 2.0 dropout_rate = 0.5 elif version == "b8": assert (in_size == (672, 672)) depth_factor = 3.6 width_factor = 2.2 dropout_rate = 0.5 else: raise ValueError("Unsupported EfficientNet version {}".format(version)) init_block_channels = 32 layers = [1, 2, 2, 3, 3, 4, 1] downsample = [1, 1, 1, 1, 0, 1, 0] channels_per_layers = [16, 24, 40, 80, 112, 192, 320] expansion_factors_per_layers = [1, 6, 6, 6, 6, 6, 6] kernel_sizes_per_layers = [3, 3, 5, 3, 5, 5, 3] strides_per_stage = [1, 2, 2, 2, 1, 2, 1] final_block_channels = 1280 layers = [int(math.ceil(li * depth_factor)) for li in layers] channels_per_layers = [round_channels(ci * width_factor) for ci in channels_per_layers] from functools import reduce channels = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]], zip(channels_per_layers, layers, downsample), []) kernel_sizes = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]], zip(kernel_sizes_per_layers, layers, downsample), []) expansion_factors = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]], zip(expansion_factors_per_layers, layers, downsample), []) strides_per_stage = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]], zip(strides_per_stage, layers, downsample), []) strides_per_stage = [si[0] for si in strides_per_stage] init_block_channels = round_channels(init_block_channels * width_factor) if width_factor > 1.0: assert (int(final_block_channels * width_factor) == round_channels(final_block_channels * width_factor)) final_block_channels = round_channels(final_block_channels * width_factor) net = EfficientNet( channels=channels, init_block_channels=init_block_channels, final_block_channels=final_block_channels, kernel_sizes=kernel_sizes, strides_per_stage=strides_per_stage, expansion_factors=expansion_factors, dropout_rate=dropout_rate, tf_mode=tf_mode, bn_eps=bn_eps, 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def efficientnet_b0(in_size=(224, 224), **kwargs): """ EfficientNet-B0 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (224, 224) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b0", in_size=in_size, model_name="efficientnet_b0", **kwargs) def efficientnet_b1(in_size=(240, 240), **kwargs): """ EfficientNet-B1 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (240, 240) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b1", in_size=in_size, model_name="efficientnet_b1", **kwargs) def efficientnet_b2(in_size=(260, 260), **kwargs): """ EfficientNet-B2 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (260, 260) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b2", in_size=in_size, model_name="efficientnet_b2", **kwargs) def efficientnet_b3(in_size=(300, 300), **kwargs): """ EfficientNet-B3 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (300, 300) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b3", in_size=in_size, model_name="efficientnet_b3", **kwargs) def efficientnet_b4(in_size=(380, 380), **kwargs): """ EfficientNet-B4 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (380, 380) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b4", in_size=in_size, model_name="efficientnet_b4", **kwargs) def efficientnet_b5(in_size=(456, 456), **kwargs): """ EfficientNet-B5 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (456, 456) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b5", in_size=in_size, model_name="efficientnet_b5", **kwargs) def efficientnet_b6(in_size=(528, 528), **kwargs): """ EfficientNet-B6 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (528, 528) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b6", in_size=in_size, model_name="efficientnet_b6", **kwargs) def efficientnet_b7(in_size=(600, 600), **kwargs): """ EfficientNet-B7 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (600, 600) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b7", in_size=in_size, model_name="efficientnet_b7", **kwargs) def efficientnet_b8(in_size=(672, 672), **kwargs): """ EfficientNet-B8 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (672, 672) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b8", in_size=in_size, model_name="efficientnet_b8", **kwargs) def efficientnet_b0b(in_size=(224, 224), **kwargs): """ EfficientNet-B0-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (224, 224) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b0", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b0b", **kwargs) def efficientnet_b1b(in_size=(240, 240), **kwargs): """ EfficientNet-B1-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (240, 240) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b1", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b1b", **kwargs) def efficientnet_b2b(in_size=(260, 260), **kwargs): """ EfficientNet-B2-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (260, 260) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b2", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b2b", **kwargs) def efficientnet_b3b(in_size=(300, 300), **kwargs): """ EfficientNet-B3-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (300, 300) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b3", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b3b", **kwargs) def efficientnet_b4b(in_size=(380, 380), **kwargs): """ EfficientNet-B4-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (380, 380) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b4", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b4b", **kwargs) def efficientnet_b5b(in_size=(456, 456), **kwargs): """ EfficientNet-B5-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (456, 456) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b5", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b5b", **kwargs) def efficientnet_b6b(in_size=(528, 528), **kwargs): """ EfficientNet-B6-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (528, 528) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b6", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b6b", **kwargs) def efficientnet_b7b(in_size=(600, 600), **kwargs): """ EfficientNet-B7-b (like TF-implementation) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (600, 600) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b7", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b7b", **kwargs) def efficientnet_b0c(in_size=(224, 224), **kwargs): """ EfficientNet-B0-c (like TF-implementation, trained with AdvProp) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (224, 224) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b0", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b0c", **kwargs) def efficientnet_b1c(in_size=(240, 240), **kwargs): """ EfficientNet-B1-c (like TF-implementation, trained with AdvProp) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (240, 240) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b1", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b1c", **kwargs) def efficientnet_b2c(in_size=(260, 260), **kwargs): """ EfficientNet-B2-c (like TF-implementation, trained with AdvProp) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (260, 260) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b2", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b2c", **kwargs) def efficientnet_b3c(in_size=(300, 300), **kwargs): """ EfficientNet-B3-c (like TF-implementation, trained with AdvProp) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (300, 300) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b3", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b3c", **kwargs) def efficientnet_b4c(in_size=(380, 380), **kwargs): """ EfficientNet-B4-c (like TF-implementation, trained with AdvProp) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (380, 380) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b4", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b4c", **kwargs) def efficientnet_b5c(in_size=(456, 456), **kwargs): """ EfficientNet-B5-c (like TF-implementation, trained with AdvProp) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (456, 456) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b5", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b5c", **kwargs) def efficientnet_b6c(in_size=(528, 528), **kwargs): """ EfficientNet-B6-c (like TF-implementation, trained with AdvProp) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (528, 528) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b6", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b6c", **kwargs) def efficientnet_b7c(in_size=(600, 600), **kwargs): """ EfficientNet-B7-c (like TF-implementation, trained with AdvProp) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (600, 600) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b7", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b7c", **kwargs) def efficientnet_b8c(in_size=(672, 672), **kwargs): """ EfficientNet-B8-c (like TF-implementation, trained with AdvProp) model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (672, 672) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet(version="b8", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_b8c", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ efficientnet_b0, efficientnet_b1, efficientnet_b2, efficientnet_b3, efficientnet_b4, efficientnet_b5, efficientnet_b6, efficientnet_b7, efficientnet_b8, efficientnet_b0b, efficientnet_b1b, efficientnet_b2b, efficientnet_b3b, efficientnet_b4b, efficientnet_b5b, efficientnet_b6b, efficientnet_b7b, efficientnet_b0c, efficientnet_b1c, efficientnet_b2c, efficientnet_b3c, efficientnet_b4c, efficientnet_b5c, efficientnet_b6c, efficientnet_b7c, efficientnet_b8c, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != efficientnet_b0 or weight_count == 5288548) assert (model != efficientnet_b1 or weight_count == 7794184) assert (model != efficientnet_b2 or weight_count == 9109994) assert (model != efficientnet_b3 or weight_count == 12233232) assert (model != efficientnet_b4 or weight_count == 19341616) assert (model != efficientnet_b5 or weight_count == 30389784) assert (model != efficientnet_b6 or weight_count == 43040704) assert (model != efficientnet_b7 or weight_count == 66347960) assert (model != efficientnet_b8 or weight_count == 87413142) assert (model != efficientnet_b0b or weight_count == 5288548) assert (model != efficientnet_b1b or weight_count == 7794184) assert (model != efficientnet_b2b or weight_count == 9109994) assert (model != efficientnet_b3b or weight_count == 12233232) assert (model != efficientnet_b4b or weight_count == 19341616) assert (model != efficientnet_b5b or weight_count == 30389784) assert (model != efficientnet_b6b or weight_count == 43040704) assert (model != efficientnet_b7b or weight_count == 66347960) if __name__ == "__main__": _test()
40,223
36.804511
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/pnasnet.py
""" PNASNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'Progressive Neural Architecture Search,' https://arxiv.org/abs/1712.00559. """ __all__ = ['PNASNet', 'pnasnet5large'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import MaxPool2d, conv1x1, SimpleSequential, flatten, is_channels_first, get_channel_axis from .nasnet import nasnet_dual_path_sequential, nasnet_batch_norm, NasConv, NasDwsConv, NasPathBlock, NASNetInitBlock class PnasMaxPoolBlock(nn.Layer): """ PNASNet specific Max pooling layer with extra padding. Parameters: ---------- strides : int or tuple/list of 2 int, default 2 Strides of the convolution. extra_padding : bool, default False Whether to use extra padding. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, strides=2, extra_padding=False, data_format="channels_last", **kwargs): super(PnasMaxPoolBlock, self).__init__(**kwargs) self.extra_padding = extra_padding self.data_format = data_format self.pool = MaxPool2d( pool_size=3, strides=strides, padding=1, data_format=data_format, name="pool") if self.extra_padding: self.pad = nn.ZeroPadding2D( padding=((1, 0), (1, 0)), data_format=data_format) def call(self, x, training=None): if self.extra_padding: x = self.pad(x) x = self.pool(x) if self.extra_padding: if is_channels_first(self.data_format): x = x[:, :, 1:, 1:] else: x = x[:, 1:, 1:, :] return x def pnas_conv1x1(in_channels, out_channels, strides=1, data_format="channels_last", **kwargs): """ 1x1 version of the PNASNet 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ return NasConv( in_channels=in_channels, out_channels=out_channels, kernel_size=1, strides=strides, padding=0, groups=1, data_format=data_format, **kwargs) class DwsBranch(nn.Layer): """ PNASNet 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. extra_padding : bool, default False Whether to use extra padding. stem : bool, default False Whether to use squeeze reduction if False. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, strides, extra_padding=False, stem=False, data_format="channels_last", **kwargs): super(DwsBranch, self).__init__(**kwargs) assert (not stem) or (not extra_padding) mid_channels = out_channels if stem else in_channels padding = kernel_size // 2 self.conv1 = NasDwsConv( in_channels=in_channels, out_channels=mid_channels, kernel_size=kernel_size, strides=strides, padding=padding, extra_padding=extra_padding, data_format=data_format, name="conv1") self.conv2 = NasDwsConv( in_channels=mid_channels, out_channels=out_channels, kernel_size=kernel_size, strides=1, padding=padding, data_format=data_format, name="conv2") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) return x def dws_branch_k3(in_channels, out_channels, strides=2, extra_padding=False, stem=False, data_format="channels_last", **kwargs): """ 3x3 version of the PNASNet specific depthwise separable convolution branch. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. strides : int or tuple/list of 2 int, default 2 Strides of the convolution. extra_padding : bool, default False Whether to use extra padding. stem : bool, default False Whether to use squeeze reduction if False. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ return DwsBranch( in_channels=in_channels, out_channels=out_channels, kernel_size=3, strides=strides, extra_padding=extra_padding, stem=stem, data_format=data_format, **kwargs) def dws_branch_k5(in_channels, out_channels, strides=2, extra_padding=False, stem=False, data_format="channels_last", **kwargs): """ 5x5 version of the PNASNet specific depthwise separable convolution branch. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. strides : int or tuple/list of 2 int, default 2 Strides of the convolution. extra_padding : bool, default False Whether to use extra padding. stem : bool, default False Whether to use squeeze reduction if False. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ return DwsBranch( in_channels=in_channels, out_channels=out_channels, kernel_size=5, strides=strides, extra_padding=extra_padding, stem=stem, data_format=data_format, **kwargs) def dws_branch_k7(in_channels, out_channels, strides=2, extra_padding=False, data_format="channels_last", **kwargs): """ 7x7 version of the PNASNet specific depthwise separable convolution branch. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. strides : int or tuple/list of 2 int, default 2 Strides of the convolution. extra_padding : bool, default False Whether to use extra padding. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ return DwsBranch( in_channels=in_channels, out_channels=out_channels, kernel_size=7, strides=strides, extra_padding=extra_padding, stem=False, data_format=data_format, **kwargs) class PnasMaxPathBlock(nn.Layer): """ PNASNet specific `max path` auxiliary block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(PnasMaxPathBlock, self).__init__(**kwargs) self.maxpool = PnasMaxPoolBlock( data_format=data_format, name="maxpool") self.conv = conv1x1( in_channels=in_channels, out_channels=out_channels, data_format=data_format, name="conv") self.bn = nasnet_batch_norm( channels=out_channels, data_format=data_format, name="bn") def call(self, x, training=None): x = self.maxpool(x) x = self.conv(x) x = self.bn(x, training=training) return x class PnasBaseUnit(nn.Layer): """ PNASNet base unit. Parameters: ---------- data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, data_format="channels_last", **kwargs): super(PnasBaseUnit, self).__init__(**kwargs) self.data_format = data_format def cell_forward(self, x, x_prev, training=None): assert (hasattr(self, 'comb0_left')) x_left = x_prev x_right = x x0 = self.comb0_left(x_left, training=training) + self.comb0_right(x_left, training=training) x1 = self.comb1_left(x_right, training=training) + self.comb1_right(x_right, training=training) x2 = self.comb2_left(x_right, training=training) + self.comb2_right(x_right, training=training) x3 = self.comb3_left(x2, training=training) + self.comb3_right(x_right, training=training) x4 = self.comb4_left(x_left, training=training) + (self.comb4_right(x_right, training=training) if self.comb4_right else x_right) x_out = tf.concat([x0, x1, x2, x3, x4], axis=get_channel_axis(self.data_format)) return x_out class Stem1Unit(PnasBaseUnit): """ PNASNet Stem1 unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(Stem1Unit, self).__init__(**kwargs) mid_channels = out_channels // 5 self.conv_1x1 = pnas_conv1x1( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv_1x1") self.comb0_left = dws_branch_k5( in_channels=in_channels, out_channels=mid_channels, stem=True, data_format=data_format, name="comb0_left") self.comb0_right = PnasMaxPathBlock( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="comb0_right") self.comb1_left = dws_branch_k7( in_channels=mid_channels, out_channels=mid_channels, data_format=data_format, name="comb1_left") self.comb1_right = PnasMaxPoolBlock( data_format=data_format, name="comb1_right") self.comb2_left = dws_branch_k5( in_channels=mid_channels, out_channels=mid_channels, data_format=data_format, name="comb2_left") self.comb2_right = dws_branch_k3( in_channels=mid_channels, out_channels=mid_channels, data_format=data_format, name="comb2_right") self.comb3_left = dws_branch_k3( in_channels=mid_channels, out_channels=mid_channels, strides=1, data_format=data_format, name="comb3_left") self.comb3_right = PnasMaxPoolBlock( data_format=data_format, name="comb3_right") self.comb4_left = dws_branch_k3( in_channels=in_channels, out_channels=mid_channels, stem=True, data_format=data_format, name="comb4_left") self.comb4_right = pnas_conv1x1( in_channels=mid_channels, out_channels=mid_channels, strides=2, data_format=data_format, name="comb4_right") def call(self, x, training=None): x_prev = x x = self.conv_1x1(x, training=training) x_out = self.cell_forward(x, x_prev, training=training) return x_out class PnasUnit(PnasBaseUnit): """ PNASNet ordinary 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. reduction : bool, default False Whether to use reduction. extra_padding : bool, default False Whether to use extra padding. match_prev_layer_dimensions : bool, default False Whether to match previous layer dimensions. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, prev_in_channels, out_channels, reduction=False, extra_padding=False, match_prev_layer_dimensions=False, data_format="channels_last", **kwargs): super(PnasUnit, self).__init__(**kwargs) mid_channels = out_channels // 5 stride = 2 if reduction else 1 if match_prev_layer_dimensions: self.conv_prev_1x1 = NasPathBlock( in_channels=prev_in_channels, out_channels=mid_channels, data_format=data_format, name="conv_prev_1x1") else: self.conv_prev_1x1 = pnas_conv1x1( in_channels=prev_in_channels, out_channels=mid_channels, data_format=data_format, name="conv_prev_1x1") self.conv_1x1 = pnas_conv1x1( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv_1x1") self.comb0_left = dws_branch_k5( in_channels=mid_channels, out_channels=mid_channels, strides=stride, extra_padding=extra_padding, data_format=data_format, name="comb0_left") self.comb0_right = PnasMaxPoolBlock( strides=stride, extra_padding=extra_padding, data_format=data_format, name="comb0_right") self.comb1_left = dws_branch_k7( in_channels=mid_channels, out_channels=mid_channels, strides=stride, extra_padding=extra_padding, data_format=data_format, name="comb1_left") self.comb1_right = PnasMaxPoolBlock( strides=stride, extra_padding=extra_padding, data_format=data_format, name="comb1_right") self.comb2_left = dws_branch_k5( in_channels=mid_channels, out_channels=mid_channels, strides=stride, extra_padding=extra_padding, data_format=data_format, name="comb2_left") self.comb2_right = dws_branch_k3( in_channels=mid_channels, out_channels=mid_channels, strides=stride, extra_padding=extra_padding, data_format=data_format, name="comb2_right") self.comb3_left = dws_branch_k3( in_channels=mid_channels, out_channels=mid_channels, strides=1, data_format=data_format, name="comb3_left") self.comb3_right = PnasMaxPoolBlock( strides=stride, extra_padding=extra_padding, data_format=data_format, name="comb3_right") self.comb4_left = dws_branch_k3( in_channels=mid_channels, out_channels=mid_channels, strides=stride, extra_padding=extra_padding, data_format=data_format, name="comb4_left") if reduction: self.comb4_right = pnas_conv1x1( in_channels=mid_channels, out_channels=mid_channels, strides=stride, data_format=data_format, name="comb4_right") else: self.comb4_right = None def call(self, x, x_prev, training=None): x_prev = self.conv_prev_1x1(x_prev, training=training) x = self.conv_1x1(x, training=training) x_out = self.cell_forward(x, x_prev, training=training) return x_out class PNASNet(tf.keras.Model): """ PNASNet model from 'Progressive Neural Architecture Search,' https://arxiv.org/abs/1712.00559. 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. stem1_blocks_channels : list of 2 int Number of output channels for the Stem1 unit. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, stem1_blocks_channels, in_channels=3, in_size=(331, 331), classes=1000, data_format="channels_last", **kwargs): super(PNASNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = nasnet_dual_path_sequential( return_two=False, first_ordinals=2, last_ordinals=2, name="features") self.features.add(NASNetInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels self.features.add(Stem1Unit( in_channels=in_channels, out_channels=stem1_blocks_channels, data_format=data_format, name="stem1_unit")) prev_in_channels = in_channels in_channels = stem1_blocks_channels for i, channels_per_stage in enumerate(channels): stage = nasnet_dual_path_sequential( name="stage{}".format(i + 1)) for j, out_channels in enumerate(channels_per_stage): reduction = (j == 0) extra_padding = (j == 0) and (i not in [0, 2]) match_prev_layer_dimensions = (j == 1) or ((j == 0) and (i == 0)) stage.add(PnasUnit( in_channels=in_channels, prev_in_channels=prev_in_channels, out_channels=out_channels, reduction=reduction, extra_padding=extra_padding, match_prev_layer_dimensions=match_prev_layer_dimensions, data_format=data_format, name="unit{}".format(j + 1))) prev_in_channels = in_channels in_channels = out_channels self.features.add(stage) self.features.add(nn.ReLU(name="activ")) self.features.add(nn.AveragePooling2D( pool_size=11, strides=1, data_format=data_format, name="final_pool")) self.output1 = SimpleSequential(name="output1") self.output1.add(nn.Dropout( rate=0.5, name="dropout")) self.output1.add(nn.Dense( units=classes, input_dim=in_channels, name="fc")) def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_pnasnet(model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create PNASNet 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ repeat = 4 init_block_channels = 96 stem_blocks_channels = [270, 540] norm_channels = [1080, 2160, 4320] channels = [[ci] * repeat for ci in norm_channels] stem1_blocks_channels = stem_blocks_channels[0] channels[0] = [stem_blocks_channels[1]] + channels[0] net = PNASNet( channels=channels, init_block_channels=init_block_channels, stem1_blocks_channels=stem1_blocks_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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def pnasnet5large(**kwargs): """ PNASNet-5-Large model from 'Progressive Neural Architecture Search,' https://arxiv.org/abs/1712.00559. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pnasnet(model_name="pnasnet5large", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ pnasnet5large, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 331, 331) if is_channels_first(data_format) else (batch, 331, 331, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != pnasnet5large or weight_count == 86057668) if __name__ == "__main__": _test()
23,512
31.253772
118
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/efficientnetedge.py
""" EfficientNet-Edge for ImageNet-1K, implemented in TensorFlow. Original paper: 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. """ __all__ = ['EfficientNetEdge', 'efficientnet_edge_small_b', 'efficientnet_edge_medium_b', 'efficientnet_edge_large_b'] import os import math import tensorflow as tf import tensorflow.keras.layers as nn from .common import round_channels, conv1x1_block, conv3x3_block, SEBlock, SimpleSequential, is_channels_first from .efficientnet import EffiInvResUnit, EffiInitBlock class EffiEdgeResUnit(nn.Layer): """ EfficientNet-Edge edge 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 second convolution layer. exp_factor : int Factor for expansion of channels. se_factor : int SE reduction factor for each unit. mid_from_in : bool Whether to use input channel count for middle channel count calculation. use_skip : bool Whether to use skip connection. bn_eps : float Small float added to variance in Batch norm. activation : str Name of activation function. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, exp_factor, se_factor, mid_from_in, use_skip, bn_eps, activation, data_format="channels_last", **kwargs): super(EffiEdgeResUnit, self).__init__(**kwargs) self.residual = (in_channels == out_channels) and (strides == 1) and use_skip self.use_se = se_factor > 0 mid_channels = in_channels * exp_factor if mid_from_in else out_channels * exp_factor self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels, bn_eps=bn_eps, activation=activation, data_format=data_format, name="conv1") if self.use_se: self.se = SEBlock( channels=mid_channels, reduction=(exp_factor * se_factor), mid_activation=activation, data_format=data_format, name="se") self.conv2 = conv1x1_block( in_channels=mid_channels, out_channels=out_channels, strides=strides, bn_eps=bn_eps, activation=None, data_format=data_format, name="conv2") def call(self, x, training=None): if self.residual: identity = x x = self.conv1(x, training=training) if self.use_se: x = self.se(x) x = self.conv2(x, training=training) if self.residual: x = x + identity return x class EfficientNetEdge(tf.keras.Model): """ EfficientNet-Edge model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- channels : list of list of int Number of output channels for each unit. init_block_channels : int Number of output channels for initial unit. final_block_channels : int Number of output channels for the final block of the feature extractor. kernel_sizes : list of list of int Number of kernel sizes for each unit. strides_per_stage : list int Stride value for the first unit of each stage. expansion_factors : list of list of int Number of expansion factors for each unit. dropout_rate : float, default 0.2 Fraction of the input units to drop. Must be a number between 0 and 1. tf_mode : bool, default False Whether to use TF-like mode. bn_eps : float, default 1e-5 Small float added to variance in Batch norm. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, final_block_channels, kernel_sizes, strides_per_stage, expansion_factors, dropout_rate=0.2, tf_mode=False, bn_eps=1e-5, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(EfficientNetEdge, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format activation = "relu" self.features = SimpleSequential(name="features") self.features.add(EffiInitBlock( in_channels=in_channels, out_channels=init_block_channels, bn_eps=bn_eps, activation=activation, tf_mode=tf_mode, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): kernel_sizes_per_stage = kernel_sizes[i] expansion_factors_per_stage = expansion_factors[i] mid_from_in = (i != 0) use_skip = (i != 0) stage = SimpleSequential(name="stage{}".format(i + 1)) for j, out_channels in enumerate(channels_per_stage): kernel_size = kernel_sizes_per_stage[j] expansion_factor = expansion_factors_per_stage[j] strides = strides_per_stage[i] if (j == 0) else 1 if i < 3: stage.add(EffiEdgeResUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, exp_factor=expansion_factor, se_factor=0, mid_from_in=mid_from_in, use_skip=use_skip, bn_eps=bn_eps, activation=activation, data_format=data_format, name="unit{}".format(j + 1))) else: stage.add(EffiInvResUnit( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, strides=strides, exp_factor=expansion_factor, se_factor=0, bn_eps=bn_eps, activation=activation, tf_mode=tf_mode, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(conv1x1_block( in_channels=in_channels, out_channels=final_block_channels, bn_eps=bn_eps, activation=activation, data_format=data_format, name="final_block")) in_channels = final_block_channels self.features.add(nn.GlobalAvgPool2D( data_format=data_format, name="final_pool")) self.output1 = SimpleSequential(name="output1") if dropout_rate > 0.0: self.output1.add(nn.Dropout( rate=dropout_rate, name="dropout")) self.output1.add(nn.Dense( units=classes, input_dim=in_channels, name="fc")) def call(self, x, training=None): x = self.features(x, training=training) x = self.output1(x) return x def get_efficientnet_edge(version, in_size, tf_mode=False, bn_eps=1e-5, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create EfficientNet-Edge model with specific parameters. Parameters: ---------- version : str Version of EfficientNet ('small', 'medium', 'large'). in_size : tuple of two ints Spatial size of the expected input image. tf_mode : bool, default False Whether to use TF-like mode. bn_eps : 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ dropout_rate = 0.0 if version == "small": assert (in_size == (224, 224)) depth_factor = 1.0 width_factor = 1.0 # dropout_rate = 0.2 elif version == "medium": assert (in_size == (240, 240)) depth_factor = 1.1 width_factor = 1.0 # dropout_rate = 0.2 elif version == "large": assert (in_size == (300, 300)) depth_factor = 1.4 width_factor = 1.2 # dropout_rate = 0.3 else: raise ValueError("Unsupported EfficientNet-Edge version {}".format(version)) init_block_channels = 32 layers = [1, 2, 4, 5, 4, 2] downsample = [1, 1, 1, 1, 0, 1] channels_per_layers = [24, 32, 48, 96, 144, 192] expansion_factors_per_layers = [4, 8, 8, 8, 8, 8] kernel_sizes_per_layers = [3, 3, 3, 5, 5, 5] strides_per_stage = [1, 2, 2, 2, 1, 2] final_block_channels = 1280 layers = [int(math.ceil(li * depth_factor)) for li in layers] channels_per_layers = [round_channels(ci * width_factor) for ci in channels_per_layers] from functools import reduce channels = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]], zip(channels_per_layers, layers, downsample), []) kernel_sizes = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]], zip(kernel_sizes_per_layers, layers, downsample), []) expansion_factors = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]], zip(expansion_factors_per_layers, layers, downsample), []) strides_per_stage = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]], zip(strides_per_stage, layers, downsample), []) strides_per_stage = [si[0] for si in strides_per_stage] init_block_channels = round_channels(init_block_channels * width_factor) if width_factor > 1.0: assert (int(final_block_channels * width_factor) == round_channels(final_block_channels * width_factor)) final_block_channels = round_channels(final_block_channels * width_factor) net = EfficientNetEdge( channels=channels, init_block_channels=init_block_channels, final_block_channels=final_block_channels, kernel_sizes=kernel_sizes, strides_per_stage=strides_per_stage, expansion_factors=expansion_factors, dropout_rate=dropout_rate, tf_mode=tf_mode, bn_eps=bn_eps, 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def efficientnet_edge_small_b(in_size=(224, 224), **kwargs): """ EfficientNet-Edge-Small-b model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (224, 224) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet_edge(version="small", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_edge_small_b", **kwargs) def efficientnet_edge_medium_b(in_size=(240, 240), **kwargs): """ EfficientNet-Edge-Medium-b model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (240, 240) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet_edge(version="medium", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_edge_medium_b", **kwargs) def efficientnet_edge_large_b(in_size=(300, 300), **kwargs): """ EfficientNet-Edge-Large-b model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (300, 300) Spatial size of the expected input image. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_efficientnet_edge(version="large", in_size=in_size, tf_mode=True, bn_eps=1e-3, model_name="efficientnet_edge_large_b", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ efficientnet_edge_small_b, efficientnet_edge_medium_b, efficientnet_edge_large_b, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != efficientnet_edge_small_b or weight_count == 5438392) assert (model != efficientnet_edge_medium_b or weight_count == 6899496) assert (model != efficientnet_edge_large_b or weight_count == 10589712) if __name__ == "__main__": _test()
15,845
37
118
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/ibnresnext.py
""" IBN-ResNeXt for ImageNet-1K, implemented in TensorFlow. Original paper: 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431. """ __all__ = ['IBNResNeXt', 'ibn_resnext50_32x4d', 'ibn_resnext101_32x4d', 'ibn_resnext101_64x4d'] import os import math import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1_block, conv3x3_block, SimpleSequential, flatten, is_channels_first from .resnet import ResInitBlock from .ibnresnet import ibn_conv1x1_block class IBNResNeXtBottleneck(nn.Layer): """ IBN-ResNeXt bottleneck block for residual path in IBN-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. conv1_ibn : bool Whether to use IBN normalization in the first convolution layer of the block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, cardinality, bottleneck_width, conv1_ibn, data_format="channels_last", **kwargs): super(IBNResNeXtBottleneck, self).__init__(**kwargs) mid_channels = out_channels // 4 D = int(math.floor(mid_channels * (bottleneck_width / 64.0))) group_width = cardinality * D self.conv1 = ibn_conv1x1_block( in_channels=in_channels, out_channels=group_width, use_ibn=conv1_ibn, data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=group_width, out_channels=group_width, strides=strides, groups=cardinality, data_format=data_format, name="conv2") self.conv3 = conv1x1_block( in_channels=group_width, out_channels=out_channels, activation=None, data_format=data_format, name="conv3") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.conv3(x, training=training) return x class IBNResNeXtUnit(nn.Layer): """ IBN-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. conv1_ibn : bool Whether to use IBN normalization in the first convolution layer of the block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, cardinality, bottleneck_width, conv1_ibn, data_format="channels_last", **kwargs): super(IBNResNeXtUnit, self).__init__(**kwargs) self.resize_identity = (in_channels != out_channels) or (strides != 1) self.body = IBNResNeXtBottleneck( in_channels=in_channels, out_channels=out_channels, strides=strides, cardinality=cardinality, bottleneck_width=bottleneck_width, conv1_ibn=conv1_ibn, data_format=data_format, name="body") if self.resize_identity: self.identity_conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, strides=strides, activation=None, data_format=data_format, name="identity_conv") self.activ = nn.ReLU() def call(self, x, training=None): if self.resize_identity: identity = self.identity_conv(x, training=training) else: identity = x x = self.body(x, training=training) x = x + identity x = self.activ(x) return x class IBNResNeXt(tf.keras.Model): """ IBN-ResNeXt 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. cardinality: int Number of groups. bottleneck_width: int Width of bottleneck 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, cardinality, bottleneck_width, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(IBNResNeXt, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(ResInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) 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(IBNResNeXtUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, cardinality=cardinality, bottleneck_width=bottleneck_width, conv1_ibn=conv1_ibn, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_ibnresnext(blocks, cardinality, bottleneck_width, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create IBN-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if blocks == 50: layers = [3, 4, 6, 3] elif blocks == 101: layers = [3, 4, 23, 3] else: raise ValueError("Unsupported IBN-ResNeXt 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 = IBNResNeXt( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def ibn_resnext50_32x4d(**kwargs): """ IBN-ResNeXt-50 (32x4d) 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_ibnresnext(blocks=50, cardinality=32, bottleneck_width=4, model_name="ibn_resnext50_32x4d", **kwargs) def ibn_resnext101_32x4d(**kwargs): """ IBN-ResNeXt-101 (32x4d) 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_ibnresnext(blocks=101, cardinality=32, bottleneck_width=4, model_name="ibn_resnext101_32x4d", **kwargs) def ibn_resnext101_64x4d(**kwargs): """ IBN-ResNeXt-101 (64x4d) 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_ibnresnext(blocks=101, cardinality=64, bottleneck_width=4, model_name="ibn_resnext101_64x4d", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ ibn_resnext50_32x4d, ibn_resnext101_32x4d, ibn_resnext101_64x4d, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != ibn_resnext50_32x4d or weight_count == 25028904) assert (model != ibn_resnext101_32x4d or weight_count == 44177704) assert (model != ibn_resnext101_64x4d or weight_count == 83455272) if __name__ == "__main__": _test()
12,035
32.620112
118
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/squeezenext.py
""" SqueezeNext for ImageNet-1K, implemented in TensorFlow. Original paper: 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615. """ __all__ = ['SqueezeNext', 'sqnxt23_w1', 'sqnxt23_w3d2', 'sqnxt23_w2', 'sqnxt23v5_w1', 'sqnxt23v5_w3d2', 'sqnxt23v5_w2'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import ConvBlock, conv1x1_block, conv7x7_block, MaxPool2d, SimpleSequential, flatten class SqnxtUnit(nn.Layer): """ SqueezeNext 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, data_format="channels_last", **kwargs): super(SqnxtUnit, self).__init__(**kwargs) if strides == 2: reduction_den = 1 self.resize_identity = True elif in_channels > out_channels: reduction_den = 4 self.resize_identity = True else: reduction_den = 2 self.resize_identity = False self.conv1 = conv1x1_block( in_channels=in_channels, out_channels=(in_channels // reduction_den), strides=strides, use_bias=True, data_format=data_format, name="conv1") self.conv2 = conv1x1_block( in_channels=(in_channels // reduction_den), out_channels=(in_channels // (2 * reduction_den)), use_bias=True, data_format=data_format, name="conv2") self.conv3 = ConvBlock( in_channels=(in_channels // (2 * reduction_den)), out_channels=(in_channels // reduction_den), kernel_size=(1, 3), strides=1, padding=(0, 1), use_bias=True, data_format=data_format, name="conv3") self.conv4 = ConvBlock( in_channels=(in_channels // reduction_den), out_channels=(in_channels // reduction_den), kernel_size=(3, 1), strides=1, padding=(1, 0), use_bias=True, data_format=data_format, name="conv4") self.conv5 = conv1x1_block( in_channels=(in_channels // reduction_den), out_channels=out_channels, use_bias=True, data_format=data_format, name="conv5") if self.resize_identity: self.identity_conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, strides=strides, use_bias=True, data_format=data_format, name="identity_conv") self.activ = nn.ReLU() def call(self, x, training=None): if self.resize_identity: identity = self.identity_conv(x, training=training) else: identity = x x = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.conv3(x, training=training) x = self.conv4(x, training=training) x = self.conv5(x, training=training) x = x + identity x = self.activ(x) return x class SqnxtInitBlock(nn.Layer): """ SqueezeNext specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(SqnxtInitBlock, self).__init__(**kwargs) self.conv = conv7x7_block( in_channels=in_channels, out_channels=out_channels, strides=2, padding=1, use_bias=True, data_format=data_format, name="conv") self.pool = MaxPool2d( pool_size=3, strides=2, ceil_mode=True, data_format=data_format, name="pool") def call(self, x, training=None): x = self.conv(x, training=training) x = self.pool(x) return x class SqueezeNext(tf.keras.Model): """ SqueezeNext model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615. 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, final_block_channels, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(SqueezeNext, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(SqnxtInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(SqnxtUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(conv1x1_block( in_channels=in_channels, out_channels=final_block_channels, use_bias=True, data_format=data_format, name="final_block")) in_channels = final_block_channels self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_squeezenext(version, width_scale, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create SqueezeNext model with specific parameters. Parameters: ---------- version : str Version of SqueezeNet ('23' or '23v5'). 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ init_block_channels = 64 final_block_channels = 128 channels_per_layers = [32, 64, 128, 256] if version == '23': layers = [6, 6, 8, 1] elif version == '23v5': layers = [2, 4, 14, 1] else: raise ValueError("Unsupported SqueezeNet version {}".format(version)) channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)] if width_scale != 1: channels = [[int(cij * width_scale) for cij in ci] for ci in channels] init_block_channels = int(init_block_channels * width_scale) final_block_channels = int(final_block_channels * width_scale) net = SqueezeNext( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def sqnxt23_w1(**kwargs): """ 1.0-SqNxt-23 model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_squeezenext(version="23", width_scale=1.0, model_name="sqnxt23_w1", **kwargs) def sqnxt23_w3d2(**kwargs): """ 1.5-SqNxt-23 model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_squeezenext(version="23", width_scale=1.5, model_name="sqnxt23_w3d2", **kwargs) def sqnxt23_w2(**kwargs): """ 2.0-SqNxt-23 model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_squeezenext(version="23", width_scale=2.0, model_name="sqnxt23_w2", **kwargs) def sqnxt23v5_w1(**kwargs): """ 1.0-SqNxt-23v5 model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_squeezenext(version="23v5", width_scale=1.0, model_name="sqnxt23v5_w1", **kwargs) def sqnxt23v5_w3d2(**kwargs): """ 1.5-SqNxt-23v5 model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_squeezenext(version="23v5", width_scale=1.5, model_name="sqnxt23v5_w3d2", **kwargs) def sqnxt23v5_w2(**kwargs): """ 2.0-SqNxt-23v5 model from 'SqueezeNext: Hardware-Aware Neural Network Design,' https://arxiv.org/abs/1803.10615. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_squeezenext(version="23v5", width_scale=2.0, model_name="sqnxt23v5_w2", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K pretrained = False models = [ sqnxt23_w1, sqnxt23_w3d2, sqnxt23_w2, sqnxt23v5_w1, sqnxt23v5_w3d2, sqnxt23v5_w2, ] for model in models: net = model(pretrained=pretrained) batch = 14 x = tf.random.normal((batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != sqnxt23_w1 or weight_count == 724056) assert (model != sqnxt23_w3d2 or weight_count == 1511824) assert (model != sqnxt23_w2 or weight_count == 2583752) assert (model != sqnxt23v5_w1 or weight_count == 921816) assert (model != sqnxt23v5_w3d2 or weight_count == 1953616) assert (model != sqnxt23v5_w2 or weight_count == 3366344) if __name__ == "__main__": _test()
13,713
32.367397
119
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/grmiposelite_coco.py
""" GRMIPose (Google PoseNet) for COCO Keypoint, implemented in TensorFlow (Lite). Original paper: 'Towards Accurate Multi-person Pose Estimation in the Wild,' https://arxiv.org/abs/1701.01779. """ __all__ = ['GRMIPoseLite', 'grmiposelite_mobilenet_w1_coco'] import math import numpy as np import tensorflow as tf class GRMIPoseLite(tf.keras.Model): """ GRMIPose (Google PoseNet) model from 'Towards Accurate Multi-person Pose Estimation in the Wild,' https://arxiv.org/abs/1701.01779. Parameters: ---------- interpreter : obj Instance of the TFLite model interpreter. in_channels : int, default 3 Number of input channels. in_size : tuple of two ints, default (257, 257) Spatial size of the expected input image. keypoints : int, default 17 Number of keypoints. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, interpreter, in_channels=3, in_size=(257, 257), keypoints=17, data_format="channels_last", **kwargs): super(GRMIPoseLite, self).__init__(**kwargs) assert (in_channels == 3) self.in_size = in_size self.keypoints = keypoints self.data_format = data_format self.interpreter = interpreter self.interpreter.allocate_tensors() input_details = self.interpreter.get_input_details() self.input_tensor_index = input_details[0]["index"] self.in_shape = tuple(input_details[0]["shape"]) assert (self.in_size == self.in_shape[1:3]) self.output_tensor_index_list = [i["index"] for i in self.interpreter.get_output_details()] def call(self, x, training=None): x_np = x.numpy() # import cv2 # cv2.imshow("x_np", x_np[0]) # cv2.waitKey(0) # cv2.destroyAllWindows() assert (x_np.shape == self.in_shape) self.interpreter.set_tensor(self.input_tensor_index, x_np) self.interpreter.invoke() heatmap = self.interpreter.get_tensor(self.output_tensor_index_list[0]) offsets = self.interpreter.get_tensor(self.output_tensor_index_list[1]) pts = np.zeros((self.keypoints, 3), np.float32) oh, ow = heatmap.shape[1:3] fh = self.in_size[0] / (oh - 1) fw = self.in_size[1] / (ow - 1) for k in range(self.keypoints): max_h = heatmap[0, 0, 0, 0] max_i = 0 max_j = 0 for i in range(oh): for j in range(ow): h = heatmap[0, i, j, k] if h > max_h: max_h = h max_i = i max_j = j pts[k, 0] = max_i * fh + offsets[0, max_i, max_j, k] pts[k, 1] = max_j * fw + offsets[0, max_i, max_j, k + self.keypoints] pts[k, 2] = self.sigmoid(max_h) pts1 = pts.copy() for k in range(self.keypoints): pts1[k, 0] = 0.25 * pts[k, 1] pts1[k, 1] = 0.25 * pts[k, 0] y = tf.convert_to_tensor(np.expand_dims(pts1, axis=0)) # import cv2 # canvas = x_np[0] # canvas = cv2.cvtColor(canvas, code=cv2.COLOR_BGR2RGB) # for k in range(self.keypoints): # cv2.circle( # canvas, # (pts[k, 1], pts[k, 0]), # 3, # (0, 0, 255), # -1) # scale_factor = 3 # cv2.imshow( # winname="canvas", # mat=cv2.resize( # src=canvas, # dsize=None, # fx=scale_factor, # fy=scale_factor, # interpolation=cv2.INTER_NEAREST)) # cv2.waitKey(0) # cv2.destroyAllWindows() return y @staticmethod def sigmoid(x): return 1.0 / (1.0 + math.exp(-x)) def get_grmiposelite(model_path, keypoints, model_name=None, data_format="channels_last", pretrained=False, **kwargs): """ Create GRMIPose (Google PoseNet) model with specific parameters. Parameters: ---------- model_path : str Path to pretrained model. keypoints : int Number of keypoints. model_name : str or None, default None Model name for loading pretrained model. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. """ assert (pretrained is not None) assert (model_name is not None) if (model_path is None) or (not model_path): raise ValueError("Parameter `model_path` should be properly initialized for loading pretrained model.") interpreter = tf.lite.Interpreter(model_path=model_path) net = GRMIPoseLite( interpreter=interpreter, keypoints=keypoints, data_format=data_format, **kwargs) return net def grmiposelite_mobilenet_w1_coco(model_path, keypoints=17, data_format="channels_last", pretrained=False, **kwargs): """ GRMIPose (Google PoseNet) model on the base of 1.0 MobileNet-224 for COCO Keypoint from 'Towards Accurate Multi-person Pose Estimation in the Wild,' https://arxiv.org/abs/1701.01779. Parameters: ---------- model_path : str Path to pretrained model. keypoints : int, default 17 Number of keypoints. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_grmiposelite(model_path=model_path, keypoints=keypoints, model_name="grmiposelite_mobilenet_w1_coco", data_format=data_format, pretrained=pretrained, **kwargs) def _test(): data_format = "channels_last" in_size = (257, 257) keypoints = 17 pretrained = False model_path = "" models = [ grmiposelite_mobilenet_w1_coco, ] for model in models: net = model(model_path=model_path, pretrained=pretrained, in_size=in_size, data_format=data_format) batch = 1 x = tf.random.normal((batch, in_size[0], in_size[1], 3)) y = net(x) assert (y.shape[0] == batch) assert ((y.shape[1] == keypoints) and (y.shape[2] == 3)) if __name__ == "__main__": _test()
6,726
32.137931
118
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/bisenet.py
""" BiSeNet for CelebAMask-HQ, implemented in TensorFlow. Original paper: 'BiSeNet: Bilateral Segmentation Network for Real-time Semantic Segmentation,' https://arxiv.org/abs/1808.00897. """ __all__ = ['BiSeNet', 'bisenet_resnet18_celebamaskhq'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1, conv1x1_block, conv3x3_block, InterpolationBlock, MultiOutputSequential, get_channel_axis,\ get_im_size, is_channels_first from .resnet import resnet18 class PyramidPoolingZeroBranch(nn.Layer): """ Pyramid pooling zero branch. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. in_size : tuple of 2 int Spatial size of output image for the upsampling operation. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, in_size, data_format="channels_last", **kwargs): super(PyramidPoolingZeroBranch, self).__init__(**kwargs) self.in_size = in_size self.data_format = data_format self.pool = nn.GlobalAveragePooling2D( data_format=data_format, name="pool") self.conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, data_format=data_format, name="conv") self.up = InterpolationBlock( scale_factor=None, interpolation="bilinear", data_format=data_format, name="up") def call(self, x, training=None): in_size = self.in_size if self.in_size is not None else get_im_size(x, data_format=self.data_format) x = self.pool(x) axis = -1 if is_channels_first(self.data_format) else 1 x = tf.expand_dims(tf.expand_dims(x, axis=axis), axis=axis) x = self.conv(x, training=training) x = self.up(x, size=in_size) return x class AttentionRefinementBlock(nn.Layer): """ Attention refinement block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(AttentionRefinementBlock, self).__init__(**kwargs) self.data_format = data_format self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=out_channels, data_format=data_format, name="conv1") self.pool = nn.GlobalAveragePooling2D( data_format=data_format, name="pool") self.conv2 = conv1x1_block( in_channels=out_channels, out_channels=out_channels, activation="sigmoid", data_format=data_format, name="conv2") def call(self, x, training=None): x = self.conv1(x, training=training) w = self.pool(x) axis = -1 if is_channels_first(self.data_format) else 1 w = tf.expand_dims(tf.expand_dims(w, axis=axis), axis=axis) w = self.conv2(w, training=training) x = x * w return x class PyramidPoolingMainBranch(nn.Layer): """ Pyramid pooling main branch. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. scale_factor : float Multiplier for spatial size. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, scale_factor, data_format="channels_last", **kwargs): super(PyramidPoolingMainBranch, self).__init__(**kwargs) self.att = AttentionRefinementBlock( in_channels=in_channels, out_channels=out_channels, data_format=data_format, name="att") self.up = InterpolationBlock( scale_factor=scale_factor, interpolation="bilinear", data_format=data_format, name="up") self.conv = conv3x3_block( in_channels=out_channels, out_channels=out_channels, data_format=data_format, name="conv") def call(self, x, y, training=None): x = self.att(x, training=training) x = x + y x = self.up(x) x = self.conv(x, training=training) return x class FeatureFusion(nn.Layer): """ Feature fusion block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. reduction : int, default 4 Squeeze reduction value. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, reduction=4, data_format="channels_last", **kwargs): super(FeatureFusion, self).__init__(**kwargs) self.data_format = data_format mid_channels = out_channels // reduction self.conv_merge = conv1x1_block( in_channels=in_channels, out_channels=out_channels, data_format=data_format, name="conv_merge") self.pool = nn.GlobalAveragePooling2D( data_format=data_format, name="pool") self.conv1 = conv1x1( in_channels=out_channels, out_channels=mid_channels, data_format=data_format, name="conv1") self.activ = nn.ReLU() self.conv2 = conv1x1( in_channels=mid_channels, out_channels=out_channels, data_format=data_format, name="conv2") self.sigmoid = tf.nn.sigmoid def call(self, x, y, training=None): x = tf.concat([x, y], axis=get_channel_axis(self.data_format)) x = self.conv_merge(x, training=training) w = self.pool(x) axis = -1 if is_channels_first(self.data_format) else 1 w = tf.expand_dims(tf.expand_dims(w, axis=axis), axis=axis) w = self.conv1(w) w = self.activ(w) w = self.conv2(w) w = self.sigmoid(w) x_att = x * w x = x + x_att return x class PyramidPooling(nn.Layer): """ Pyramid Pooling module. Parameters: ---------- x16_in_channels : int Number of input channels for x16. x32_in_channels : int Number of input channels for x32. y_out_channels : int Number of output channels for y-outputs. y32_out_size : tuple of 2 int Spatial size of the y32 tensor. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, x16_in_channels, x32_in_channels, y_out_channels, y32_out_size, data_format="channels_last", **kwargs): super(PyramidPooling, self).__init__(**kwargs) z_out_channels = 2 * y_out_channels self.pool32 = PyramidPoolingZeroBranch( in_channels=x32_in_channels, out_channels=y_out_channels, in_size=y32_out_size, data_format=data_format, name="pool32") self.pool16 = PyramidPoolingMainBranch( in_channels=x32_in_channels, out_channels=y_out_channels, scale_factor=2, data_format=data_format, name="pool16") self.pool8 = PyramidPoolingMainBranch( in_channels=x16_in_channels, out_channels=y_out_channels, scale_factor=2, data_format=data_format, name="pool8") self.fusion = FeatureFusion( in_channels=z_out_channels, out_channels=z_out_channels, data_format=data_format, name="fusion") def call(self, x8, x16, x32, training=None): y32 = self.pool32(x32, training=training) y16 = self.pool16(x32, y32, training=training) y8 = self.pool8(x16, y16, training=training) z8 = self.fusion(x8, y8, training=training) return z8, y8, y16 class BiSeHead(nn.Layer): """ BiSeNet head (final) block. Parameters: ---------- in_channels : int Number of input channels. mid_channels : int Number of middle channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, mid_channels, out_channels, data_format="channels_last", **kwargs): super(BiSeHead, self).__init__(**kwargs) self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv1") self.conv2 = conv1x1( in_channels=mid_channels, out_channels=out_channels, data_format=data_format, name="conv2") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x) return x class BiSeNet(tf.keras.Model): """ BiSeNet model from 'BiSeNet: Bilateral Segmentation Network for Real-time Semantic Segmentation,' https://arxiv.org/abs/1808.00897. Parameters: ---------- backbone : func -> nn.Sequential Feature extractor. aux : bool, default True Whether to output an auxiliary results. 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 (640, 480) Spatial size of the expected input image. classes : int, default 1000 Number of classification classes. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, backbone, aux=True, fixed_size=True, in_channels=3, in_size=(640, 480), classes=19, data_format="channels_last", **kwargs): super(BiSeNet, self).__init__(**kwargs) assert (in_channels == 3) self.in_size = in_size self.classes = classes self.data_format = data_format self.aux = aux self.fixed_size = fixed_size self.backbone, backbone_out_channels = backbone( data_format=data_format, name="backbone") y_out_channels = backbone_out_channels[0] z_out_channels = 2 * y_out_channels y32_out_size = (self.in_size[0] // 32, self.in_size[1] // 32) if fixed_size else None self.pool = PyramidPooling( x16_in_channels=backbone_out_channels[1], x32_in_channels=backbone_out_channels[2], y_out_channels=y_out_channels, y32_out_size=y32_out_size, data_format=data_format, name="pool") self.head_z8 = BiSeHead( in_channels=z_out_channels, mid_channels=z_out_channels, out_channels=classes, data_format=data_format, name="head_z8") self.up8 = InterpolationBlock( scale_factor=(8 if fixed_size else None), data_format=data_format, name="up8") if self.aux: mid_channels = y_out_channels // 2 self.head_y8 = BiSeHead( in_channels=y_out_channels, mid_channels=mid_channels, out_channels=classes, data_format=data_format, name="head_y8") self.head_y16 = BiSeHead( in_channels=y_out_channels, mid_channels=mid_channels, out_channels=classes, data_format=data_format, name="head_y16") self.up16 = InterpolationBlock( scale_factor=(16 if fixed_size else None), data_format=data_format, name="up16") def call(self, x, training=None): assert is_channels_first(self.data_format) or ((x.shape[1] % 32 == 0) and (x.shape[2] % 32 == 0)) assert (not is_channels_first(self.data_format)) or ((x.shape[2] % 32 == 0) and (x.shape[3] % 32 == 0)) x8, x16, x32 = self.backbone(x, training=training) z8, y8, y16 = self.pool(x8, x16, x32, training=training) z8 = self.head_z8(z8, training=training) z8 = self.up8(z8) if self.aux: y8 = self.head_y8(y8, training=training) y16 = self.head_y16(y16, training=training) y8 = self.up8(y8) y16 = self.up16(y16) return z8, y8, y16 else: return z8 def get_bisenet(model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create BiSeNet 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ net = BiSeNet( **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def bisenet_resnet18_celebamaskhq(pretrained_backbone=False, classes=19, **kwargs): """ BiSeNet model on the base of ResNet-18 for face segmentation on CelebAMask-HQ from 'BiSeNet: Bilateral Segmentation Network for Real-time Semantic Segmentation,' https://arxiv.org/abs/1808.00897. Parameters: ---------- pretrained_backbone : bool, default False Whether to load the pretrained weights for feature extractor. classes : int, default 19 Number of classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ def backbone(**bb_kwargs): features_raw = resnet18(pretrained=pretrained_backbone, **bb_kwargs).features del features_raw.children[-1] features = MultiOutputSequential(return_last=False, name="backbone") features.add(features_raw.children[0]) for i, stage in enumerate(features_raw.children[1:]): if i != 0: stage.do_output = True features.add(stage) out_channels = [128, 256, 512] return features, out_channels return get_bisenet(backbone=backbone, classes=classes, model_name="bisenet_resnet18_celebamaskhq", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" in_size = (640, 480) aux = True pretrained = False models = [ bisenet_resnet18_celebamaskhq, ] for model in models: net = model(pretrained=pretrained, in_size=in_size, aux=aux, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, in_size[0], in_size[1]) if is_channels_first(data_format) else (batch, in_size[0], in_size[1], 3)) ys = net(x) y = ys[0] if aux else ys assert (y.shape[0] == x.shape[0]) if is_channels_first(data_format): assert ((y.shape[1] == 19) and (y.shape[2] == x.shape[2]) and (y.shape[3] == x.shape[3])) else: assert ((y.shape[3] == 19) and (y.shape[1] == x.shape[1]) and (y.shape[2] == x.shape[2])) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) if aux: assert (model != bisenet_resnet18_celebamaskhq or weight_count == 13300416) else: assert (model != bisenet_resnet18_celebamaskhq or weight_count == 13150272) if __name__ == "__main__": _test()
17,516
32.429389
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/resnet.py
""" ResNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. """ __all__ = ['ResNet', 'resnet10', 'resnet12', 'resnet14', 'resnetbc14b', 'resnet16', 'resnet18_wd4', 'resnet18_wd2', 'resnet18_w3d4', 'resnet18', 'resnet26', 'resnetbc26b', 'resnet34', 'resnetbc38b', 'resnet50', 'resnet50b', 'resnet101', 'resnet101b', 'resnet152', 'resnet152b', 'resnet200', 'resnet200b', 'ResBlock', 'ResBottleneck', 'ResUnit', 'ResInitBlock', 'get_resnet'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1_block, conv3x3_block, conv7x7_block, MaxPool2d, SimpleSequential, flatten, is_channels_first class ResBlock(nn.Layer): """ Simple ResNet block for residual path in 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_bias : bool, default False Whether the layer uses a bias vector. use_bn : bool, default True Whether to use BatchNorm layer. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, use_bias=False, use_bn=True, data_format="channels_last", **kwargs): super(ResBlock, self).__init__(**kwargs) self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=out_channels, strides=strides, use_bias=use_bias, use_bn=use_bn, data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=out_channels, out_channels=out_channels, use_bias=use_bias, use_bn=use_bn, activation=None, data_format=data_format, name="conv2") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) return x class ResBottleneck(nn.Layer): """ ResNet bottleneck block for residual path in 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, padding=1, dilation=1, conv1_stride=False, bottleneck_factor=4, data_format="channels_last", **kwargs): super(ResBottleneck, self).__init__(**kwargs) mid_channels = out_channels // bottleneck_factor self.conv1 = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, strides=(strides if conv1_stride else 1), data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=mid_channels, out_channels=mid_channels, strides=(1 if conv1_stride else strides), padding=padding, dilation=dilation, data_format=data_format, name="conv2") self.conv3 = conv1x1_block( in_channels=mid_channels, out_channels=out_channels, activation=None, data_format=data_format, name="conv3") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.conv3(x, training=training) return x class ResUnit(nn.Layer): """ 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. use_bias : bool, default False Whether the layer uses a bias vector. use_bn : bool, default True Whether to use BatchNorm layer. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, padding=1, dilation=1, use_bias=False, use_bn=True, bottleneck=True, conv1_stride=False, data_format="channels_last", **kwargs): super(ResUnit, self).__init__(**kwargs) self.resize_identity = (in_channels != out_channels) or (strides != 1) if bottleneck: self.body = ResBottleneck( in_channels=in_channels, out_channels=out_channels, strides=strides, padding=padding, dilation=dilation, conv1_stride=conv1_stride, data_format=data_format, name="body") else: self.body = ResBlock( in_channels=in_channels, out_channels=out_channels, strides=strides, use_bias=use_bias, use_bn=use_bn, data_format=data_format, name="body") if self.resize_identity: self.identity_conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, strides=strides, use_bias=use_bias, use_bn=use_bn, activation=None, data_format=data_format, name="identity_conv") self.activ = nn.ReLU() def call(self, x, training=None): if self.resize_identity: identity = self.identity_conv(x, training=training) else: identity = x x = self.body(x, training=training) x = x + identity x = self.activ(x) return x class ResInitBlock(nn.Layer): """ ResNet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(ResInitBlock, self).__init__(**kwargs) self.conv = conv7x7_block( in_channels=in_channels, out_channels=out_channels, strides=2, data_format=data_format, name="conv") self.pool = MaxPool2d( pool_size=3, strides=2, padding=1, data_format=data_format, name="pool") def call(self, x, training=None): x = self.conv(x, training=training) x = self.pool(x) return x class ResNet(tf.keras.Model): """ ResNet 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, bottleneck, conv1_stride, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(ResNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(ResInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(ResUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, bottleneck=bottleneck, conv1_stride=conv1_stride, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_resnet(blocks, bottleneck=None, conv1_stride=True, width_scale=1.0, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create 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. root : str, default '~/.tensorflow/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 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 = ResNet( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def resnet10(**kwargs): """ ResNet-10 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=10, model_name="resnet10", **kwargs) def resnet12(**kwargs): """ ResNet-12 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=12, model_name="resnet12", **kwargs) def resnet14(**kwargs): """ ResNet-14 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=14, model_name="resnet14", **kwargs) def resnetbc14b(**kwargs): """ ResNet-BC-14b 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=14, bottleneck=True, conv1_stride=False, model_name="resnetbc14b", **kwargs) def resnet16(**kwargs): """ ResNet-16 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=16, model_name="resnet16", **kwargs) def resnet18_wd4(**kwargs): """ ResNet-18 model with 0.25 width scale from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=18, width_scale=0.25, model_name="resnet18_wd4", **kwargs) def resnet18_wd2(**kwargs): """ ResNet-18 model with 0.5 width scale from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=18, width_scale=0.5, model_name="resnet18_wd2", **kwargs) def resnet18_w3d4(**kwargs): """ ResNet-18 model with 0.75 width scale from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=18, width_scale=0.75, model_name="resnet18_w3d4", **kwargs) def resnet18(**kwargs): """ ResNet-18 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=18, model_name="resnet18", **kwargs) def resnet26(**kwargs): """ ResNet-26 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=26, bottleneck=False, model_name="resnet26", **kwargs) def resnetbc26b(**kwargs): """ ResNet-BC-26b 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=26, bottleneck=True, conv1_stride=False, model_name="resnetbc26b", **kwargs) def resnet34(**kwargs): """ ResNet-34 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=34, model_name="resnet34", **kwargs) def resnetbc38b(**kwargs): """ ResNet-BC-38b 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=38, bottleneck=True, conv1_stride=False, model_name="resnetbc38b", **kwargs) def resnet50(**kwargs): """ ResNet-50 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=50, model_name="resnet50", **kwargs) def resnet50b(**kwargs): """ ResNet-50 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=50, conv1_stride=False, model_name="resnet50b", **kwargs) def resnet101(**kwargs): """ ResNet-101 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=101, model_name="resnet101", **kwargs) def resnet101b(**kwargs): """ ResNet-101 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=101, conv1_stride=False, model_name="resnet101b", **kwargs) def resnet152(**kwargs): """ ResNet-152 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=152, model_name="resnet152", **kwargs) def resnet152b(**kwargs): """ ResNet-152 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=152, conv1_stride=False, model_name="resnet152b", **kwargs) def resnet200(**kwargs): """ ResNet-200 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=200, model_name="resnet200", **kwargs) def resnet200b(**kwargs): """ ResNet-200 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=200, conv1_stride=False, model_name="resnet200b", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" pretrained = False models = [ resnet10, resnet12, resnet14, resnetbc14b, resnet16, resnet18_wd4, resnet18_wd2, resnet18_w3d4, resnet18, resnet26, resnetbc26b, resnet34, resnetbc38b, resnet50, resnet50b, resnet101, resnet101b, resnet152, resnet152b, resnet200, resnet200b, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 4 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != resnet10 or weight_count == 5418792) assert (model != resnet12 or weight_count == 5492776) assert (model != resnet14 or weight_count == 5788200) assert (model != resnetbc14b or weight_count == 10064936) assert (model != resnet16 or weight_count == 6968872) assert (model != resnet18_wd4 or weight_count == 3937400) assert (model != resnet18_wd2 or weight_count == 5804296) assert (model != resnet18_w3d4 or weight_count == 8476056) assert (model != resnet18 or weight_count == 11689512) assert (model != resnet26 or weight_count == 17960232) assert (model != resnetbc26b or weight_count == 15995176) assert (model != resnet34 or weight_count == 21797672) assert (model != resnetbc38b or weight_count == 21925416) assert (model != resnet50 or weight_count == 25557032) assert (model != resnet50b or weight_count == 25557032) assert (model != resnet101 or weight_count == 44549160) assert (model != resnet101b or weight_count == 44549160) assert (model != resnet152 or weight_count == 60192808) assert (model != resnet152b or weight_count == 60192808) assert (model != resnet200 or weight_count == 64673832) assert (model != resnet200b or weight_count == 64673832) if __name__ == "__main__": _test()
27,599
32.948339
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/simpleposemobile_coco.py
""" SimplePose(Mobile) for COCO Keypoint, implemented in TensorFlow. Original paper: 'Simple Baselines for Human Pose Estimation and Tracking,' https://arxiv.org/abs/1804.06208. """ __all__ = ['SimplePoseMobile', 'simplepose_mobile_resnet18_coco', 'simplepose_mobile_resnet50b_coco', 'simplepose_mobile_mobilenet_w1_coco', 'simplepose_mobile_mobilenetv2b_w1_coco', 'simplepose_mobile_mobilenetv3_small_w1_coco', 'simplepose_mobile_mobilenetv3_large_w1_coco'] import os import tensorflow as tf from .common import conv1x1, DucBlock, HeatmapMaxDetBlock, SimpleSequential, is_channels_first from .resnet import resnet18, resnet50b from .mobilenet import mobilenet_w1 from .mobilenetv2 import mobilenetv2b_w1 from .mobilenetv3 import mobilenetv3_small_w1, mobilenetv3_large_w1 class SimplePoseMobile(tf.keras.Model): """ SimplePose(Mobile) 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. decoder_init_block_channels : int Number of output channels for the initial unit of the decoder. return_heatmap : bool, default False Whether to return only heatmap. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, backbone, backbone_out_channels, channels, decoder_init_block_channels, return_heatmap=False, in_channels=3, in_size=(256, 192), keypoints=17, data_format="channels_last", **kwargs): super(SimplePoseMobile, self).__init__(**kwargs) assert (in_channels == 3) self.in_size = in_size self.keypoints = keypoints self.return_heatmap = return_heatmap self.data_format = data_format self.backbone = backbone self.backbone._name = "backbone" self.decoder = SimpleSequential(name="decoder") in_channels = backbone_out_channels self.decoder.add(conv1x1( in_channels=in_channels, out_channels=decoder_init_block_channels, data_format=data_format, name="init_block")) in_channels = decoder_init_block_channels for i, out_channels in enumerate(channels): self.decoder.add(DucBlock( in_channels=in_channels, out_channels=out_channels, scale_factor=2, data_format=data_format, name="unit{}".format(i + 1))) in_channels = out_channels self.decoder.add(conv1x1( in_channels=in_channels, out_channels=keypoints, data_format=data_format, name="final_block")) self.heatmap_max_det = HeatmapMaxDetBlock( data_format=data_format, name="heatmap_max_det") def call(self, x, training=None): x = self.backbone(x, training=training) heatmap = self.decoder(x, training=training) if self.return_heatmap or not tf.executing_eagerly(): return heatmap else: keypoints = self.heatmap_max_det(heatmap) return keypoints def get_simpleposemobile(backbone, backbone_out_channels, keypoints, model_name=None, data_format="channels_last", pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create SimplePose(Mobile) 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. model_name : str or None, default None Model name for loading pretrained model. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ channels = [128, 64, 32] decoder_init_block_channels = 256 net = SimplePoseMobile( backbone=backbone, backbone_out_channels=backbone_out_channels, channels=channels, decoder_init_block_channels=decoder_init_block_channels, keypoints=keypoints, data_format=data_format, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def simplepose_mobile_resnet18_coco(pretrained_backbone=False, keypoints=17, data_format="channels_last", **kwargs): """ SimplePose(Mobile) 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnet18(pretrained=pretrained_backbone, data_format=data_format).features del backbone.children[-1] return get_simpleposemobile(backbone=backbone, backbone_out_channels=512, keypoints=keypoints, model_name="simplepose_mobile_resnet18_coco", data_format=data_format, **kwargs) def simplepose_mobile_resnet50b_coco(pretrained_backbone=False, keypoints=17, data_format="channels_last", **kwargs): """ SimplePose(Mobile) 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnet50b(pretrained=pretrained_backbone, data_format=data_format).features del backbone.children[-1] return get_simpleposemobile(backbone=backbone, backbone_out_channels=2048, keypoints=keypoints, model_name="simplepose_mobile_resnet50b_coco", data_format=data_format, **kwargs) def simplepose_mobile_mobilenet_w1_coco(pretrained_backbone=False, keypoints=17, data_format="channels_last", **kwargs): """ SimplePose(Mobile) model on the base of 1.0 MobileNet-224 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = mobilenet_w1(pretrained=pretrained_backbone, data_format=data_format).features del backbone.children[-1] return get_simpleposemobile(backbone=backbone, backbone_out_channels=1024, keypoints=keypoints, model_name="simplepose_mobile_mobilenet_w1_coco", data_format=data_format, **kwargs) def simplepose_mobile_mobilenetv2b_w1_coco(pretrained_backbone=False, keypoints=17, data_format="channels_last", **kwargs): """ SimplePose(Mobile) model on the base of 1.0 MobileNetV2b-224 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = mobilenetv2b_w1(pretrained=pretrained_backbone, data_format=data_format).features del backbone.children[-1] return get_simpleposemobile(backbone=backbone, backbone_out_channels=1280, keypoints=keypoints, model_name="simplepose_mobile_mobilenetv2b_w1_coco", data_format=data_format, **kwargs) def simplepose_mobile_mobilenetv3_small_w1_coco(pretrained_backbone=False, keypoints=17, data_format="channels_last", **kwargs): """ SimplePose(Mobile) model on the base of MobileNetV3 Small 224/1.0 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = mobilenetv3_small_w1(pretrained=pretrained_backbone, data_format=data_format).features del backbone.children[-1] return get_simpleposemobile(backbone=backbone, backbone_out_channels=576, keypoints=keypoints, model_name="simplepose_mobile_mobilenetv3_small_w1_coco", data_format=data_format, **kwargs) def simplepose_mobile_mobilenetv3_large_w1_coco(pretrained_backbone=False, keypoints=17, data_format="channels_last", **kwargs): """ SimplePose(Mobile) model on the base of MobileNetV3 Large 224/1.0 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = mobilenetv3_large_w1(pretrained=pretrained_backbone, data_format=data_format).features del backbone.children[-1] return get_simpleposemobile(backbone=backbone, backbone_out_channels=960, keypoints=keypoints, model_name="simplepose_mobile_mobilenetv3_large_w1_coco", data_format=data_format, **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" in_size = (256, 192) keypoints = 17 pretrained_backbone = False return_heatmap = False pretrained = False models = [ simplepose_mobile_resnet18_coco, simplepose_mobile_resnet50b_coco, simplepose_mobile_mobilenet_w1_coco, simplepose_mobile_mobilenetv2b_w1_coco, simplepose_mobile_mobilenetv3_small_w1_coco, simplepose_mobile_mobilenetv3_large_w1_coco, ] for model in models: net = model(pretrained_backbone=pretrained_backbone, keypoints=keypoints, pretrained=pretrained, in_size=in_size, return_heatmap=return_heatmap, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, in_size[0], in_size[1]) if is_channels_first(data_format) else (batch, in_size[0], in_size[1], 3)) y = net(x) assert (y.shape[0] == batch) if return_heatmap: if is_channels_first(data_format): assert ((y.shape[1] == keypoints) and (y.shape[2] == x.shape[2] // 4) and (y.shape[3] == x.shape[3] // 4)) else: assert ((y.shape[3] == keypoints) and (y.shape[1] == x.shape[1] // 4) and (y.shape[2] == x.shape[2] // 4)) else: assert ((y.shape[1] == keypoints) and (y.shape[2] == 3)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != simplepose_mobile_resnet18_coco or weight_count == 12858208) assert (model != simplepose_mobile_resnet50b_coco or weight_count == 25582944) assert (model != simplepose_mobile_mobilenet_w1_coco or weight_count == 5019744) assert (model != simplepose_mobile_mobilenetv2b_w1_coco or weight_count == 4102176) assert (model != simplepose_mobile_mobilenetv3_small_w1_coco or weight_count == 2625088) assert (model != simplepose_mobile_mobilenetv3_large_w1_coco or weight_count == 4768336) if __name__ == "__main__": _test()
15,320
41.558333
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/cbamresnet.py
""" CBAM-ResNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521. """ __all__ = ['CbamResNet', 'cbam_resnet18', 'cbam_resnet34', 'cbam_resnet50', 'cbam_resnet101', 'cbam_resnet152'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1_block, conv7x7_block, SimpleSequential, flatten, is_channels_first, get_channel_axis from .resnet import ResInitBlock, ResBlock, ResBottleneck class MLP(nn.Layer): """ Multilayer perceptron block. Parameters: ---------- channels : int Number of input/output channels. reduction_ratio : int, default 16 Channel reduction ratio. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, reduction_ratio=16, data_format="channels_last", **kwargs): super(MLP, self).__init__(**kwargs) self.data_format = data_format mid_channels = channels // reduction_ratio self.fc1 = nn.Dense( units=mid_channels, input_dim=channels, name="fc1") self.activ = nn.ReLU() self.fc2 = nn.Dense( units=channels, input_dim=mid_channels, name="fc2") def call(self, x, training=None): # x = flatten(x, self.data_format) x = self.fc1(x) x = self.activ(x) x = self.fc2(x) return x class ChannelGate(nn.Layer): """ CBAM channel gate block. Parameters: ---------- channels : int Number of input/output channels. reduction_ratio : int, default 16 Channel reduction ratio. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, reduction_ratio=16, data_format="channels_last", **kwargs): super(ChannelGate, self).__init__(**kwargs) self.data_format = data_format self.avg_pool = nn.GlobalAvgPool2D( data_format=data_format, name="avg_pool") self.max_pool = nn.GlobalMaxPool2D( data_format=data_format, name="max_pool") self.mlp = MLP( channels=channels, reduction_ratio=reduction_ratio, data_format=data_format, name="mlp") self.sigmoid = tf.nn.sigmoid def call(self, x, training=None): att1 = self.avg_pool(x) att1 = self.mlp(att1) att2 = self.max_pool(x) att2 = self.mlp(att2) att = att1 + att2 att = self.sigmoid(att) if is_channels_first(self.data_format): att = tf.broadcast_to(tf.expand_dims(tf.expand_dims(att, 2), 3), shape=x.shape) else: att = tf.broadcast_to(tf.expand_dims(tf.expand_dims(att, 1), 2), shape=x.shape) x = x * att return x class SpatialGate(nn.Layer): """ CBAM spatial gate block. Parameters: ---------- data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, data_format="channels_last", **kwargs): super(SpatialGate, self).__init__(**kwargs) self.data_format = data_format self.conv = conv7x7_block( in_channels=2, out_channels=1, activation=None, data_format=data_format, name="conv") self.sigmoid = tf.nn.sigmoid def call(self, x, training=None): axis = get_channel_axis(self.data_format) att1 = tf.math.reduce_max(x, axis=axis, keepdims=True) att2 = tf.math.reduce_mean(x, axis=axis, keepdims=True) att = tf.concat([att1, att2], axis=axis) att = self.conv(att, training=training) att = tf.broadcast_to(self.sigmoid(att), shape=x.shape) x = x * att return x class CbamBlock(nn.Layer): """ CBAM attention block for CBAM-ResNet. Parameters: ---------- channels : int Number of input/output channels. reduction_ratio : int, default 16 Channel reduction ratio. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, reduction_ratio=16, data_format="channels_last", **kwargs): super(CbamBlock, self).__init__(**kwargs) self.ch_gate = ChannelGate( channels=channels, reduction_ratio=reduction_ratio, data_format=data_format, name="ch_gate") self.sp_gate = SpatialGate( data_format=data_format, name="sp_gate") def call(self, x, training=None): x = self.ch_gate(x, training=training) x = self.sp_gate(x, training=training) return x class CbamResUnit(nn.Layer): """ CBAM-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. bottleneck : bool Whether to use a bottleneck or simple block in units. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, bottleneck, data_format="channels_last", **kwargs): super(CbamResUnit, self).__init__(**kwargs) self.resize_identity = (in_channels != out_channels) or (strides != 1) if bottleneck: self.body = ResBottleneck( in_channels=in_channels, out_channels=out_channels, strides=strides, conv1_stride=False, data_format=data_format, name="body") else: self.body = ResBlock( in_channels=in_channels, out_channels=out_channels, strides=strides, data_format=data_format, name="body") if self.resize_identity: self.identity_conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, strides=strides, activation=None, data_format=data_format, name="identity_conv") self.cbam = CbamBlock( channels=out_channels, data_format=data_format, name="cbam") self.activ = nn.ReLU() def call(self, x, training=None): if self.resize_identity: identity = self.identity_conv(x, training=training) else: identity = x x = self.body(x, training=training) x = self.cbam(x, training=training) x = x + identity x = self.activ(x) return x class CbamResNet(tf.keras.Model): """ CBAM-ResNet model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521. 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, bottleneck, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(CbamResNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(ResInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(CbamResUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, bottleneck=bottleneck, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_resnet(blocks, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create CBAM-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. root : str, default '~/.tensorflow/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 CBAM-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 = CbamResNet( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def cbam_resnet18(**kwargs): """ CBAM-ResNet-18 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=18, model_name="cbam_resnet18", **kwargs) def cbam_resnet34(**kwargs): """ CBAM-ResNet-34 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=34, model_name="cbam_resnet34", **kwargs) def cbam_resnet50(**kwargs): """ CBAM-ResNet-50 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=50, model_name="cbam_resnet50", **kwargs) def cbam_resnet101(**kwargs): """ CBAM-ResNet-101 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=101, model_name="cbam_resnet101", **kwargs) def cbam_resnet152(**kwargs): """ CBAM-ResNet-152 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(blocks=152, model_name="cbam_resnet152", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ cbam_resnet18, cbam_resnet34, cbam_resnet50, cbam_resnet101, cbam_resnet152, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != cbam_resnet18 or weight_count == 11779392) assert (model != cbam_resnet34 or weight_count == 21960468) assert (model != cbam_resnet50 or weight_count == 28089624) assert (model != cbam_resnet101 or weight_count == 49330172) assert (model != cbam_resnet152 or weight_count == 66826848) if __name__ == "__main__": _test()
15,596
30.830612
115
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/diracnetv2.py
""" DiracNetV2 for ImageNet-1K, implemented in TensorFlow. Original paper: 'DiracNets: Training Very Deep Neural Networks Without Skip-Connections,' https://arxiv.org/abs/1706.00388. """ __all__ = ['DiracNetV2', 'diracnet18v2', 'diracnet34v2'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import Conv2d, MaxPool2d, SimpleSequential, flatten, is_channels_first class DiracConv(nn.Layer): """ DiracNetV2 specific convolution block with 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, strides, padding, data_format="channels_last", **kwargs): super(DiracConv, self).__init__(**kwargs) self.activ = nn.ReLU() self.conv = Conv2d( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, strides=strides, padding=padding, use_bias=True, data_format=data_format, name="conv") def call(self, x, training=None): x = self.activ(x) x = self.conv(x) return x def dirac_conv3x3(in_channels, out_channels, data_format="channels_last", **kwargs): """ 3x3 version of the DiracNetV2 specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ return DiracConv( in_channels=in_channels, out_channels=out_channels, kernel_size=3, strides=1, padding=1, data_format=data_format, **kwargs) class DiracInitBlock(nn.Layer): """ DiracNetV2 specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(DiracInitBlock, self).__init__(**kwargs) self.conv = Conv2d( in_channels=in_channels, out_channels=out_channels, kernel_size=7, strides=2, padding=3, use_bias=True, data_format=data_format, name="conv") self.pool = MaxPool2d( pool_size=3, strides=2, padding=1, data_format=data_format, name="pool") def call(self, x, training=None): x = self.conv(x) x = self.pool(x) return x class DiracNetV2(tf.keras.Model): """ DiracNetV2 model from 'DiracNets: Training Very Deep Neural Networks Without Skip-Connections,' https://arxiv.org/abs/1706.00388. 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(DiracNetV2, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(DiracInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) for j, out_channels in enumerate(channels_per_stage): stage.add(dirac_conv3x3( in_channels=in_channels, out_channels=out_channels, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels if i != len(channels) - 1: stage.add(MaxPool2d( pool_size=2, strides=2, padding=0, data_format=data_format, name="pool{}".format(i + 1))) self.features.add(stage) self.features.add(nn.ReLU(name="final_activ")) self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_diracnetv2(blocks, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create DiracNetV2 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if blocks == 18: layers = [4, 4, 4, 4] elif blocks == 34: layers = [6, 8, 12, 6] else: raise ValueError("Unsupported DiracNetV2 with number of blocks: {}".format(blocks)) channels_per_layers = [64, 128, 256, 512] channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)] init_block_channels = 64 net = DiracNetV2( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def diracnet18v2(**kwargs): """ DiracNetV2 model from 'DiracNets: Training Very Deep Neural Networks Without Skip-Connections,' https://arxiv.org/abs/1706.00388. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_diracnetv2(blocks=18, model_name="diracnet18v2", **kwargs) def diracnet34v2(**kwargs): """ DiracNetV2 model from 'DiracNets: Training Very Deep Neural Networks Without Skip-Connections,' https://arxiv.org/abs/1706.00388. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_diracnetv2(blocks=34, model_name="diracnet34v2", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ diracnet18v2, diracnet34v2, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != diracnet18v2 or weight_count == 11511784) assert (model != diracnet34v2 or weight_count == 21616232) if __name__ == "__main__": _test()
9,781
30.152866
115
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/sepreresnet_cifar.py
""" SE-PreResNet for CIFAR/SVHN, implemented in TensorFlow. Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. """ __all__ = ['CIFARSEPreResNet', 'sepreresnet20_cifar10', 'sepreresnet20_cifar100', 'sepreresnet20_svhn', 'sepreresnet56_cifar10', 'sepreresnet56_cifar100', 'sepreresnet56_svhn', 'sepreresnet110_cifar10', 'sepreresnet110_cifar100', 'sepreresnet110_svhn', 'sepreresnet164bn_cifar10', 'sepreresnet164bn_cifar100', 'sepreresnet164bn_svhn', 'sepreresnet272bn_cifar10', 'sepreresnet272bn_cifar100', 'sepreresnet272bn_svhn', 'sepreresnet542bn_cifar10', 'sepreresnet542bn_cifar100', 'sepreresnet542bn_svhn', 'sepreresnet1001_cifar10', 'sepreresnet1001_cifar100', 'sepreresnet1001_svhn', 'sepreresnet1202_cifar10', 'sepreresnet1202_cifar100', 'sepreresnet1202_svhn'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv3x3_block, SimpleSequential, flatten, is_channels_first from .sepreresnet import SEPreResUnit class CIFARSEPreResNet(tf.keras.Model): """ SE-PreResNet model for CIFAR 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, bottleneck, in_channels=3, in_size=(32, 32), classes=10, data_format="channels_last", **kwargs): super(CIFARSEPreResNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(conv3x3_block( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(SEPreResUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, bottleneck=bottleneck, conv1_stride=False, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(nn.AveragePooling2D( pool_size=8, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_sepreresnet_cifar(classes, blocks, bottleneck, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create SE-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. root : str, default '~/.tensorflow/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 = CIFARSEPreResNet( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def sepreresnet20_cifar10(classes=10, **kwargs): """ SE-PreResNet-20 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="sepreresnet20_cifar10", **kwargs) def sepreresnet20_cifar100(classes=100, **kwargs): """ SE-PreResNet-20 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="sepreresnet20_cifar100", **kwargs) def sepreresnet20_svhn(classes=10, **kwargs): """ SE-PreResNet-20 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="sepreresnet20_svhn", **kwargs) def sepreresnet56_cifar10(classes=10, **kwargs): """ SE-PreResNet-56 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name="sepreresnet56_cifar10", **kwargs) def sepreresnet56_cifar100(classes=100, **kwargs): """ SE-PreResNet-56 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name="sepreresnet56_cifar100", **kwargs) def sepreresnet56_svhn(classes=10, **kwargs): """ SE-PreResNet-56 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name="sepreresnet56_svhn", **kwargs) def sepreresnet110_cifar10(classes=10, **kwargs): """ SE-PreResNet-110 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name="sepreresnet110_cifar10", **kwargs) def sepreresnet110_cifar100(classes=100, **kwargs): """ SE-PreResNet-110 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name="sepreresnet110_cifar100", **kwargs) def sepreresnet110_svhn(classes=10, **kwargs): """ SE-PreResNet-110 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name="sepreresnet110_svhn", **kwargs) def sepreresnet164bn_cifar10(classes=10, **kwargs): """ SE-PreResNet-164(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name="sepreresnet164bn_cifar10", **kwargs) def sepreresnet164bn_cifar100(classes=100, **kwargs): """ SE-PreResNet-164(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name="sepreresnet164bn_cifar100", **kwargs) def sepreresnet164bn_svhn(classes=10, **kwargs): """ SE-PreResNet-164(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name="sepreresnet164bn_svhn", **kwargs) def sepreresnet272bn_cifar10(classes=10, **kwargs): """ SE-PreResNet-272(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name="sepreresnet272bn_cifar10", **kwargs) def sepreresnet272bn_cifar100(classes=100, **kwargs): """ SE-PreResNet-272(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name="sepreresnet272bn_cifar100", **kwargs) def sepreresnet272bn_svhn(classes=10, **kwargs): """ SE-PreResNet-272(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name="sepreresnet272bn_svhn", **kwargs) def sepreresnet542bn_cifar10(classes=10, **kwargs): """ SE-PreResNet-542(BN) model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name="sepreresnet542bn_cifar10", **kwargs) def sepreresnet542bn_cifar100(classes=100, **kwargs): """ SE-PreResNet-542(BN) model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name="sepreresnet542bn_cifar100", **kwargs) def sepreresnet542bn_svhn(classes=10, **kwargs): """ SE-PreResNet-542(BN) model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name="sepreresnet542bn_svhn", **kwargs) def sepreresnet1001_cifar10(classes=10, **kwargs): """ SE-PreResNet-1001 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="sepreresnet1001_cifar10", **kwargs) def sepreresnet1001_cifar100(classes=100, **kwargs): """ SE-PreResNet-1001 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="sepreresnet1001_cifar100", **kwargs) def sepreresnet1001_svhn(classes=10, **kwargs): """ SE-PreResNet-1001 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="sepreresnet1001_svhn", **kwargs) def sepreresnet1202_cifar10(classes=10, **kwargs): """ SE-PreResNet-1202 model for CIFAR-10 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name="sepreresnet1202_cifar10", **kwargs) def sepreresnet1202_cifar100(classes=100, **kwargs): """ SE-PreResNet-1202 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name="sepreresnet1202_cifar100", **kwargs) def sepreresnet1202_svhn(classes=10, **kwargs): """ SE-PreResNet-1202 model for SVHN from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_sepreresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name="sepreresnet1202_svhn", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" pretrained = False models = [ (sepreresnet20_cifar10, 10), (sepreresnet20_cifar100, 100), (sepreresnet20_svhn, 10), (sepreresnet56_cifar10, 10), (sepreresnet56_cifar100, 100), (sepreresnet56_svhn, 10), (sepreresnet110_cifar10, 10), (sepreresnet110_cifar100, 100), (sepreresnet110_svhn, 10), (sepreresnet164bn_cifar10, 10), (sepreresnet164bn_cifar100, 100), (sepreresnet164bn_svhn, 10), (sepreresnet272bn_cifar10, 10), (sepreresnet272bn_cifar100, 100), (sepreresnet272bn_svhn, 10), (sepreresnet542bn_cifar10, 10), (sepreresnet542bn_cifar100, 100), (sepreresnet542bn_svhn, 10), (sepreresnet1001_cifar10, 10), (sepreresnet1001_cifar100, 100), (sepreresnet1001_svhn, 10), (sepreresnet1202_cifar10, 10), (sepreresnet1202_cifar100, 100), (sepreresnet1202_svhn, 10), ] for model, classes in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 32, 32) if is_channels_first(data_format) else (batch, 32, 32, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, classes)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != sepreresnet20_cifar10 or weight_count == 274559) assert (model != sepreresnet20_cifar100 or weight_count == 280409) assert (model != sepreresnet20_svhn or weight_count == 274559) assert (model != sepreresnet56_cifar10 or weight_count == 862601) assert (model != sepreresnet56_cifar100 or weight_count == 868451) assert (model != sepreresnet56_svhn or weight_count == 862601) assert (model != sepreresnet110_cifar10 or weight_count == 1744664) assert (model != sepreresnet110_cifar100 or weight_count == 1750514) assert (model != sepreresnet110_svhn or weight_count == 1744664) assert (model != sepreresnet164bn_cifar10 or weight_count == 1904882) assert (model != sepreresnet164bn_cifar100 or weight_count == 1928012) assert (model != sepreresnet164bn_svhn or weight_count == 1904882) assert (model != sepreresnet272bn_cifar10 or weight_count == 3152450) assert (model != sepreresnet272bn_cifar100 or weight_count == 3175580) assert (model != sepreresnet272bn_svhn or weight_count == 3152450) assert (model != sepreresnet542bn_cifar10 or weight_count == 6271370) assert (model != sepreresnet542bn_cifar100 or weight_count == 6294500) assert (model != sepreresnet542bn_svhn or weight_count == 6271370) assert (model != sepreresnet1001_cifar10 or weight_count == 11573534) assert (model != sepreresnet1001_cifar100 or weight_count == 11596664) assert (model != sepreresnet1001_svhn or weight_count == 11573534) assert (model != sepreresnet1202_cifar10 or weight_count == 19581938) assert (model != sepreresnet1202_cifar100 or weight_count == 19587788) assert (model != sepreresnet1202_svhn or weight_count == 19581938) if __name__ == "__main__": _test()
24,762
37.511664
119
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/danet.py
""" DANet for image segmentation, implemented in TensorFlow. Original paper: 'Dual Attention Network for Scene Segmentation,' https://arxiv.org/abs/1809.02983. """ __all__ = ['DANet', 'danet_resnetd50b_cityscapes', 'danet_resnetd101b_cityscapes'] import os import tensorflow as tf import tensorflow.keras.layers as nn from tensorflow.python.keras import initializers from tensorflow.python.keras.engine.input_spec import InputSpec from .common import conv1x1, conv3x3_block, is_channels_first, interpolate_im, get_im_size from .resnetd import resnetd50b, resnetd101b class ScaleBlock(nn.Layer): """ Simple scale block. Parameters: ---------- alpha_initializer : str, default 'zeros' Initializer function for the weights. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, alpha_initializer="zeros", data_format="channels_last", **kwargs): super(ScaleBlock, self).__init__(**kwargs) self.data_format = data_format self.alpha_initializer = initializers.get(alpha_initializer) def build(self, input_shape): self.alpha = self.add_weight( shape=(1,), name="alpha", initializer=self.alpha_initializer, regularizer=None, constraint=None, dtype=self.dtype, trainable=True) channel_axis = (1 if is_channels_first(self.data_format) else len(input_shape) - 1) axes = {} for i in range(1, len(input_shape)): if i != channel_axis: axes[i] = input_shape[i] self.input_spec = InputSpec(ndim=len(input_shape), axes=axes) self.built = True def call(self, x, training=None): return self.alpha * x def get_config(self): config = { "alpha_initializer": initializers.serialize(self.alpha_initializer), "data_format": self.data_format, } base_config = super(ScaleBlock, self).get_config() return dict(list(base_config.items()) + list(config.items())) def compute_output_shape(self, input_shape): return input_shape class PosAttBlock(nn.Layer): """ Position attention block from 'Dual Attention Network for Scene Segmentation,' https://arxiv.org/abs/1809.02983. It captures long-range spatial contextual information. Parameters: ---------- channels : int Number of channels. reduction : int, default 8 Squeeze reduction value. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, reduction=8, data_format="channels_last", **kwargs): super(PosAttBlock, self).__init__(**kwargs) self.data_format = data_format mid_channels = channels // reduction self.query_conv = conv1x1( in_channels=channels, out_channels=mid_channels, use_bias=True, data_format=data_format, name="query_conv") self.key_conv = conv1x1( in_channels=channels, out_channels=mid_channels, use_bias=True, data_format=data_format, name="key_conv") self.value_conv = conv1x1( in_channels=channels, out_channels=channels, use_bias=True, data_format=data_format, name="value_conv") self.scale = ScaleBlock( data_format=data_format, name="scale") self.softmax = nn.Softmax(axis=-1) def call(self, x, training=None): proj_query = self.query_conv(x) proj_key = self.key_conv(x) proj_value = self.value_conv(x) if not is_channels_first(self.data_format): proj_query = tf.transpose(proj_query, perm=(0, 3, 1, 2)) proj_key = tf.transpose(proj_key, perm=(0, 3, 1, 2)) proj_value = tf.transpose(proj_value, perm=(0, 3, 1, 2)) batch, channels, height, width = proj_query.shape proj_query = tf.reshape(proj_query, shape=(batch, -1, height * width)) proj_key = tf.reshape(proj_key, shape=(batch, -1, height * width)) proj_value = tf.reshape(proj_value, shape=(batch, -1, height * width)) energy = tf.keras.backend.batch_dot(tf.transpose(proj_query, perm=(0, 2, 1)), proj_key) w = self.softmax(energy) y = tf.keras.backend.batch_dot(proj_value, tf.transpose(w, perm=(0, 2, 1))) y = tf.reshape(y, shape=(batch, -1, height, width)) if not is_channels_first(self.data_format): y = tf.transpose(y, perm=(0, 2, 3, 1)) y = self.scale(y, training=training) + x return y class ChaAttBlock(nn.Layer): """ Channel attention block from 'Dual Attention Network for Scene Segmentation,' https://arxiv.org/abs/1809.02983. It explicitly models interdependencies between channels. Parameters: ---------- data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, data_format="channels_last", **kwargs): super(ChaAttBlock, self).__init__(**kwargs) self.data_format = data_format self.scale = ScaleBlock( data_format=data_format, name="scale") self.softmax = nn.Softmax(axis=-1) def call(self, x, training=None): proj_query = x proj_key = x proj_value = x if not is_channels_first(self.data_format): proj_query = tf.transpose(proj_query, perm=(0, 3, 1, 2)) proj_key = tf.transpose(proj_key, perm=(0, 3, 1, 2)) proj_value = tf.transpose(proj_value, perm=(0, 3, 1, 2)) batch, channels, height, width = proj_query.shape proj_query = tf.reshape(proj_query, shape=(batch, -1, height * width)) proj_key = tf.reshape(proj_key, shape=(batch, -1, height * width)) proj_value = tf.reshape(proj_value, shape=(batch, -1, height * width)) energy = tf.keras.backend.batch_dot(proj_query, tf.transpose(proj_key, perm=(0, 2, 1))) energy_new = tf.broadcast_to(tf.math.reduce_max(energy, axis=-1, keepdims=True), shape=energy.shape) - energy w = self.softmax(energy_new) y = tf.keras.backend.batch_dot(w, proj_value) y = tf.reshape(y, shape=(batch, -1, height, width)) if not is_channels_first(self.data_format): y = tf.transpose(y, perm=(0, 2, 3, 1)) y = self.scale(y, training=training) + x return y class DANetHeadBranch(nn.Layer): """ DANet head branch. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. pose_att : bool, default True Whether to use position attention instead of channel one. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, pose_att=True, data_format="channels_last", **kwargs): super(DANetHeadBranch, self).__init__(**kwargs) mid_channels = in_channels // 4 dropout_rate = 0.1 self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv1") if pose_att: self.att = PosAttBlock( mid_channels, data_format=data_format, name="att") else: self.att = ChaAttBlock( data_format=data_format, name="att") self.conv2 = conv3x3_block( in_channels=mid_channels, out_channels=mid_channels, data_format=data_format, name="conv2") self.conv3 = conv1x1( in_channels=mid_channels, out_channels=out_channels, use_bias=True, data_format=data_format, name="conv3") self.dropout = nn.Dropout( rate=dropout_rate, name="dropout") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.att(x, training=training) y = self.conv2(x, training=training) x = self.conv3(y) x = self.dropout(x, training=training) return x, y class DANetHead(nn.Layer): """ DANet head block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(DANetHead, self).__init__(**kwargs) mid_channels = in_channels // 4 dropout_rate = 0.1 self.branch_pa = DANetHeadBranch( in_channels=in_channels, out_channels=out_channels, pose_att=True, data_format=data_format, name="branch_pa") self.branch_ca = DANetHeadBranch( in_channels=in_channels, out_channels=out_channels, pose_att=False, data_format=data_format, name="branch_ca") self.conv = conv1x1( in_channels=mid_channels, out_channels=out_channels, use_bias=True, data_format=data_format, name="conv") self.dropout = nn.Dropout( rate=dropout_rate, name="dropout") def call(self, x, training=None): pa_x, pa_y = self.branch_pa(x, training=training) ca_x, ca_y = self.branch_ca(x, training=training) y = pa_y + ca_y x = self.conv(y) x = self.dropout(x, training=training) return x, pa_x, ca_x class DANet(tf.keras.Model): """ DANet model from 'Dual Attention Network for Scene Segmentation,' https://arxiv.org/abs/1809.02983. 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 19 Number of segmentation classes. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, backbone, backbone_out_channels=2048, aux=False, fixed_size=True, in_channels=3, in_size=(480, 480), classes=19, data_format="channels_last", **kwargs): super(DANet, 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 self.data_format = data_format self.backbone = backbone self.head = DANetHead( in_channels=backbone_out_channels, out_channels=classes, data_format=data_format, name="head") def call(self, x, training=None): in_size = self.in_size if self.fixed_size else get_im_size(x, data_format=self.data_format) x, _ = self.backbone(x, training=training) x, y, z = self.head(x, training=training) x = interpolate_im(x, out_size=in_size, data_format=self.data_format) if self.aux: y = interpolate_im(y, out_size=in_size, data_format=self.data_format) z = interpolate_im(z, out_size=in_size, data_format=self.data_format) return x, y, z else: return x def get_danet(backbone, classes, aux=False, model_name=None, data_format="channels_last", pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create DANet 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ net = DANet( backbone=backbone, classes=classes, aux=aux, data_format=data_format, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root), by_name=True, skip_mismatch=True) return net def danet_resnetd50b_cityscapes(pretrained_backbone=False, classes=19, aux=True, data_format="channels_last", **kwargs): """ DANet model on the base of ResNet(D)-50b for Cityscapes from 'Dual Attention Network for Scene Segmentation,' https://arxiv.org/abs/1809.02983. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_danet(backbone=backbone, classes=classes, aux=aux, model_name="danet_resnetd50b_cityscapes", data_format=data_format, **kwargs) def danet_resnetd101b_cityscapes(pretrained_backbone=False, classes=19, aux=True, data_format="channels_last", **kwargs): """ DANet model on the base of ResNet(D)-101b for Cityscapes from 'Dual Attention Network for Scene Segmentation,' https://arxiv.org/abs/1809.02983. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = resnetd101b(pretrained=pretrained_backbone, ordinary_init=False, bends=(3,), data_format=data_format).features del backbone.children[-1] return get_danet(backbone=backbone, classes=classes, aux=aux, model_name="danet_resnetd101b_cityscapes", data_format=data_format, **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" in_size = (480, 480) aux = False pretrained = False models = [ danet_resnetd50b_cityscapes, danet_resnetd101b_cityscapes, ] for model in models: net = model(pretrained=pretrained, in_size=in_size, aux=aux, data_format=data_format) batch = 14 classes = 19 x = tf.random.normal((batch, 3, in_size[0], in_size[1]) if is_channels_first(data_format) else (batch, in_size[0], in_size[1], 3)) ys = net(x) y = ys[0] if aux else ys assert (y.shape[0] == x.shape[0]) if is_channels_first(data_format): assert ((y.shape[1] == classes) and (y.shape[2] == x.shape[2]) and (y.shape[3] == x.shape[3])) else: assert ((y.shape[3] == classes) and (y.shape[1] == x.shape[1]) and (y.shape[2] == x.shape[2])) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != danet_resnetd50b_cityscapes or weight_count == 47586427) assert (model != danet_resnetd101b_cityscapes or weight_count == 66578555) if __name__ == "__main__": _test()
18,175
34.156673
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/mobilenetv2.py
""" MobileNetV2 for ImageNet-1K, implemented in TensorFlow. Original paper: 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,' https://arxiv.org/abs/1801.04381. """ __all__ = ['MobileNetV2', 'mobilenetv2_w1', 'mobilenetv2_w3d4', 'mobilenetv2_wd2', 'mobilenetv2_wd4', 'mobilenetv2b_w1', 'mobilenetv2b_w3d4', 'mobilenetv2b_wd2', 'mobilenetv2b_wd4'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import ReLU6, conv1x1, conv1x1_block, conv3x3_block, dwconv3x3_block, SimpleSequential, flatten,\ is_channels_first class LinearBottleneck(nn.Layer): """ So-called 'Linear Bottleneck' layer. It is used as a MobileNetV2 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. expansion : bool Whether do expansion of channels. remove_exp_conv : bool Whether to remove expansion convolution. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, expansion, remove_exp_conv, data_format="channels_last", **kwargs): super(LinearBottleneck, self).__init__(**kwargs) self.residual = (in_channels == out_channels) and (strides == 1) mid_channels = in_channels * 6 if expansion else in_channels self.use_exp_conv = (expansion or (not remove_exp_conv)) if self.use_exp_conv: self.conv1 = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, activation=ReLU6(), data_format=data_format, name="conv1") self.conv2 = dwconv3x3_block( in_channels=mid_channels, out_channels=mid_channels, strides=strides, activation=ReLU6(), data_format=data_format, name="conv2") self.conv3 = conv1x1_block( in_channels=mid_channels, out_channels=out_channels, activation=None, data_format=data_format, name="conv3") def call(self, x, training=None): if self.residual: identity = x if self.use_exp_conv: x = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.conv3(x, training=training) if self.residual: x = x + identity return x class MobileNetV2(tf.keras.Model): """ MobileNetV2 model from 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,' https://arxiv.org/abs/1801.04381. 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. remove_exp_conv : bool Whether to remove expansion convolution. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, final_block_channels, remove_exp_conv, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(MobileNetV2, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(conv3x3_block( in_channels=in_channels, out_channels=init_block_channels, strides=2, activation=ReLU6(), data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) for j, out_channels in enumerate(channels_per_stage): strides = 2 if (j == 0) and (i != 0) else 1 expansion = (i != 0) or (j != 0) stage.add(LinearBottleneck( in_channels=in_channels, out_channels=out_channels, strides=strides, expansion=expansion, remove_exp_conv=remove_exp_conv, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(conv1x1_block( in_channels=in_channels, out_channels=final_block_channels, activation=ReLU6(), data_format=data_format, name="final_block")) in_channels = final_block_channels self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = conv1x1( in_channels=in_channels, out_channels=classes, use_bias=False, data_format=data_format, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = self.output1(x) x = flatten(x, self.data_format) return x def get_mobilenetv2(width_scale, remove_exp_conv=False, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create MobileNetV2 model with specific parameters. Parameters: ---------- width_scale : float Scale factor for width of layers. remove_exp_conv : bool, default False Whether to remove expansion convolution. 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ init_block_channels = 32 final_block_channels = 1280 layers = [1, 2, 3, 4, 3, 3, 1] downsample = [0, 1, 1, 1, 0, 1, 0] channels_per_layers = [16, 24, 32, 64, 96, 160, 320] from functools import reduce channels = reduce(lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]], zip(channels_per_layers, layers, downsample), [[]]) 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) if width_scale > 1.0: final_block_channels = int(final_block_channels * width_scale) net = MobileNetV2( channels=channels, init_block_channels=init_block_channels, final_block_channels=final_block_channels, remove_exp_conv=remove_exp_conv, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def mobilenetv2_w1(**kwargs): """ 1.0 MobileNetV2-224 model from 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,' https://arxiv.org/abs/1801.04381. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mobilenetv2(width_scale=1.0, model_name="mobilenetv2_w1", **kwargs) def mobilenetv2_w3d4(**kwargs): """ 0.75 MobileNetV2-224 model from 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,' https://arxiv.org/abs/1801.04381. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mobilenetv2(width_scale=0.75, model_name="mobilenetv2_w3d4", **kwargs) def mobilenetv2_wd2(**kwargs): """ 0.5 MobileNetV2-224 model from 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,' https://arxiv.org/abs/1801.04381. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mobilenetv2(width_scale=0.5, model_name="mobilenetv2_wd2", **kwargs) def mobilenetv2_wd4(**kwargs): """ 0.25 MobileNetV2-224 model from 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,' https://arxiv.org/abs/1801.04381. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mobilenetv2(width_scale=0.25, model_name="mobilenetv2_wd4", **kwargs) def mobilenetv2b_w1(**kwargs): """ 1.0 MobileNetV2b-224 model from 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,' https://arxiv.org/abs/1801.04381. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mobilenetv2(width_scale=1.0, remove_exp_conv=True, model_name="mobilenetv2b_w1", **kwargs) def mobilenetv2b_w3d4(**kwargs): """ 0.75 MobileNetV2b-224 model from 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,' https://arxiv.org/abs/1801.04381. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mobilenetv2(width_scale=0.75, remove_exp_conv=True, model_name="mobilenetv2b_w3d4", **kwargs) def mobilenetv2b_wd2(**kwargs): """ 0.5 MobileNetV2b-224 model from 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,' https://arxiv.org/abs/1801.04381. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mobilenetv2(width_scale=0.5, remove_exp_conv=True, model_name="mobilenetv2b_wd2", **kwargs) def mobilenetv2b_wd4(**kwargs): """ 0.25 MobileNetV2-224 model from 'MobileNetV2: Inverted Residuals and Linear Bottlenecks,' https://arxiv.org/abs/1801.04381. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mobilenetv2(width_scale=0.25, remove_exp_conv=True, model_name="mobilenetv2b_wd4", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" pretrained = False models = [ mobilenetv2_w1, mobilenetv2_w3d4, mobilenetv2_wd2, mobilenetv2_wd4, mobilenetv2b_w1, mobilenetv2b_w3d4, mobilenetv2b_wd2, mobilenetv2b_wd4, ] for model in models: net = model(pretrained=pretrained) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != mobilenetv2_w1 or weight_count == 3504960) assert (model != mobilenetv2_w3d4 or weight_count == 2627592) assert (model != mobilenetv2_wd2 or weight_count == 1964736) assert (model != mobilenetv2_wd4 or weight_count == 1516392) assert (model != mobilenetv2b_w1 or weight_count == 3503872) assert (model != mobilenetv2b_w3d4 or weight_count == 2626968) assert (model != mobilenetv2b_wd2 or weight_count == 1964448) assert (model != mobilenetv2b_wd4 or weight_count == 1516312) if __name__ == "__main__": _test()
13,837
34.121827
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/squeezenet.py
""" SqueezeNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size,' https://arxiv.org/abs/1602.07360. """ __all__ = ['SqueezeNet', 'squeezenet_v1_0', 'squeezenet_v1_1', 'squeezeresnet_v1_0', 'squeezeresnet_v1_1'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import get_channel_axis, Conv2d, MaxPool2d, SimpleSequential, flatten class FireConv(nn.Layer): """ SqueezeNet 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. padding : int or tuple/list of 2 int Padding value for convolution layer. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, padding, data_format="channels_last", **kwargs): super(FireConv, self).__init__(**kwargs) self.conv = Conv2d( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, padding=padding, data_format=data_format, name="conv") self.activ = nn.ReLU() def call(self, x): x = self.conv(x) x = self.activ(x) return x class FireUnit(nn.Layer): """ SqueezeNet unit, so-called 'Fire' unit. Parameters: ---------- in_channels : int Number of input channels. squeeze_channels : int Number of output channels for squeeze convolution blocks. expand1x1_channels : int Number of output channels for expand 1x1 convolution blocks. expand3x3_channels : int Number of output channels for expand 3x3 convolution blocks. residual : bool Whether use residual connection. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, squeeze_channels, expand1x1_channels, expand3x3_channels, residual, data_format="channels_last", **kwargs): super(FireUnit, self).__init__(**kwargs) self.residual = residual self.data_format = data_format self.squeeze = FireConv( in_channels=in_channels, out_channels=squeeze_channels, kernel_size=1, padding=0, data_format=data_format, name="squeeze") self.expand1x1 = FireConv( in_channels=squeeze_channels, out_channels=expand1x1_channels, kernel_size=1, padding=0, data_format=data_format, name="expand1x1") self.expand3x3 = FireConv( in_channels=squeeze_channels, out_channels=expand3x3_channels, kernel_size=3, padding=1, data_format=data_format, name="expand3x3") def call(self, x): if self.residual: identity = x x = self.squeeze(x) y1 = self.expand1x1(x) y2 = self.expand3x3(x) out = tf.concat([y1, y2], axis=get_channel_axis(self.data_format)) if self.residual: out = out + identity return out class SqueezeInitBlock(nn.Layer): """ SqueezeNet 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, data_format="channels_last", **kwargs): super(SqueezeInitBlock, self).__init__(**kwargs) self.conv = Conv2d( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, strides=2, data_format=data_format, name="conv") self.activ = nn.ReLU() def call(self, x): x = self.conv(x) x = self.activ(x) return x class SqueezeNet(tf.keras.Model): """ SqueezeNet model from 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size,' https://arxiv.org/abs/1602.07360. Parameters: ---------- channels : list of list of int Number of output channels for each unit. residuals : bool Whether to use residual units. init_block_kernel_size : int or tuple/list of 2 int The dimensions of the convolution window for the initial unit. init_block_channels : int Number of output channels for the initial unit. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, residuals, init_block_kernel_size, init_block_channels, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(SqueezeNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(SqueezeInitBlock( in_channels=in_channels, out_channels=init_block_channels, kernel_size=init_block_kernel_size, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) stage.add(MaxPool2d( pool_size=3, strides=2, ceil_mode=True, data_format=data_format, name="pool{}".format(i + 1))) for j, out_channels in enumerate(channels_per_stage): expand_channels = out_channels // 2 squeeze_channels = out_channels // 8 stage.add(FireUnit( in_channels=in_channels, squeeze_channels=squeeze_channels, expand1x1_channels=expand_channels, expand3x3_channels=expand_channels, residual=((residuals is not None) and (residuals[i][j] == 1)), data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(nn.Dropout( rate=0.5, name="dropout")) self.output1 = SimpleSequential(name="output1") self.output1.add(Conv2d( in_channels=in_channels, out_channels=classes, kernel_size=1, data_format=data_format, name="final_conv")) self.output1.add(nn.ReLU()) self.output1.add(nn.AveragePooling2D( pool_size=13, strides=1, data_format=data_format, name="final_pool")) def call(self, x, training=None): x = self.features(x, training=training) x = self.output1(x) x = flatten(x, self.data_format) return x def get_squeezenet(version, residual=False, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create SqueezeNet model with specific parameters. Parameters: ---------- version : str Version of SqueezeNet ('1.0' or '1.1'). residual : bool, default False Whether to use residual connections. 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if version == "1.0": channels = [[128, 128, 256], [256, 384, 384, 512], [512]] residuals = [[0, 1, 0], [1, 0, 1, 0], [1]] init_block_kernel_size = 7 init_block_channels = 96 elif version == "1.1": channels = [[128, 128], [256, 256], [384, 384, 512, 512]] residuals = [[0, 1], [0, 1], [0, 1, 0, 1]] init_block_kernel_size = 3 init_block_channels = 64 else: raise ValueError("Unsupported SqueezeNet version {}".format(version)) if not residual: residuals = None net = SqueezeNet( channels=channels, residuals=residuals, init_block_kernel_size=init_block_kernel_size, 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def squeezenet_v1_0(**kwargs): """ SqueezeNet 'vanilla' model from 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size,' https://arxiv.org/abs/1602.07360. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_squeezenet(version="1.0", residual=False, model_name="squeezenet_v1_0", **kwargs) def squeezenet_v1_1(**kwargs): """ SqueezeNet v1.1 model from 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size,' https://arxiv.org/abs/1602.07360. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_squeezenet(version="1.1", residual=False, model_name="squeezenet_v1_1", **kwargs) def squeezeresnet_v1_0(**kwargs): """ SqueezeNet model with residual connections from 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size,' https://arxiv.org/abs/1602.07360. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_squeezenet(version="1.0", residual=True, model_name="squeezeresnet_v1_0", **kwargs) def squeezeresnet_v1_1(**kwargs): """ SqueezeNet v1.1 model with residual connections from 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size,' https://arxiv.org/abs/1602.07360. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_squeezenet(version="1.1", residual=True, model_name="squeezeresnet_v1_1", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K pretrained = False models = [ squeezenet_v1_0, squeezenet_v1_1, squeezeresnet_v1_0, squeezeresnet_v1_1, ] for model in models: net = model(pretrained=pretrained) batch = 14 x = tf.random.normal((batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != squeezenet_v1_0 or weight_count == 1248424) assert (model != squeezenet_v1_1 or weight_count == 1235496) assert (model != squeezeresnet_v1_0 or weight_count == 1248424) assert (model != squeezeresnet_v1_1 or weight_count == 1235496) if __name__ == "__main__": _test()
13,417
32.212871
118
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/vgg.py
""" VGG for ImageNet-1K, implemented in TensorFlow. Original paper: 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. """ __all__ = ['VGG', 'vgg11', 'vgg13', 'vgg16', 'vgg19', 'bn_vgg11', 'bn_vgg13', 'bn_vgg16', 'bn_vgg19', 'bn_vgg11b', 'bn_vgg13b', 'bn_vgg16b', 'bn_vgg19b'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv3x3_block, MaxPool2d, SimpleSequential, flatten class VGGDense(nn.Layer): """ VGG 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(VGGDense, self).__init__(**kwargs) self.fc = nn.Dense( units=out_channels, input_dim=in_channels, name="fc") self.activ = nn.ReLU() self.dropout = nn.Dropout( rate=0.5, name="dropout") def call(self, x, training=None): x = self.fc(x) x = self.activ(x) x = self.dropout(x, training=training) return x class VGGOutputBlock(nn.Layer): """ VGG 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(VGGOutputBlock, self).__init__(**kwargs) mid_channels = 4096 self.fc1 = VGGDense( in_channels=in_channels, out_channels=mid_channels, name="fc1") self.fc2 = VGGDense( in_channels=mid_channels, out_channels=mid_channels, name="fc2") self.fc3 = nn.Dense( units=classes, input_dim=mid_channels, name="fc3") def call(self, x, training=None): x = self.fc1(x, training=training) x = self.fc2(x, training=training) x = self.fc3(x) return x class VGG(tf.keras.Model): """ VGG models from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- channels : list of list of int Number of output channels for each unit. use_bias : bool, default True Whether the convolution layer uses a bias vector. use_bn : bool, default False Whether to use 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, use_bias=True, use_bn=False, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(VGG, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) for j, out_channels in enumerate(channels_per_stage): stage.add(conv3x3_block( in_channels=in_channels, out_channels=out_channels, use_bias=use_bias, use_bn=use_bn, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels stage.add(MaxPool2d( pool_size=2, strides=2, padding=0, data_format=data_format, name="pool{}".format(i + 1))) self.features.add(stage) self.output1 = VGGOutputBlock( in_channels=(in_channels * 7 * 7), classes=classes, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_vgg(blocks, use_bias=True, use_bn=False, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create VGG model with specific parameters. Parameters: ---------- blocks : int Number of blocks. use_bias : bool, default True Whether the convolution layer uses a bias vector. use_bn : bool, default False Whether to use BatchNorm 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if blocks == 11: layers = [1, 1, 2, 2, 2] elif blocks == 13: layers = [2, 2, 2, 2, 2] elif blocks == 16: layers = [2, 2, 3, 3, 3] elif blocks == 19: layers = [2, 2, 4, 4, 4] else: raise ValueError("Unsupported VGG with number of blocks: {}".format(blocks)) channels_per_layers = [64, 128, 256, 512, 512] channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)] net = VGG( channels=channels, use_bias=use_bias, 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def vgg11(**kwargs): """ VGG-11 model from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_vgg(blocks=11, model_name="vgg11", **kwargs) def vgg13(**kwargs): """ VGG-13 model from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_vgg(blocks=13, model_name="vgg13", **kwargs) def vgg16(**kwargs): """ VGG-16 model from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_vgg(blocks=16, model_name="vgg16", **kwargs) def vgg19(**kwargs): """ VGG-19 model from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_vgg(blocks=19, model_name="vgg19", **kwargs) def bn_vgg11(**kwargs): """ VGG-11 model with batch normalization from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_vgg(blocks=11, use_bias=False, use_bn=True, model_name="bn_vgg11", **kwargs) def bn_vgg13(**kwargs): """ VGG-13 model with batch normalization from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_vgg(blocks=13, use_bias=False, use_bn=True, model_name="bn_vgg13", **kwargs) def bn_vgg16(**kwargs): """ VGG-16 model with batch normalization from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_vgg(blocks=16, use_bias=False, use_bn=True, model_name="bn_vgg16", **kwargs) def bn_vgg19(**kwargs): """ VGG-19 model with batch normalization from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_vgg(blocks=19, use_bias=False, use_bn=True, model_name="bn_vgg19", **kwargs) def bn_vgg11b(**kwargs): """ VGG-11 model with batch normalization and biases in convolution layers from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_vgg(blocks=11, use_bias=True, use_bn=True, model_name="bn_vgg11b", **kwargs) def bn_vgg13b(**kwargs): """ VGG-13 model with batch normalization and biases in convolution layers from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_vgg(blocks=13, use_bias=True, use_bn=True, model_name="bn_vgg13b", **kwargs) def bn_vgg16b(**kwargs): """ VGG-16 model with batch normalization and biases in convolution layers from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_vgg(blocks=16, use_bias=True, use_bn=True, model_name="bn_vgg16b", **kwargs) def bn_vgg19b(**kwargs): """ VGG-19 model with batch normalization and biases in convolution layers from 'Very Deep Convolutional Networks for Large-Scale Image Recognition,' https://arxiv.org/abs/1409.1556. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_vgg(blocks=19, use_bias=True, use_bn=True, model_name="bn_vgg19b", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K pretrained = False models = [ vgg11, vgg13, vgg16, vgg19, bn_vgg11, bn_vgg13, bn_vgg16, bn_vgg19, bn_vgg11b, bn_vgg13b, bn_vgg16b, bn_vgg19b, ] for model in models: net = model(pretrained=pretrained) batch = 14 x = tf.random.normal((batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != vgg11 or weight_count == 132863336) assert (model != vgg13 or weight_count == 133047848) assert (model != vgg16 or weight_count == 138357544) assert (model != vgg19 or weight_count == 143667240) assert (model != bn_vgg11 or weight_count == 132866088) assert (model != bn_vgg13 or weight_count == 133050792) assert (model != bn_vgg16 or weight_count == 138361768) assert (model != bn_vgg19 or weight_count == 143672744) assert (model != bn_vgg11b or weight_count == 132868840) assert (model != bn_vgg13b or weight_count == 133053736) assert (model != bn_vgg16b or weight_count == 138365992) assert (model != bn_vgg19b or weight_count == 143678248) if __name__ == "__main__": _test()
14,207
31
117
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/resnet_cub.py
""" ResNet for CUB-200-2011, implemented in TensorFlow. Original paper: 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. """ __all__ = ['resnet10_cub', 'resnet12_cub', 'resnet14_cub', 'resnetbc14b_cub', 'resnet16_cub', 'resnet18_cub', 'resnet26_cub', 'resnetbc26b_cub', 'resnet34_cub', 'resnetbc38b_cub', 'resnet50_cub', 'resnet50b_cub', 'resnet101_cub', 'resnet101b_cub', 'resnet152_cub', 'resnet152b_cub', 'resnet200_cub', 'resnet200b_cub'] from .common import is_channels_first from .resnet import get_resnet def resnet10_cub(classes=200, **kwargs): """ ResNet-10 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=10, model_name="resnet10_cub", **kwargs) def resnet12_cub(classes=200, **kwargs): """ ResNet-12 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=12, model_name="resnet12_cub", **kwargs) def resnet14_cub(classes=200, **kwargs): """ ResNet-14 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=14, model_name="resnet14_cub", **kwargs) def resnetbc14b_cub(classes=200, **kwargs): """ ResNet-BC-14b model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model (bottleneck compressed). Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=14, bottleneck=True, conv1_stride=False, model_name="resnetbc14b_cub", **kwargs) def resnet16_cub(classes=200, **kwargs): """ ResNet-16 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=16, model_name="resnet16_cub", **kwargs) def resnet18_cub(classes=200, **kwargs): """ ResNet-18 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=18, model_name="resnet18_cub", **kwargs) def resnet26_cub(classes=200, **kwargs): """ ResNet-26 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=26, bottleneck=False, model_name="resnet26_cub", **kwargs) def resnetbc26b_cub(classes=200, **kwargs): """ ResNet-BC-26b model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model (bottleneck compressed). Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=26, bottleneck=True, conv1_stride=False, model_name="resnetbc26b_cub", **kwargs) def resnet34_cub(classes=200, **kwargs): """ ResNet-34 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=34, model_name="resnet34_cub", **kwargs) def resnetbc38b_cub(classes=200, **kwargs): """ ResNet-BC-38b model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model (bottleneck compressed). Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=38, bottleneck=True, conv1_stride=False, model_name="resnetbc38b_cub", **kwargs) def resnet50_cub(classes=200, **kwargs): """ ResNet-50 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=50, model_name="resnet50_cub", **kwargs) def resnet50b_cub(classes=200, **kwargs): """ ResNet-50 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=50, conv1_stride=False, model_name="resnet50b_cub", **kwargs) def resnet101_cub(classes=200, **kwargs): """ ResNet-101 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=101, model_name="resnet101_cub", **kwargs) def resnet101b_cub(classes=200, **kwargs): """ ResNet-101 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=101, conv1_stride=False, model_name="resnet101b_cub", **kwargs) def resnet152_cub(classes=200, **kwargs): """ ResNet-152 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=152, model_name="resnet152_cub", **kwargs) def resnet152b_cub(classes=200, **kwargs): """ ResNet-152 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=152, conv1_stride=False, model_name="resnet152b_cub", **kwargs) def resnet200_cub(classes=200, **kwargs): """ ResNet-200 model for CUB-200-2011 from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=200, model_name="resnet200_cub", **kwargs) def resnet200b_cub(classes=200, **kwargs): """ ResNet-200 model with stride at the second convolution in bottleneck block from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. It's an experimental model. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_resnet(classes=classes, blocks=200, conv1_stride=False, model_name="resnet200b_cub", **kwargs) def _test(): import numpy as np import tensorflow as tf import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" pretrained = False models = [ resnet10_cub, resnet12_cub, resnet14_cub, resnetbc14b_cub, resnet16_cub, resnet18_cub, resnet26_cub, resnetbc26b_cub, resnet34_cub, resnetbc38b_cub, resnet50_cub, resnet50b_cub, resnet101_cub, resnet101b_cub, resnet152_cub, resnet152b_cub, resnet200_cub, resnet200b_cub, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 200)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != resnet10_cub or weight_count == 5008392) assert (model != resnet12_cub or weight_count == 5082376) assert (model != resnet14_cub or weight_count == 5377800) assert (model != resnetbc14b_cub or weight_count == 8425736) assert (model != resnet16_cub or weight_count == 6558472) assert (model != resnet18_cub or weight_count == 11279112) assert (model != resnet26_cub or weight_count == 17549832) assert (model != resnetbc26b_cub or weight_count == 14355976) assert (model != resnet34_cub or weight_count == 21387272) assert (model != resnetbc38b_cub or weight_count == 20286216) assert (model != resnet50_cub or weight_count == 23917832) assert (model != resnet50b_cub or weight_count == 23917832) assert (model != resnet101_cub or weight_count == 42909960) assert (model != resnet101b_cub or weight_count == 42909960) assert (model != resnet152_cub or weight_count == 58553608) assert (model != resnet152b_cub or weight_count == 58553608) assert (model != resnet200_cub or weight_count == 63034632) assert (model != resnet200b_cub or weight_count == 63034632) if __name__ == "__main__": _test()
14,084
35.489637
117
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/bagnet.py
""" BagNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'Approximating CNNs with Bag-of-local-Features models works surprisingly well on ImageNet,' https://openreview.net/pdf?id=SkfMWhAqYQ. """ __all__ = ['BagNet', 'bagnet9', 'bagnet17', 'bagnet33'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1, conv1x1_block, conv3x3_block, ConvBlock, SimpleSequential, flatten, is_channels_first class BagNetBottleneck(nn.Layer): """ BagNet bottleneck block for residual path in BagNet unit. 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 of the second convolution. strides : int or tuple/list of 2 int Strides of the second convolution. bottleneck_factor : int, default 4 Bottleneck factor. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, strides, bottleneck_factor=4, data_format="channels_last", **kwargs): super(BagNetBottleneck, self).__init__(**kwargs) mid_channels = out_channels // bottleneck_factor self.conv1 = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv1") self.conv2 = ConvBlock( in_channels=mid_channels, out_channels=mid_channels, kernel_size=kernel_size, strides=strides, padding=0, data_format=data_format, name="conv2") self.conv3 = conv1x1_block( in_channels=mid_channels, out_channels=out_channels, activation=None, data_format=data_format, name="conv3") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.conv3(x, training=training) return x class BagNetUnit(nn.Layer): """ BagNet unit. 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 of the second body convolution. strides : int or tuple/list of 2 int Strides of the second body convolution. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, strides, data_format="channels_last", **kwargs): super(BagNetUnit, self).__init__(**kwargs) self.data_format = data_format self.resize_identity = (in_channels != out_channels) or (strides != 1) self.body = BagNetBottleneck( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, strides=strides, data_format=data_format, name="body") if self.resize_identity: self.identity_conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, strides=strides, activation=None, data_format=data_format, name="identity_conv") self.activ = nn.ReLU() def call(self, x, training=None): if self.resize_identity: identity = self.identity_conv(x, training=training) else: identity = x x = self.body(x, training=training) if x.shape[-2] != identity.shape[-2]: diff = identity.shape[-2] - x.shape[-2] if is_channels_first(self.data_format): identity = identity[:, :, :-diff, :-diff] else: identity = identity[:, :-diff, :-diff, :] x = x + identity x = self.activ(x) return x class BagNetInitBlock(nn.Layer): """ BagNet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(BagNetInitBlock, self).__init__(**kwargs) self.conv1 = conv1x1( in_channels=in_channels, out_channels=out_channels, data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=out_channels, out_channels=out_channels, padding=0, data_format=data_format, name="conv2") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) return x class BagNet(tf.keras.Model): """ BagNet model from 'Approximating CNNs with Bag-of-local-Features models works surprisingly well on ImageNet,' https://openreview.net/pdf?id=SkfMWhAqYQ. 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_pool_size : int Size of the pooling windows for final pool. normal_kernel_sizes : list of int Count of the first units with 3x3 convolution window size for each stage. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, final_pool_size, normal_kernel_sizes, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(BagNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(BagNetInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) for j, out_channels in enumerate(channels_per_stage): strides = 2 if (j == 0) and (i != len(channels) - 1) else 1 kernel_size = 3 if j < normal_kernel_sizes[i] else 1 stage.add(BagNetUnit( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, strides=strides, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(nn.AveragePooling2D( pool_size=final_pool_size, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_bagnet(field, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create BagNet 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ layers = [3, 4, 6, 3] if field == 9: normal_kernel_sizes = [1, 1, 0, 0] final_pool_size = 27 elif field == 17: normal_kernel_sizes = [1, 1, 1, 0] final_pool_size = 26 elif field == 33: normal_kernel_sizes = [1, 1, 1, 1] final_pool_size = 24 else: raise ValueError("Unsupported BagNet with field: {}".format(field)) init_block_channels = 64 channels_per_layers = [256, 512, 1024, 2048] channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)] net = BagNet( channels=channels, init_block_channels=init_block_channels, final_pool_size=final_pool_size, normal_kernel_sizes=normal_kernel_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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def bagnet9(**kwargs): """ BagNet-9 model from 'Approximating CNNs with Bag-of-local-Features models works surprisingly well on ImageNet,' https://openreview.net/pdf?id=SkfMWhAqYQ. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_bagnet(field=9, model_name="bagnet9", **kwargs) def bagnet17(**kwargs): """ BagNet-17 model from 'Approximating CNNs with Bag-of-local-Features models works surprisingly well on ImageNet,' https://openreview.net/pdf?id=SkfMWhAqYQ. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_bagnet(field=17, model_name="bagnet17", **kwargs) def bagnet33(**kwargs): """ BagNet-33 model from 'Approximating CNNs with Bag-of-local-Features models works surprisingly well on ImageNet,' https://openreview.net/pdf?id=SkfMWhAqYQ. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_bagnet(field=33, model_name="bagnet33", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ bagnet9, bagnet17, bagnet33, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != bagnet9 or weight_count == 15688744) assert (model != bagnet17 or weight_count == 16213032) assert (model != bagnet33 or weight_count == 18310184) if __name__ == "__main__": _test()
12,719
31.868217
116
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/airnet.py
""" AirNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'Attention Inspiring Receptive-Fields Network for Learning Invariant Representations,' https://ieeexplore.ieee.org/document/8510896. """ __all__ = ['AirNet', 'airnet50_1x64d_r2', 'airnet50_1x64d_r16', 'airnet101_1x64d_r2', 'AirBlock', 'AirInitBlock'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1_block, conv3x3_block, MaxPool2d, SimpleSequential, flatten, is_channels_first class AirBlock(nn.Layer): """ AirNet attention block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. groups : int, default 1 Number of groups. ratio: int, default 2 Air compression ratio. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, groups=1, ratio=2, data_format="channels_last", **kwargs): super(AirBlock, self).__init__(**kwargs) assert (out_channels % ratio == 0) mid_channels = out_channels // ratio self.conv1 = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv1") self.pool = MaxPool2d( pool_size=3, strides=2, padding=1, data_format=data_format, name="pool") self.conv2 = conv3x3_block( in_channels=mid_channels, out_channels=mid_channels, groups=groups, data_format=data_format, name="conv2") self.conv3 = conv1x1_block( in_channels=mid_channels, out_channels=out_channels, activation=None, data_format=data_format, name="conv3") self.sigmoid = tf.nn.sigmoid self.upsample = nn.UpSampling2D( size=(2, 2), data_format=data_format, interpolation="bilinear", name="upsample") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.pool(x) x = self.conv2(x, training=training) x = self.upsample(x) x = self.conv3(x, training=training) x = self.sigmoid(x) return x class AirBottleneck(nn.Layer): """ AirNet bottleneck block for residual path in AirNet 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. ratio: int Air compression ratio. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, ratio, data_format="channels_last", **kwargs): super(AirBottleneck, self).__init__(**kwargs) mid_channels = out_channels // 4 self.use_air_block = (strides == 1 and mid_channels < 512) self.conv1 = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=mid_channels, out_channels=mid_channels, strides=strides, data_format=data_format, name="conv2") self.conv3 = conv1x1_block( in_channels=mid_channels, out_channels=out_channels, activation=None, data_format=data_format, name="conv3") if self.use_air_block: self.air = AirBlock( in_channels=in_channels, out_channels=mid_channels, ratio=ratio, data_format=data_format, name="air") def call(self, x, training=None): if self.use_air_block: att = self.air(x, training=training) x = self.conv1(x, training=training) x = self.conv2(x, training=training) if self.use_air_block: x = x * att x = self.conv3(x, training=training) return x class AirUnit(nn.Layer): """ AirNet 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. ratio: int Air compression ratio. in_size : tuple of 2 int Spatial size of the input tensor for the bilinear upsampling operation. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, ratio, data_format="channels_last", **kwargs): super(AirUnit, self).__init__(**kwargs) self.resize_identity = (in_channels != out_channels) or (strides != 1) self.body = AirBottleneck( in_channels=in_channels, out_channels=out_channels, strides=strides, ratio=ratio, data_format=data_format, name="body") if self.resize_identity: self.identity_conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, strides=strides, activation=None, data_format=data_format, name="identity_conv") self.activ = nn.ReLU() def call(self, x, training=None): if self.resize_identity: identity = self.identity_conv(x, training=training) else: identity = x x = self.body(x, training=training) x = x + identity x = self.activ(x) return x class AirInitBlock(nn.Layer): """ AirNet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(AirInitBlock, self).__init__(**kwargs) mid_channels = out_channels // 2 self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels, strides=2, data_format=data_format, name="conv1") self.conv2 = conv3x3_block( in_channels=mid_channels, out_channels=mid_channels, data_format=data_format, name="conv2") self.conv3 = conv3x3_block( in_channels=mid_channels, out_channels=out_channels, data_format=data_format, name="conv3") self.pool = MaxPool2d( pool_size=3, strides=2, padding=1, data_format=data_format, name="pool") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.conv3(x, training=training) x = self.pool(x) return x class AirNet(tf.keras.Model): """ AirNet model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant Representations,' https://ieeexplore.ieee.org/document/8510896. 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. ratio: int Air compression ratio. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, ratio, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(AirNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(AirInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(AirUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, ratio=ratio, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_airnet(blocks, base_channels, ratio, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create AirNet model with specific parameters. Parameters: ---------- blocks : int Number of blocks. base_channels: int Base number of channels. ratio: int Air compression ratio. 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if blocks == 50: layers = [3, 4, 6, 3] elif blocks == 101: layers = [3, 4, 23, 3] else: raise ValueError("Unsupported AirNet with number of blocks: {}".format(blocks)) bottleneck_expansion = 4 init_block_channels = base_channels channels_per_layers = [base_channels * (2 ** i) * bottleneck_expansion for i in range(len(layers))] channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)] net = AirNet( channels=channels, init_block_channels=init_block_channels, ratio=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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def airnet50_1x64d_r2(**kwargs): """ AirNet50-1x64d (r=2) model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant Representations,' https://ieeexplore.ieee.org/document/8510896. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_airnet(blocks=50, base_channels=64, ratio=2, model_name="airnet50_1x64d_r2", **kwargs) def airnet50_1x64d_r16(**kwargs): """ AirNet50-1x64d (r=16) model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant Representations,' https://ieeexplore.ieee.org/document/8510896. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_airnet(blocks=50, base_channels=64, ratio=16, model_name="airnet50_1x64d_r16", **kwargs) def airnet101_1x64d_r2(**kwargs): """ AirNet101-1x64d (r=2) model from 'Attention Inspiring Receptive-Fields Network for Learning Invariant Representations,' https://ieeexplore.ieee.org/document/8510896. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_airnet(blocks=101, base_channels=64, ratio=2, model_name="airnet101_1x64d_r2", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ airnet50_1x64d_r2, airnet50_1x64d_r16, airnet101_1x64d_r2, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != airnet50_1x64d_r2 or weight_count == 27425864) assert (model != airnet50_1x64d_r16 or weight_count == 25714952) assert (model != airnet101_1x64d_r2 or weight_count == 51727432) if __name__ == "__main__": _test()
14,996
31.182403
115
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/mnasnet.py
""" MnasNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'MnasNet: Platform-Aware Neural Architecture Search for Mobile,' https://arxiv.org/abs/1807.11626. """ __all__ = ['MnasNet', 'mnasnet_b1', 'mnasnet_a1', 'mnasnet_small'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import round_channels, conv1x1_block, conv3x3_block, dwconv3x3_block, dwconv5x5_block, SEBlock,\ SimpleSequential, flatten class DwsExpSEResUnit(nn.Layer): """ Depthwise separable expanded residual unit with SE-block. Here it used as MnasNet unit. 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 second convolution layer. use_kernel3 : bool, default True Whether to use 3x3 (instead of 5x5) kernel. exp_factor : int, default 1 Expansion factor for each unit. se_factor : int, default 0 SE reduction factor for each unit. use_skip : bool, default True Whether to use skip connection. activation : str, default 'relu' Activation function or name of activation function. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides=1, use_kernel3=True, exp_factor=1, se_factor=0, use_skip=True, activation="relu", data_format="channels_last", **kwargs): super(DwsExpSEResUnit, 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 self.use_se = se_factor > 0 mid_channels = exp_factor * in_channels dwconv_block_fn = dwconv3x3_block if use_kernel3 else dwconv5x5_block if self.use_exp_conv: self.exp_conv = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, activation=activation, data_format=data_format, name="exp_conv") self.dw_conv = dwconv_block_fn( in_channels=mid_channels, out_channels=mid_channels, strides=strides, activation=activation, data_format=data_format, name="dw_conv") if self.use_se: self.se = SEBlock( channels=mid_channels, reduction=(exp_factor * se_factor), round_mid=False, mid_activation=activation, data_format=data_format, name="se") self.pw_conv = conv1x1_block( in_channels=mid_channels, out_channels=out_channels, activation=None, data_format=data_format, name="pw_conv") def call(self, x, training=None): if self.residual: identity = x if self.use_exp_conv: x = self.exp_conv(x, training=training) x = self.dw_conv(x, training=training) if self.use_se: x = self.se(x) x = self.pw_conv(x, training=training) if self.residual: x = x + identity return x class MnasInitBlock(nn.Layer): """ MnasNet 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. use_skip : bool Whether to use skip connection in the second block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, mid_channels, use_skip, data_format="channels_last", **kwargs): super(MnasInitBlock, self).__init__(**kwargs) self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels, strides=2, data_format=data_format, name="conv1") self.conv2 = DwsExpSEResUnit( in_channels=mid_channels, out_channels=out_channels, use_skip=use_skip, data_format=data_format, name="conv2") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) return x class MnasFinalBlock(nn.Layer): """ MnasNet 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. use_skip : bool Whether to use skip connection in the second block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, mid_channels, use_skip, data_format="channels_last", **kwargs): super(MnasFinalBlock, self).__init__(**kwargs) self.conv1 = DwsExpSEResUnit( in_channels=in_channels, out_channels=mid_channels, exp_factor=6, use_skip=use_skip, data_format=data_format, name="conv1") self.conv2 = conv1x1_block( in_channels=mid_channels, out_channels=out_channels, data_format=data_format, name="conv2") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) return x class MnasNet(tf.keras.Model): """ MnasNet model from 'MnasNet: Platform-Aware Neural Architecture Search for Mobile,' https://arxiv.org/abs/1807.11626. 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. se_factors : list of list of int SE reduction factor for each unit. init_block_use_skip : bool Whether to use skip connection in the initial unit. final_block_use_skip : bool Whether to use skip connection in the final block of the feature extractor. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, final_block_channels, kernels3, exp_factors, se_factors, init_block_use_skip, final_block_use_skip, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(MnasNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(MnasInitBlock( in_channels=in_channels, out_channels=init_block_channels[1], mid_channels=init_block_channels[0], use_skip=init_block_use_skip, data_format=data_format, name="init_block")) in_channels = init_block_channels[1] for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) 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] se_factor = se_factors[i][j] stage.add(DwsExpSEResUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, use_kernel3=use_kernel3, exp_factor=exp_factor, se_factor=se_factor, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(MnasFinalBlock( in_channels=in_channels, out_channels=final_block_channels[1], mid_channels=final_block_channels[0], use_skip=final_block_use_skip, data_format=data_format, name="final_block")) in_channels = final_block_channels[1] self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_mnasnet(version, width_scale, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create MnasNet model with specific parameters. Parameters: ---------- version : str Version of MobileNetV3 ('b1', 'a1' or 'small'). 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if version == "b1": init_block_channels = [32, 16] final_block_channels = [320, 1280] channels = [[24, 24, 24], [40, 40, 40], [80, 80, 80, 96, 96], [192, 192, 192, 192]] kernels3 = [[1, 1, 1], [0, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 0]] exp_factors = [[3, 3, 3], [3, 3, 3], [6, 6, 6, 6, 6], [6, 6, 6, 6]] se_factors = [[0, 0, 0], [0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0]] init_block_use_skip = False final_block_use_skip = False elif version == "a1": init_block_channels = [32, 16] final_block_channels = [320, 1280] channels = [[24, 24], [40, 40, 40], [80, 80, 80, 80, 112, 112], [160, 160, 160]] kernels3 = [[1, 1], [0, 0, 0], [1, 1, 1, 1, 1, 1], [0, 0, 0]] exp_factors = [[6, 6], [3, 3, 3], [6, 6, 6, 6, 6, 6], [6, 6, 6]] se_factors = [[0, 0], [4, 4, 4], [0, 0, 0, 0, 4, 4], [4, 4, 4]] init_block_use_skip = False final_block_use_skip = True elif version == "small": init_block_channels = [8, 8] final_block_channels = [144, 1280] channels = [[16], [16, 16], [32, 32, 32, 32, 32, 32, 32], [88, 88, 88]] kernels3 = [[1], [1, 1], [0, 0, 0, 0, 1, 1, 1], [0, 0, 0]] exp_factors = [[3], [6, 6], [6, 6, 6, 6, 6, 6, 6], [6, 6, 6]] se_factors = [[0], [0, 0], [4, 4, 4, 4, 4, 4, 4], [4, 4, 4]] init_block_use_skip = True final_block_use_skip = True else: raise ValueError("Unsupported MnasNet version {}".format(version)) if width_scale != 1.0: channels = [[round_channels(cij * width_scale) for cij in ci] for ci in channels] init_block_channels = round_channels(init_block_channels * width_scale) net = MnasNet( channels=channels, init_block_channels=init_block_channels, final_block_channels=final_block_channels, kernels3=kernels3, exp_factors=exp_factors, se_factors=se_factors, init_block_use_skip=init_block_use_skip, final_block_use_skip=final_block_use_skip, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def mnasnet_b1(**kwargs): """ MnasNet-B1 model from 'MnasNet: Platform-Aware Neural Architecture Search for Mobile,' https://arxiv.org/abs/1807.11626. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mnasnet(version="b1", width_scale=1.0, model_name="mnasnet_b1", **kwargs) def mnasnet_a1(**kwargs): """ MnasNet-A1 model from 'MnasNet: Platform-Aware Neural Architecture Search for Mobile,' https://arxiv.org/abs/1807.11626. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mnasnet(version="a1", width_scale=1.0, model_name="mnasnet_a1", **kwargs) def mnasnet_small(**kwargs): """ MnasNet-Small model from 'MnasNet: Platform-Aware Neural Architecture Search for Mobile,' https://arxiv.org/abs/1807.11626. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mnasnet(version="small", width_scale=1.0, model_name="mnasnet_small", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K pretrained = False models = [ mnasnet_b1, mnasnet_a1, mnasnet_small, ] for model in models: net = model(pretrained=pretrained) batch = 14 x = tf.random.normal((batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != mnasnet_b1 or weight_count == 4383312) assert (model != mnasnet_a1 or weight_count == 3887038) assert (model != mnasnet_small or weight_count == 2030264) if __name__ == "__main__": _test()
15,818
33.997788
118
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/pyramidnet_cifar.py
""" PyramidNet for CIFAR/SVHN, implemented in TensorFlow. Original paper: 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. """ __all__ = ['CIFARPyramidNet', 'pyramidnet110_a48_cifar10', 'pyramidnet110_a48_cifar100', 'pyramidnet110_a48_svhn', 'pyramidnet110_a84_cifar10', 'pyramidnet110_a84_cifar100', 'pyramidnet110_a84_svhn', 'pyramidnet110_a270_cifar10', 'pyramidnet110_a270_cifar100', 'pyramidnet110_a270_svhn', 'pyramidnet164_a270_bn_cifar10', 'pyramidnet164_a270_bn_cifar100', 'pyramidnet164_a270_bn_svhn', 'pyramidnet200_a240_bn_cifar10', 'pyramidnet200_a240_bn_cifar100', 'pyramidnet200_a240_bn_svhn', 'pyramidnet236_a220_bn_cifar10', 'pyramidnet236_a220_bn_cifar100', 'pyramidnet236_a220_bn_svhn', 'pyramidnet272_a200_bn_cifar10', 'pyramidnet272_a200_bn_cifar100', 'pyramidnet272_a200_bn_svhn'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv3x3_block, SimpleSequential, flatten, is_channels_first from .preresnet import PreResActivation from .pyramidnet import PyrUnit class CIFARPyramidNet(tf.keras.Model): """ PyramidNet model for CIFAR from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, bottleneck, in_channels=3, in_size=(32, 32), classes=10, data_format="channels_last", **kwargs): super(CIFARPyramidNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(conv3x3_block( in_channels=in_channels, out_channels=init_block_channels, activation=None, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(PyrUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, bottleneck=bottleneck, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(PreResActivation( in_channels=in_channels, data_format=data_format, name="post_activ")) self.features.add(nn.AveragePooling2D( pool_size=8, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_pyramidnet_cifar(classes, blocks, alpha, bottleneck, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create PyramidNet for CIFAR model with specific parameters. Parameters: ---------- classes : int Number of classification classes. blocks : int Number of blocks. alpha : int PyramidNet's alpha value. 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. root : str, default '~/.tensorflow/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 init_block_channels = 16 growth_add = float(alpha) / float(sum(layers)) from functools import reduce channels = reduce( lambda xi, yi: xi + [[(i + 1) * growth_add + xi[-1][-1] for i in list(range(yi))]], layers, [[init_block_channels]])[1:] channels = [[int(round(cij)) for cij in ci] for ci in channels] if bottleneck: channels = [[cij * 4 for cij in ci] for ci in channels] net = CIFARPyramidNet( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def pyramidnet110_a48_cifar10(classes=10, **kwargs): """ PyramidNet-110 (a=48) model for CIFAR-10 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=110, alpha=48, bottleneck=False, model_name="pyramidnet110_a48_cifar10", **kwargs) def pyramidnet110_a48_cifar100(classes=100, **kwargs): """ PyramidNet-110 (a=48) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=110, alpha=48, bottleneck=False, model_name="pyramidnet110_a48_cifar100", **kwargs) def pyramidnet110_a48_svhn(classes=10, **kwargs): """ PyramidNet-110 (a=48) model for SVHN from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=110, alpha=48, bottleneck=False, model_name="pyramidnet110_a48_svhn", **kwargs) def pyramidnet110_a84_cifar10(classes=10, **kwargs): """ PyramidNet-110 (a=84) model for CIFAR-10 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=110, alpha=84, bottleneck=False, model_name="pyramidnet110_a84_cifar10", **kwargs) def pyramidnet110_a84_cifar100(classes=100, **kwargs): """ PyramidNet-110 (a=84) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=110, alpha=84, bottleneck=False, model_name="pyramidnet110_a84_cifar100", **kwargs) def pyramidnet110_a84_svhn(classes=10, **kwargs): """ PyramidNet-110 (a=84) model for SVHN from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=110, alpha=84, bottleneck=False, model_name="pyramidnet110_a84_svhn", **kwargs) def pyramidnet110_a270_cifar10(classes=10, **kwargs): """ PyramidNet-110 (a=270) model for CIFAR-10 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=110, alpha=270, bottleneck=False, model_name="pyramidnet110_a270_cifar10", **kwargs) def pyramidnet110_a270_cifar100(classes=100, **kwargs): """ PyramidNet-110 (a=270) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=110, alpha=270, bottleneck=False, model_name="pyramidnet110_a270_cifar100", **kwargs) def pyramidnet110_a270_svhn(classes=10, **kwargs): """ PyramidNet-110 (a=270) model for SVHN from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=110, alpha=270, bottleneck=False, model_name="pyramidnet110_a270_svhn", **kwargs) def pyramidnet164_a270_bn_cifar10(classes=10, **kwargs): """ PyramidNet-164 (a=270, bn) model for CIFAR-10 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=164, alpha=270, bottleneck=True, model_name="pyramidnet164_a270_bn_cifar10", **kwargs) def pyramidnet164_a270_bn_cifar100(classes=100, **kwargs): """ PyramidNet-164 (a=270, bn) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=164, alpha=270, bottleneck=True, model_name="pyramidnet164_a270_bn_cifar100", **kwargs) def pyramidnet164_a270_bn_svhn(classes=10, **kwargs): """ PyramidNet-164 (a=270, bn) model for SVHN from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=164, alpha=270, bottleneck=True, model_name="pyramidnet164_a270_bn_svhn", **kwargs) def pyramidnet200_a240_bn_cifar10(classes=10, **kwargs): """ PyramidNet-200 (a=240, bn) model for CIFAR-10 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=200, alpha=240, bottleneck=True, model_name="pyramidnet200_a240_bn_cifar10", **kwargs) def pyramidnet200_a240_bn_cifar100(classes=100, **kwargs): """ PyramidNet-200 (a=240, bn) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=200, alpha=240, bottleneck=True, model_name="pyramidnet200_a240_bn_cifar100", **kwargs) def pyramidnet200_a240_bn_svhn(classes=10, **kwargs): """ PyramidNet-200 (a=240, bn) model for SVHN from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=200, alpha=240, bottleneck=True, model_name="pyramidnet200_a240_bn_svhn", **kwargs) def pyramidnet236_a220_bn_cifar10(classes=10, **kwargs): """ PyramidNet-236 (a=220, bn) model for CIFAR-10 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=236, alpha=220, bottleneck=True, model_name="pyramidnet236_a220_bn_cifar10", **kwargs) def pyramidnet236_a220_bn_cifar100(classes=100, **kwargs): """ PyramidNet-236 (a=220, bn) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=236, alpha=220, bottleneck=True, model_name="pyramidnet236_a220_bn_cifar100", **kwargs) def pyramidnet236_a220_bn_svhn(classes=10, **kwargs): """ PyramidNet-236 (a=220, bn) model for SVHN from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=236, alpha=220, bottleneck=True, model_name="pyramidnet236_a220_bn_svhn", **kwargs) def pyramidnet272_a200_bn_cifar10(classes=10, **kwargs): """ PyramidNet-272 (a=200, bn) model for CIFAR-10 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=272, alpha=200, bottleneck=True, model_name="pyramidnet272_a200_bn_cifar10", **kwargs) def pyramidnet272_a200_bn_cifar100(classes=100, **kwargs): """ PyramidNet-272 (a=200, bn) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=272, alpha=200, bottleneck=True, model_name="pyramidnet272_a200_bn_cifar100", **kwargs) def pyramidnet272_a200_bn_svhn(classes=10, **kwargs): """ PyramidNet-272 (a=200, bn) model for SVHN from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet_cifar( classes=classes, blocks=272, alpha=200, bottleneck=True, model_name="pyramidnet272_a200_bn_svhn", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" pretrained = False models = [ (pyramidnet110_a48_cifar10, 10), (pyramidnet110_a48_cifar100, 100), (pyramidnet110_a48_svhn, 10), (pyramidnet110_a84_cifar10, 10), (pyramidnet110_a84_cifar100, 100), (pyramidnet110_a84_svhn, 10), (pyramidnet110_a270_cifar10, 10), (pyramidnet110_a270_cifar100, 100), (pyramidnet110_a270_svhn, 10), (pyramidnet164_a270_bn_cifar10, 10), (pyramidnet164_a270_bn_cifar100, 100), (pyramidnet164_a270_bn_svhn, 10), (pyramidnet200_a240_bn_cifar10, 10), (pyramidnet200_a240_bn_cifar100, 100), (pyramidnet200_a240_bn_svhn, 10), (pyramidnet236_a220_bn_cifar10, 10), (pyramidnet236_a220_bn_cifar100, 100), (pyramidnet236_a220_bn_svhn, 10), (pyramidnet272_a200_bn_cifar10, 10), (pyramidnet272_a200_bn_cifar100, 100), (pyramidnet272_a200_bn_svhn, 10), ] for model, classes in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 32, 32) if is_channels_first(data_format) else (batch, 32, 32, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, classes)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != pyramidnet110_a48_cifar10 or weight_count == 1772706) assert (model != pyramidnet110_a48_cifar100 or weight_count == 1778556) assert (model != pyramidnet110_a48_svhn or weight_count == 1772706) assert (model != pyramidnet110_a84_cifar10 or weight_count == 3904446) assert (model != pyramidnet110_a84_cifar100 or weight_count == 3913536) assert (model != pyramidnet110_a84_svhn or weight_count == 3904446) assert (model != pyramidnet110_a270_cifar10 or weight_count == 28485477) assert (model != pyramidnet110_a270_cifar100 or weight_count == 28511307) assert (model != pyramidnet110_a270_svhn or weight_count == 28485477) assert (model != pyramidnet164_a270_bn_cifar10 or weight_count == 27216021) assert (model != pyramidnet164_a270_bn_cifar100 or weight_count == 27319071) assert (model != pyramidnet164_a270_bn_svhn or weight_count == 27216021) assert (model != pyramidnet200_a240_bn_cifar10 or weight_count == 26752702) assert (model != pyramidnet200_a240_bn_cifar100 or weight_count == 26844952) assert (model != pyramidnet200_a240_bn_svhn or weight_count == 26752702) assert (model != pyramidnet236_a220_bn_cifar10 or weight_count == 26969046) assert (model != pyramidnet236_a220_bn_cifar100 or weight_count == 27054096) assert (model != pyramidnet236_a220_bn_svhn or weight_count == 26969046) assert (model != pyramidnet272_a200_bn_cifar10 or weight_count == 26210842) assert (model != pyramidnet272_a200_bn_cifar100 or weight_count == 26288692) assert (model != pyramidnet272_a200_bn_svhn or weight_count == 26210842) if __name__ == "__main__": _test()
24,103
32.711888
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/preresnet_cifar.py
""" PreResNet for CIFAR/SVHN, implemented in TensorFlow. Original papers: 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. """ __all__ = ['CIFARPreResNet', 'preresnet20_cifar10', 'preresnet20_cifar100', 'preresnet20_svhn', 'preresnet56_cifar10', 'preresnet56_cifar100', 'preresnet56_svhn', 'preresnet110_cifar10', 'preresnet110_cifar100', 'preresnet110_svhn', 'preresnet164bn_cifar10', 'preresnet164bn_cifar100', 'preresnet164bn_svhn', 'preresnet272bn_cifar10', 'preresnet272bn_cifar100', 'preresnet272bn_svhn', 'preresnet542bn_cifar10', 'preresnet542bn_cifar100', 'preresnet542bn_svhn', 'preresnet1001_cifar10', 'preresnet1001_cifar100', 'preresnet1001_svhn', 'preresnet1202_cifar10', 'preresnet1202_cifar100', 'preresnet1202_svhn'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv3x3, SimpleSequential, flatten, is_channels_first from .preresnet import PreResUnit, PreResActivation class CIFARPreResNet(tf.keras.Model): """ PreResNet model for CIFAR from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, bottleneck, in_channels=3, in_size=(32, 32), classes=10, data_format="channels_last", **kwargs): super(CIFARPreResNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(conv3x3( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(PreResUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, bottleneck=bottleneck, conv1_stride=False, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(PreResActivation( in_channels=in_channels, data_format=data_format, name="post_activ")) self.features.add(nn.AveragePooling2D( pool_size=8, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_preresnet_cifar(classes, blocks, bottleneck, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create 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. root : str, default '~/.tensorflow/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 = CIFARPreResNet( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def preresnet20_cifar10(classes=10, **kwargs): """ PreResNet-20 model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="preresnet20_cifar10", **kwargs) def preresnet20_cifar100(classes=100, **kwargs): """ PreResNet-20 model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="preresnet20_cifar100", **kwargs) def preresnet20_svhn(classes=10, **kwargs): """ PreResNet-20 model for SVHN from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="preresnet20_svhn", **kwargs) def preresnet56_cifar10(classes=10, **kwargs): """ PreResNet-56 model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name="preresnet56_cifar10", **kwargs) def preresnet56_cifar100(classes=100, **kwargs): """ PreResNet-56 model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name="preresnet56_cifar100", **kwargs) def preresnet56_svhn(classes=10, **kwargs): """ PreResNet-56 model for SVHN from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=56, bottleneck=False, model_name="preresnet56_svhn", **kwargs) def preresnet110_cifar10(classes=10, **kwargs): """ PreResNet-110 model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name="preresnet110_cifar10", **kwargs) def preresnet110_cifar100(classes=100, **kwargs): """ PreResNet-110 model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name="preresnet110_cifar100", **kwargs) def preresnet110_svhn(classes=10, **kwargs): """ PreResNet-110 model for SVHN from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=110, bottleneck=False, model_name="preresnet110_svhn", **kwargs) def preresnet164bn_cifar10(classes=10, **kwargs): """ PreResNet-164(BN) model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name="preresnet164bn_cifar10", **kwargs) def preresnet164bn_cifar100(classes=100, **kwargs): """ PreResNet-164(BN) model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name="preresnet164bn_cifar100", **kwargs) def preresnet164bn_svhn(classes=10, **kwargs): """ PreResNet-164(BN) model for SVHN from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=164, bottleneck=True, model_name="preresnet164bn_svhn", **kwargs) def preresnet272bn_cifar10(classes=10, **kwargs): """ PreResNet-272(BN) model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name="preresnet272bn_cifar10", **kwargs) def preresnet272bn_cifar100(classes=100, **kwargs): """ PreResNet-272(BN) model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name="preresnet272bn_cifar100", **kwargs) def preresnet272bn_svhn(classes=10, **kwargs): """ PreResNet-272(BN) model for SVHN from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=272, bottleneck=True, model_name="preresnet272bn_svhn", **kwargs) def preresnet542bn_cifar10(classes=10, **kwargs): """ PreResNet-542(BN) model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name="preresnet542bn_cifar10", **kwargs) def preresnet542bn_cifar100(classes=100, **kwargs): """ PreResNet-542(BN) model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name="preresnet542bn_cifar100", **kwargs) def preresnet542bn_svhn(classes=10, **kwargs): """ PreResNet-542(BN) model for SVHN from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=542, bottleneck=True, model_name="preresnet542bn_svhn", **kwargs) def preresnet1001_cifar10(classes=10, **kwargs): """ PreResNet-1001 model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="preresnet1001_cifar10", **kwargs) def preresnet1001_cifar100(classes=100, **kwargs): """ PreResNet-1001 model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="preresnet1001_cifar100", **kwargs) def preresnet1001_svhn(classes=10, **kwargs): """ PreResNet-1001 model for SVHN from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=1001, bottleneck=True, model_name="preresnet1001_svhn", **kwargs) def preresnet1202_cifar10(classes=10, **kwargs): """ PreResNet-1202 model for CIFAR-10 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name="preresnet1202_cifar10", **kwargs) def preresnet1202_cifar100(classes=100, **kwargs): """ PreResNet-1202 model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name="preresnet1202_cifar100", **kwargs) def preresnet1202_svhn(classes=10, **kwargs): """ PreResNet-1202 model for SVHN from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_preresnet_cifar(classes=classes, blocks=1202, bottleneck=False, model_name="preresnet1202_svhn", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" pretrained = False models = [ (preresnet20_cifar10, 10), (preresnet20_cifar100, 100), (preresnet20_svhn, 10), (preresnet56_cifar10, 10), (preresnet56_cifar100, 100), (preresnet56_svhn, 10), (preresnet110_cifar10, 10), (preresnet110_cifar100, 100), (preresnet110_svhn, 10), (preresnet164bn_cifar10, 10), (preresnet164bn_cifar100, 100), (preresnet164bn_svhn, 10), (preresnet272bn_cifar10, 10), (preresnet272bn_cifar100, 100), (preresnet272bn_svhn, 10), (preresnet542bn_cifar10, 10), (preresnet542bn_cifar100, 100), (preresnet542bn_svhn, 10), (preresnet1001_cifar10, 10), (preresnet1001_cifar100, 100), (preresnet1001_svhn, 10), (preresnet1202_cifar10, 10), (preresnet1202_cifar100, 100), (preresnet1202_svhn, 10), ] for model, classes in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 32, 32) if is_channels_first(data_format) else (batch, 32, 32, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, classes)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != preresnet20_cifar10 or weight_count == 272282) assert (model != preresnet20_cifar100 or weight_count == 278132) assert (model != preresnet20_svhn or weight_count == 272282) assert (model != preresnet56_cifar10 or weight_count == 855578) assert (model != preresnet56_cifar100 or weight_count == 861428) assert (model != preresnet56_svhn or weight_count == 855578) assert (model != preresnet110_cifar10 or weight_count == 1730522) assert (model != preresnet110_cifar100 or weight_count == 1736372) assert (model != preresnet110_svhn or weight_count == 1730522) assert (model != preresnet164bn_cifar10 or weight_count == 1703258) assert (model != preresnet164bn_cifar100 or weight_count == 1726388) assert (model != preresnet164bn_svhn or weight_count == 1703258) assert (model != preresnet272bn_cifar10 or weight_count == 2816090) assert (model != preresnet272bn_cifar100 or weight_count == 2839220) assert (model != preresnet272bn_svhn or weight_count == 2816090) assert (model != preresnet542bn_cifar10 or weight_count == 5598170) assert (model != preresnet542bn_cifar100 or weight_count == 5621300) assert (model != preresnet542bn_svhn or weight_count == 5598170) assert (model != preresnet1001_cifar10 or weight_count == 10327706) assert (model != preresnet1001_cifar100 or weight_count == 10350836) assert (model != preresnet1001_svhn or weight_count == 10327706) assert (model != preresnet1202_cifar10 or weight_count == 19423834) assert (model != preresnet1202_cifar100 or weight_count == 19429684) assert (model != preresnet1202_svhn or weight_count == 19423834) if __name__ == "__main__": _test()
24,758
36.11994
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/alphapose_coco.py
""" AlphaPose for COCO Keypoint, implemented in TensorFlow. Original paper: 'RMPE: Regional Multi-person Pose Estimation,' https://arxiv.org/abs/1612.00137. """ __all__ = ['AlphaPose', 'alphapose_fastseresnet101b_coco'] import os import tensorflow as tf from .common import conv3x3, PixelShuffle, DucBlock, HeatmapMaxDetBlock, SimpleSequential, is_channels_first from .fastseresnet import fastseresnet101b class AlphaPose(tf.keras.Model): """ AlphaPose model from 'RMPE: Regional Multi-person Pose Estimation,' https://arxiv.org/abs/1612.00137. 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. return_heatmap : bool, default False Whether to return only heatmap. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, backbone, backbone_out_channels, channels, return_heatmap=False, in_channels=3, in_size=(256, 192), keypoints=17, data_format="channels_last", **kwargs): super(AlphaPose, self).__init__(**kwargs) assert (in_channels == 3) self.in_size = in_size self.keypoints = keypoints self.return_heatmap = return_heatmap self.data_format = data_format self.backbone = backbone self.backbone._name = "backbone" self.decoder = SimpleSequential(name="decoder") self.decoder.add(PixelShuffle( scale_factor=2, data_format=data_format, name="init_block")) in_channels = backbone_out_channels // 4 for i, out_channels in enumerate(channels): self.decoder.add(DucBlock( in_channels=in_channels, out_channels=out_channels, scale_factor=2, data_format=data_format, name="unit{}".format(i + 1))) in_channels = out_channels self.decoder.add(conv3x3( in_channels=in_channels, out_channels=keypoints, use_bias=True, data_format=data_format, name="final_block")) self.heatmap_max_det = HeatmapMaxDetBlock( data_format=data_format, name="heatmap_max_det") def call(self, x, training=None): x = self.backbone(x, training=training) heatmap = self.decoder(x, training=training) if self.return_heatmap or not tf.executing_eagerly(): return heatmap else: keypoints = self.heatmap_max_det(heatmap) return keypoints def get_alphapose(backbone, backbone_out_channels, keypoints, model_name=None, data_format="channels_last", pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create AlphaPose 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. model_name : str or None, default None Model name for loading pretrained model. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ channels = [256, 128] net = AlphaPose( backbone=backbone, backbone_out_channels=backbone_out_channels, channels=channels, keypoints=keypoints, data_format=data_format, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def alphapose_fastseresnet101b_coco(pretrained_backbone=False, keypoints=17, data_format="channels_last", **kwargs): """ AlphaPose model on the base of ResNet-101b for COCO Keypoint from 'RMPE: Regional Multi-person Pose Estimation,' https://arxiv.org/abs/1612.00137. Parameters: ---------- pretrained_backbone : bool, default False Whether to load the pretrained weights for feature extractor. keypoints : int, default 17 Number of keypoints. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ backbone = fastseresnet101b(pretrained=pretrained_backbone, data_format=data_format).features del backbone.children[-1] return get_alphapose(backbone=backbone, backbone_out_channels=2048, keypoints=keypoints, model_name="alphapose_fastseresnet101b_coco", data_format=data_format, **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" in_size = (256, 192) keypoints = 17 return_heatmap = False pretrained = False models = [ alphapose_fastseresnet101b_coco, ] for model in models: net = model(pretrained=pretrained, in_size=in_size, return_heatmap=return_heatmap, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, in_size[0], in_size[1]) if is_channels_first(data_format) else (batch, in_size[0], in_size[1], 3)) y = net(x) assert (y.shape[0] == batch) if return_heatmap: if is_channels_first(data_format): assert ((y.shape[1] == keypoints) and (y.shape[2] == x.shape[2] // 4) and (y.shape[3] == x.shape[3] // 4)) else: assert ((y.shape[3] == keypoints) and (y.shape[1] == x.shape[1] // 4) and (y.shape[2] == x.shape[2] // 4)) else: assert ((y.shape[1] == keypoints) and (y.shape[2] == 3)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != alphapose_fastseresnet101b_coco or weight_count == 59569873) if __name__ == "__main__": _test()
7,571
34.886256
116
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/pyramidnet.py
""" PyramidNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. """ __all__ = ['PyramidNet', 'pyramidnet101_a360', 'PyrUnit'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import Conv2d, BatchNorm, MaxPool2d, AvgPool2d, pre_conv1x1_block, pre_conv3x3_block, SimpleSequential,\ flatten, is_channels_first from .preresnet import PreResActivation class PyrBlock(nn.Layer): """ Simple PyramidNet block for residual path in PyramidNet 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, data_format="channels_last", **kwargs): super(PyrBlock, self).__init__(**kwargs) self.conv1 = pre_conv3x3_block( in_channels=in_channels, out_channels=out_channels, strides=strides, activate=False, data_format=data_format, name="conv1") self.conv2 = pre_conv3x3_block( in_channels=out_channels, out_channels=out_channels, data_format=data_format, name="conv2") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) return x class PyrBottleneck(nn.Layer): """ PyramidNet bottleneck block for residual path in PyramidNet 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, data_format="channels_last", **kwargs): super(PyrBottleneck, self).__init__(**kwargs) mid_channels = out_channels // 4 self.conv1 = pre_conv1x1_block( in_channels=in_channels, out_channels=mid_channels, activate=False, data_format=data_format, name="conv1") self.conv2 = pre_conv3x3_block( in_channels=mid_channels, out_channels=mid_channels, strides=strides, data_format=data_format, name="conv2") self.conv3 = pre_conv1x1_block( in_channels=mid_channels, out_channels=out_channels, data_format=data_format, name="conv3") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.conv3(x, training=training) return x class PyrUnit(nn.Layer): """ PyramidNet 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. bottleneck : bool Whether to use a bottleneck or simple block in units. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, bottleneck, data_format="channels_last", **kwargs): super(PyrUnit, self).__init__(**kwargs) assert (out_channels >= in_channels) self.data_format = data_format self.resize_identity = (strides != 1) self.identity_pad_width = out_channels - in_channels if bottleneck: self.body = PyrBottleneck( in_channels=in_channels, out_channels=out_channels, strides=strides, data_format=data_format, name="body") else: self.body = PyrBlock( in_channels=in_channels, out_channels=out_channels, strides=strides, data_format=data_format, name="body") self.bn = BatchNorm( data_format=data_format, name="bn") if self.resize_identity: self.identity_pool = AvgPool2d( pool_size=2, strides=strides, ceil_mode=True, data_format=data_format, name="identity_pool") def call(self, x, training=None): identity = x x = self.body(x, training=training) x = self.bn(x, training=training) if self.resize_identity: identity = self.identity_pool(identity) if self.identity_pad_width > 0: if is_channels_first(self.data_format): paddings = [[0, 0], [0, self.identity_pad_width], [0, 0], [0, 0]] else: paddings = [[0, 0], [0, 0], [0, 0], [0, self.identity_pad_width]] identity = tf.pad(identity, paddings=paddings) x = x + identity return x class PyrInitBlock(nn.Layer): """ PyramidNet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(PyrInitBlock, self).__init__(**kwargs) self.conv = Conv2d( in_channels=in_channels, out_channels=out_channels, kernel_size=7, strides=2, padding=3, use_bias=False, data_format=data_format, name="conv") self.bn = BatchNorm( data_format=data_format, name="bn") self.activ = nn.ReLU() self.pool = MaxPool2d( pool_size=3, strides=2, padding=1, data_format=data_format, name="pool") def call(self, x, training=None): x = self.conv(x) x = self.bn(x, training=training) x = self.activ(x) x = self.pool(x) return x class PyramidNet(tf.keras.Model): """ PyramidNet model from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, bottleneck, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(PyramidNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(PyrInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(PyrUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, bottleneck=bottleneck, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(PreResActivation( in_channels=in_channels, data_format=data_format, name="post_activ")) self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_pyramidnet(blocks, alpha, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create PyramidNet model with specific parameters. Parameters: ---------- blocks : int Number of blocks. alpha : int PyramidNet's alpha 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if blocks == 10: layers = [1, 1, 1, 1] elif blocks == 12: layers = [2, 1, 1, 1] elif blocks == 14: layers = [2, 2, 1, 1] elif blocks == 16: layers = [2, 2, 2, 1] elif 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 ResNet with number of blocks: {}".format(blocks)) init_block_channels = 64 growth_add = float(alpha) / float(sum(layers)) from functools import reduce channels = reduce( lambda xi, yi: xi + [[(i + 1) * growth_add + xi[-1][-1] for i in list(range(yi))]], layers, [[init_block_channels]])[1:] channels = [[int(round(cij)) for cij in ci] for ci in channels] if blocks < 50: bottleneck = False else: bottleneck = True channels = [[cij * 4 for cij in ci] for ci in channels] net = PyramidNet( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def pyramidnet101_a360(**kwargs): """ PyramidNet-101 model from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_pyramidnet(blocks=101, alpha=360, model_name="pyramidnet101_a360", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ pyramidnet101_a360, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != pyramidnet101_a360 or weight_count == 42455070) if __name__ == "__main__": _test()
13,503
30.699531
117
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/seresnet.py
""" SE-ResNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. """ __all__ = ['SEResNet', 'seresnet10', 'seresnet12', 'seresnet14', 'seresnet16', 'seresnet18', 'seresnet26', 'seresnetbc26b', 'seresnet34', 'seresnetbc38b', 'seresnet50', 'seresnet50b', 'seresnet101', 'seresnet101b', 'seresnet152', 'seresnet152b', 'seresnet200', 'seresnet200b', 'SEResUnit', 'get_seresnet'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1_block, SEBlock, SimpleSequential, flatten from .resnet import ResBlock, ResBottleneck, ResInitBlock class SEResUnit(nn.Layer): """ 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, bottleneck, conv1_stride, data_format="channels_last", **kwargs): super(SEResUnit, self).__init__(**kwargs) self.resize_identity = (in_channels != out_channels) or (strides != 1) if bottleneck: self.body = ResBottleneck( in_channels=in_channels, out_channels=out_channels, strides=strides, conv1_stride=conv1_stride, data_format=data_format, name="body") else: self.body = ResBlock( in_channels=in_channels, out_channels=out_channels, strides=strides, data_format=data_format, name="body") 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, activation=None, data_format=data_format, name="identity_conv") self.activ = nn.ReLU() def call(self, x, training=None): if self.resize_identity: identity = self.identity_conv(x, training=training) else: identity = x x = self.body(x, training=training) x = self.se(x) x = x + identity x = self.activ(x) return x class SEResNet(tf.keras.Model): """ 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, bottleneck, conv1_stride, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(SEResNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(ResInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(SEResUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, bottleneck=bottleneck, conv1_stride=conv1_stride, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_seresnet(blocks, bottleneck=None, conv1_stride=True, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create 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. root : str, default '~/.tensorflow/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 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 = SEResNet( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def seresnet10(**kwargs): """ SE-ResNet-10 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=10, model_name="seresnet10", **kwargs) def seresnet12(**kwargs): """ SE-ResNet-12 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=12, model_name="seresnet12", **kwargs) def seresnet14(**kwargs): """ SE-ResNet-14 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=14, model_name="seresnet14", **kwargs) def seresnet16(**kwargs): """ SE-ResNet-16 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=16, model_name="seresnet16", **kwargs) def seresnet18(**kwargs): """ SE-ResNet-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=18, model_name="seresnet18", **kwargs) def seresnet26(**kwargs): """ SE-ResNet-26 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=26, bottleneck=False, model_name="seresnet26", **kwargs) def seresnetbc26b(**kwargs): """ SE-ResNet-BC-26b model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model (bottleneck compressed). Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=26, bottleneck=True, conv1_stride=False, model_name="seresnetbc26b", **kwargs) def seresnet34(**kwargs): """ SE-ResNet-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=34, model_name="seresnet34", **kwargs) def seresnetbc38b(**kwargs): """ SE-ResNet-BC-38b model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model (bottleneck compressed). Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=38, bottleneck=True, conv1_stride=False, model_name="seresnetbc38b", **kwargs) def seresnet50(**kwargs): """ SE-ResNet-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=50, model_name="seresnet50", **kwargs) def seresnet50b(**kwargs): """ SE-ResNet-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=50, conv1_stride=False, model_name="seresnet50b", **kwargs) def seresnet101(**kwargs): """ SE-ResNet-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=101, model_name="seresnet101", **kwargs) def seresnet101b(**kwargs): """ 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=101, conv1_stride=False, model_name="seresnet101b", **kwargs) def seresnet152(**kwargs): """ SE-ResNet-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=152, model_name="seresnet152", **kwargs) def seresnet152b(**kwargs): """ SE-ResNet-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=152, conv1_stride=False, model_name="seresnet152b", **kwargs) def seresnet200(**kwargs): """ SE-ResNet-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=200, model_name="seresnet200", **kwargs) def seresnet200b(**kwargs): """ SE-ResNet-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(blocks=200, conv1_stride=False, model_name="seresnet200b", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K pretrained = False models = [ seresnet10, seresnet12, seresnet14, seresnet16, seresnet18, seresnet26, seresnetbc26b, seresnet34, seresnetbc38b, seresnet50, seresnet50b, seresnet101, seresnet101b, seresnet152, seresnet152b, seresnet200, seresnet200b, ] for model in models: net = model(pretrained=pretrained) batch = 14 x = tf.random.normal((batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != seresnet10 or weight_count == 5463332) assert (model != seresnet12 or weight_count == 5537896) assert (model != seresnet14 or weight_count == 5835504) assert (model != seresnet16 or weight_count == 7024640) assert (model != seresnet18 or weight_count == 11778592) assert (model != seresnet26 or weight_count == 18093852) assert (model != seresnetbc26b or weight_count == 17395976) assert (model != seresnet34 or weight_count == 21958868) assert (model != seresnetbc38b or weight_count == 24026616) assert (model != seresnet50 or weight_count == 28088024) assert (model != seresnet50b or weight_count == 28088024) assert (model != seresnet101 or weight_count == 49326872) assert (model != seresnet101b or weight_count == 49326872) assert (model != seresnet152 or weight_count == 66821848) assert (model != seresnet152b or weight_count == 66821848) assert (model != seresnet200 or weight_count == 71835864) assert (model != seresnet200b or weight_count == 71835864) if __name__ == "__main__": _test()
19,070
32.694346
118
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/seresnet_cub.py
""" SE-ResNet for CUB-200-2011, implemented in TensorFlow. Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. """ __all__ = ['seresnet10_cub', 'seresnet12_cub', 'seresnet14_cub', 'seresnetbc14b_cub', 'seresnet16_cub', 'seresnet18_cub', 'seresnet26_cub', 'seresnetbc26b_cub', 'seresnet34_cub', 'seresnetbc38b_cub', 'seresnet50_cub', 'seresnet50b_cub', 'seresnet101_cub', 'seresnet101b_cub', 'seresnet152_cub', 'seresnet152b_cub', 'seresnet200_cub', 'seresnet200b_cub'] from .common import is_channels_first from .seresnet import get_seresnet def seresnet10_cub(classes=200, **kwargs): """ SE-ResNet-10 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=10, model_name="seresnet10_cub", **kwargs) def seresnet12_cub(classes=200, **kwargs): """ SE-ResNet-12 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=12, model_name="seresnet12_cub", **kwargs) def seresnet14_cub(classes=200, **kwargs): """ SE-ResNet-14 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=14, model_name="seresnet14_cub", **kwargs) def seresnetbc14b_cub(classes=200, **kwargs): """ SE-ResNet-BC-14b model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model (bottleneck compressed). Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=14, bottleneck=True, conv1_stride=False, model_name="seresnetbc14b_cub", **kwargs) def seresnet16_cub(classes=200, **kwargs): """ SE-ResNet-16 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=16, model_name="seresnet16_cub", **kwargs) def seresnet18_cub(classes=200, **kwargs): """ SE-ResNet-18 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=18, model_name="seresnet18_cub", **kwargs) def seresnet26_cub(classes=200, **kwargs): """ SE-ResNet-26 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=26, bottleneck=False, model_name="seresnet26_cub", **kwargs) def seresnetbc26b_cub(classes=200, **kwargs): """ SE-ResNet-BC-26b model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model (bottleneck compressed). Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=26, bottleneck=True, conv1_stride=False, model_name="seresnetbc26b_cub", **kwargs) def seresnet34_cub(classes=200, **kwargs): """ SE-ResNet-34 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=34, model_name="seresnet34_cub", **kwargs) def seresnetbc38b_cub(classes=200, **kwargs): """ SE-ResNet-BC-38b model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model (bottleneck compressed). Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=38, bottleneck=True, conv1_stride=False, model_name="seresnetbc38b_cub", **kwargs) def seresnet50_cub(classes=200, **kwargs): """ SE-ResNet-50 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=50, model_name="seresnet50_cub", **kwargs) def seresnet50b_cub(classes=200, **kwargs): """ SE-ResNet-50 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=50, conv1_stride=False, model_name="seresnet50b_cub", **kwargs) def seresnet101_cub(classes=200, **kwargs): """ SE-ResNet-101 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=101, model_name="seresnet101_cub", **kwargs) def seresnet101b_cub(classes=200, **kwargs): """ 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: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=101, conv1_stride=False, model_name="seresnet101b_cub", **kwargs) def seresnet152_cub(classes=200, **kwargs): """ SE-ResNet-152 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=152, model_name="seresnet152_cub", **kwargs) def seresnet152b_cub(classes=200, **kwargs): """ SE-ResNet-152 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=152, conv1_stride=False, model_name="seresnet152b_cub", **kwargs) def seresnet200_cub(classes=200, **kwargs): """ SE-ResNet-200 model for CUB-200-2011 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. It's an experimental model. Parameters: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=200, model_name="seresnet200_cub", **kwargs) def seresnet200b_cub(classes=200, **kwargs): """ SE-ResNet-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: ---------- classes : int, default 200 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnet(classes=classes, blocks=200, conv1_stride=False, model_name="seresnet200b_cub", **kwargs) def _test(): import numpy as np import tensorflow as tf import tensorflow.keras.backend as K data_format = "channels_last" # data_format = "channels_first" pretrained = False models = [ seresnet10_cub, seresnet12_cub, seresnet14_cub, seresnetbc14b_cub, seresnet16_cub, seresnet18_cub, seresnet26_cub, seresnetbc26b_cub, seresnet34_cub, seresnetbc38b_cub, seresnet50_cub, seresnet50b_cub, seresnet101_cub, seresnet101b_cub, seresnet152_cub, seresnet152b_cub, seresnet200_cub, seresnet200b_cub, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 200)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != seresnet10_cub or weight_count == 5052932) assert (model != seresnet12_cub or weight_count == 5127496) assert (model != seresnet14_cub or weight_count == 5425104) assert (model != seresnetbc14b_cub or weight_count == 9126136) assert (model != seresnet16_cub or weight_count == 6614240) assert (model != seresnet18_cub or weight_count == 11368192) assert (model != seresnet26_cub or weight_count == 17683452) assert (model != seresnetbc26b_cub or weight_count == 15756776) assert (model != seresnet34_cub or weight_count == 21548468) assert (model != seresnetbc38b_cub or weight_count == 22387416) assert (model != seresnet50_cub or weight_count == 26448824) assert (model != seresnet50b_cub or weight_count == 26448824) assert (model != seresnet101_cub or weight_count == 47687672) assert (model != seresnet101b_cub or weight_count == 47687672) assert (model != seresnet152_cub or weight_count == 65182648) assert (model != seresnet152b_cub or weight_count == 65182648) assert (model != seresnet200_cub or weight_count == 70196664) assert (model != seresnet200b_cub or weight_count == 70196664) if __name__ == "__main__": _test()
14,111
35.942408
120
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/densenet.py
""" DenseNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993. """ __all__ = ['DenseNet', 'densenet121', 'densenet161', 'densenet169', 'densenet201', 'DenseUnit', 'TransitionBlock'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import pre_conv1x1_block, pre_conv3x3_block, AvgPool2d, SimpleSequential, get_channel_axis, flatten from .preresnet import PreResInitBlock, PreResActivation class DenseUnit(nn.Layer): """ DenseNet unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. dropout_rate : float Parameter of Dropout layer. Faction of the input units to drop. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, dropout_rate, data_format="channels_last", **kwargs): super(DenseUnit, self).__init__(**kwargs) self.data_format = data_format self.use_dropout = (dropout_rate != 0.0) bn_size = 4 inc_channels = out_channels - in_channels mid_channels = inc_channels * bn_size self.conv1 = pre_conv1x1_block( in_channels=in_channels, out_channels=mid_channels, data_format=data_format, name="conv1") self.conv2 = pre_conv3x3_block( in_channels=mid_channels, out_channels=inc_channels, data_format=data_format, name="conv2") if self.use_dropout: self.dropout = nn.Dropout( rate=dropout_rate, name="dropout") def call(self, x, training=None): identity = x x = self.conv1(x, training=training) x = self.conv2(x, training=training) if self.use_dropout: x = self.dropout(x, training=training) x = tf.concat([identity, x], axis=get_channel_axis(self.data_format)) return x class TransitionBlock(nn.Layer): """ DenseNet's auxiliary block, which can be treated as the initial part of the DenseNet unit, triggered only in the first unit of each stage. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(TransitionBlock, self).__init__(**kwargs) self.conv = pre_conv1x1_block( in_channels=in_channels, out_channels=out_channels, data_format=data_format, name="conv") self.pool = AvgPool2d( pool_size=2, strides=2, padding=0) def call(self, x, training=None): x = self.conv(x, training=training) x = self.pool(x) return x class DenseNet(tf.keras.Model): """ DenseNet model 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. 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 (224, 224) Spatial size of the expected input image. classes : int, default 1000 Number of classification classes. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, dropout_rate=0.0, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(DenseNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(PreResInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) if i != 0: stage.add(TransitionBlock( in_channels=in_channels, out_channels=(in_channels // 2), data_format=data_format, name="trans{}".format(i + 1))) in_channels = in_channels // 2 for j, out_channels in enumerate(channels_per_stage): stage.add(DenseUnit( in_channels=in_channels, out_channels=out_channels, dropout_rate=dropout_rate, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(PreResActivation( in_channels=in_channels, data_format=data_format, name="post_activ")) self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_densenet(blocks, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create DenseNet 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if blocks == 121: init_block_channels = 64 growth_rate = 32 layers = [6, 12, 24, 16] elif blocks == 161: init_block_channels = 96 growth_rate = 48 layers = [6, 12, 36, 24] elif blocks == 169: init_block_channels = 64 growth_rate = 32 layers = [6, 12, 32, 32] elif blocks == 201: init_block_channels = 64 growth_rate = 32 layers = [6, 12, 48, 32] else: raise ValueError("Unsupported DenseNet version with number of layers {}".format(blocks)) 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 = DenseNet( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def densenet121(**kwargs): """ DenseNet-121 model from 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_densenet(blocks=121, model_name="densenet121", **kwargs) def densenet161(**kwargs): """ DenseNet-161 model from 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_densenet(blocks=161, model_name="densenet161", **kwargs) def densenet169(**kwargs): """ DenseNet-169 model from 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_densenet(blocks=169, model_name="densenet169", **kwargs) def densenet201(**kwargs): """ DenseNet-201 model from 'Densely Connected Convolutional Networks,' https://arxiv.org/abs/1608.06993. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_densenet(blocks=201, model_name="densenet201", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K pretrained = False models = [ densenet121, densenet161, densenet169, densenet201, ] for model in models: net = model(pretrained=pretrained) batch = 14 x = tf.random.normal((batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != densenet121 or weight_count == 7978856) assert (model != densenet161 or weight_count == 28681000) assert (model != densenet169 or weight_count == 14149480) assert (model != densenet201 or weight_count == 20013928) if __name__ == "__main__": _test()
11,289
32.011696
116
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/seresnext.py
""" SE-ResNeXt for ImageNet-1K, implemented in TensorFlow. Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. """ __all__ = ['SEResNeXt', 'seresnext50_32x4d', 'seresnext101_32x4d', 'seresnext101_64x4d'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import conv1x1_block, SEBlock, SimpleSequential, flatten from .resnet import ResInitBlock from .resnext import ResNeXtBottleneck class SEResNeXtUnit(nn.Layer): """ SE-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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, cardinality, bottleneck_width, data_format="channels_last", **kwargs): super(SEResNeXtUnit, self).__init__(**kwargs) self.resize_identity = (in_channels != out_channels) or (strides != 1) self.body = ResNeXtBottleneck( in_channels=in_channels, out_channels=out_channels, strides=strides, cardinality=cardinality, bottleneck_width=bottleneck_width, data_format=data_format, name="body") self.se = SEBlock( channels=out_channels, data_format=data_format, name="se") if self.resize_identity: self.identity_conv = conv1x1_block( in_channels=in_channels, out_channels=out_channels, strides=strides, activation=None, data_format=data_format, name="identity_conv") self.activ = nn.ReLU() def call(self, x, training=None): if self.resize_identity: identity = self.identity_conv(x, training=training) else: identity = x x = self.body(x, training=training) x = self.se(x) x = x + identity x = self.activ(x) return x class SEResNeXt(tf.keras.Model): """ SE-ResNeXt 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. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, cardinality, bottleneck_width, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(SEResNeXt, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(ResInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(SEResNeXtUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, cardinality=cardinality, bottleneck_width=bottleneck_width, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_seresnext(blocks, cardinality, bottleneck_width, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create SE-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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if blocks == 50: layers = [3, 4, 6, 3] elif blocks == 101: layers = [3, 4, 23, 3] else: raise ValueError("Unsupported SE-ResNeXt 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 = SEResNeXt( 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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def seresnext50_32x4d(**kwargs): """ SE-ResNeXt-50 (32x4d) 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnext(blocks=50, cardinality=32, bottleneck_width=4, model_name="seresnext50_32x4d", **kwargs) def seresnext101_32x4d(**kwargs): """ SE-ResNeXt-101 (32x4d) 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnext(blocks=101, cardinality=32, bottleneck_width=4, model_name="seresnext101_32x4d", **kwargs) def seresnext101_64x4d(**kwargs): """ SE-ResNeXt-101 (64x4d) 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_seresnext(blocks=101, cardinality=64, bottleneck_width=4, model_name="seresnext101_64x4d", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K pretrained = False models = [ seresnext50_32x4d, seresnext101_32x4d, seresnext101_64x4d, ] for model in models: net = model(pretrained=pretrained) batch = 14 x = tf.random.normal((batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != seresnext50_32x4d or weight_count == 27559896) assert (model != seresnext101_32x4d or weight_count == 48955416) assert (model != seresnext101_64x4d or weight_count == 88232984) if __name__ == "__main__": _test()
9,503
31.772414
115
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/drn.py
""" DRN for ImageNet-1K, implemented in TensorFlow. Original paper: 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914. """ __all__ = ['DRN', 'drnc26', 'drnc42', 'drnc58', 'drnd22', 'drnd38', 'drnd54', 'drnd105'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import Conv2d, BatchNorm, SimpleSequential, flatten, is_channels_first class DRNConv(nn.Layer): """ DRN 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. dilation : int or tuple/list of 2 int Dilation value for convolution layer. activate : bool Whether activate the convolution block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, strides, padding, dilation, activate, data_format="channels_last", **kwargs): super(DRNConv, self).__init__(**kwargs) self.activate = activate self.conv = Conv2d( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, strides=strides, padding=padding, dilation=dilation, use_bias=False, data_format=data_format, name="conv") self.bn = BatchNorm( data_format=data_format, name="bn") if self.activate: self.activ = nn.ReLU() def call(self, x, training=None): x = self.conv(x) x = self.bn(x, training=training) if self.activate: x = self.activ(x) return x def drn_conv1x1(in_channels, out_channels, strides, activate, data_format="channels_last", **kwargs): """ 1x1 version of the DRN 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ return DRNConv( in_channels=in_channels, out_channels=out_channels, kernel_size=1, strides=strides, padding=0, dilation=1, activate=activate, data_format=data_format, **kwargs) def drn_conv3x3(in_channels, out_channels, strides, dilation, activate, data_format="channels_last", **kwargs): """ 3x3 version of the DRN 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. dilation : int or tuple/list of 2 int Padding/dilation value for convolution layer. activate : bool Whether activate the convolution block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ return DRNConv( in_channels=in_channels, out_channels=out_channels, kernel_size=3, strides=strides, padding=dilation, dilation=dilation, activate=activate, data_format=data_format, **kwargs) class DRNBlock(nn.Layer): """ Simple DRN block for residual path in DRN 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 Padding/dilation value for convolution layers. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, stride, dilation, data_format="channels_last", **kwargs): super(DRNBlock, self).__init__(**kwargs) self.conv1 = drn_conv3x3( in_channels=in_channels, out_channels=out_channels, strides=stride, dilation=dilation, activate=True, data_format=data_format, name="conv1") self.conv2 = drn_conv3x3( in_channels=out_channels, out_channels=out_channels, strides=1, dilation=dilation, activate=False, data_format=data_format, name="conv2") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) return x class DRNBottleneck(nn.Layer): """ DRN bottleneck block for residual path in DRN 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 Padding/dilation value for 3x3 convolution layer. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, dilation, data_format="channels_last", **kwargs): super(DRNBottleneck, self).__init__(**kwargs) mid_channels = out_channels // 4 self.conv1 = drn_conv1x1( in_channels=in_channels, out_channels=mid_channels, strides=1, activate=True, data_format=data_format, name="conv1") self.conv2 = drn_conv3x3( in_channels=mid_channels, out_channels=mid_channels, strides=strides, dilation=dilation, activate=True, data_format=data_format, name="conv2") self.conv3 = drn_conv1x1( in_channels=mid_channels, out_channels=out_channels, strides=1, activate=False, data_format=data_format, name="conv3") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) x = self.conv3(x, training=training) return x class DRNUnit(nn.Layer): """ DRN 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. dilation : int or tuple/list of 2 int Padding/dilation value for 3x3 convolution layers. bottleneck : bool Whether to use a bottleneck or simple block in units. simplified : bool Whether to use a simple or simplified block in units. residual : bool Whether do residual calculations. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, dilation, bottleneck, simplified, residual, data_format="channels_last", **kwargs): super(DRNUnit, self).__init__(**kwargs) assert residual or (not bottleneck) assert (not (bottleneck and simplified)) assert (not (residual and simplified)) self.residual = residual self.resize_identity = ((in_channels != out_channels) or (strides != 1)) and self.residual and (not simplified) if bottleneck: self.body = DRNBottleneck( in_channels=in_channels, out_channels=out_channels, strides=strides, dilation=dilation, data_format=data_format, name="body") elif simplified: self.body = drn_conv3x3( in_channels=in_channels, out_channels=out_channels, strides=strides, dilation=dilation, activate=False, data_format=data_format, name="body") else: self.body = DRNBlock( in_channels=in_channels, out_channels=out_channels, stride=strides, dilation=dilation, data_format=data_format, name="body") if self.resize_identity: self.identity_conv = drn_conv1x1( in_channels=in_channels, out_channels=out_channels, strides=strides, activate=False, data_format=data_format, name="identity_conv") self.activ = nn.ReLU() def call(self, x, training=None): if self.resize_identity: identity = self.identity_conv(x, training=training) else: identity = x x = self.body(x, training=training) if self.residual: x = x + identity x = self.activ(x) return x def drn_init_block(in_channels, out_channels, data_format="channels_last", **kwargs): """ DRN specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ return DRNConv( in_channels=in_channels, out_channels=out_channels, kernel_size=7, strides=1, padding=3, dilation=1, activate=True, data_format=data_format, **kwargs) class DRN(tf.keras.Model): """ DRN-C&D model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914. 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. dilations : list of list of int Dilation values for 3x3 convolution layers for each unit. bottlenecks : list of list of int Whether to use a bottleneck or simple block in each unit. simplifieds : list of list of int Whether to use a simple or simplified block in each unit. residuals : list of list of int Whether to use residual block in each unit. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, dilations, bottlenecks, simplifieds, residuals, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(DRN, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(drn_init_block( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="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(DRNUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, dilation=dilations[i][j], bottleneck=(bottlenecks[i][j] == 1), simplified=(simplifieds[i][j] == 1), residual=(residuals[i][j] == 1), data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(nn.AveragePooling2D( pool_size=28, strides=1, data_format=data_format, name="final_pool")) self.output1 = Conv2d( in_channels=in_channels, out_channels=classes, kernel_size=1, data_format=data_format, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = self.output1(x) x = flatten(x, self.data_format) return x def get_drn(blocks, simplified=False, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create DRN-C or DRN-D model with specific parameters. Parameters: ---------- blocks : int Number of blocks. simplified : bool, default False Whether to use simplified scheme (D architecture). 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if blocks == 22: assert simplified layers = [1, 1, 2, 2, 2, 2, 1, 1] elif blocks == 26: layers = [1, 1, 2, 2, 2, 2, 1, 1] elif blocks == 38: assert simplified layers = [1, 1, 3, 4, 6, 3, 1, 1] elif blocks == 42: layers = [1, 1, 3, 4, 6, 3, 1, 1] elif blocks == 54: assert simplified layers = [1, 1, 3, 4, 6, 3, 1, 1] elif blocks == 58: layers = [1, 1, 3, 4, 6, 3, 1, 1] elif blocks == 105: assert simplified layers = [1, 1, 3, 4, 23, 3, 1, 1] else: raise ValueError("Unsupported DRN with number of blocks: {}".format(blocks)) if blocks < 50: channels_per_layers = [16, 32, 64, 128, 256, 512, 512, 512] bottlenecks_per_layers = [0, 0, 0, 0, 0, 0, 0, 0] else: channels_per_layers = [16, 32, 256, 512, 1024, 2048, 512, 512] bottlenecks_per_layers = [0, 0, 1, 1, 1, 1, 0, 0] if simplified: simplifieds_per_layers = [1, 1, 0, 0, 0, 0, 1, 1] residuals_per_layers = [0, 0, 1, 1, 1, 1, 0, 0] else: simplifieds_per_layers = [0, 0, 0, 0, 0, 0, 0, 0] residuals_per_layers = [1, 1, 1, 1, 1, 1, 0, 0] dilations_per_layers = [1, 1, 1, 1, 2, 4, 2, 1] downsample = [0, 1, 1, 1, 0, 0, 0, 0] def expand(property_per_layers): from functools import reduce return reduce( lambda x, y: x + [[y[0]] * y[1]] if y[2] != 0 else x[:-1] + [x[-1] + [y[0]] * y[1]], zip(property_per_layers, layers, downsample), [[]]) channels = expand(channels_per_layers) dilations = expand(dilations_per_layers) bottlenecks = expand(bottlenecks_per_layers) residuals = expand(residuals_per_layers) simplifieds = expand(simplifieds_per_layers) init_block_channels = channels_per_layers[0] net = DRN( channels=channels, init_block_channels=init_block_channels, dilations=dilations, bottlenecks=bottlenecks, simplifieds=simplifieds, residuals=residuals, **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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def drnc26(**kwargs): """ DRN-C-26 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_drn(blocks=26, model_name="drnc26", **kwargs) def drnc42(**kwargs): """ DRN-C-42 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_drn(blocks=42, model_name="drnc42", **kwargs) def drnc58(**kwargs): """ DRN-C-58 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_drn(blocks=58, model_name="drnc58", **kwargs) def drnd22(**kwargs): """ DRN-D-58 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_drn(blocks=22, simplified=True, model_name="drnd22", **kwargs) def drnd38(**kwargs): """ DRN-D-38 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_drn(blocks=38, simplified=True, model_name="drnd38", **kwargs) def drnd54(**kwargs): """ DRN-D-54 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_drn(blocks=54, simplified=True, model_name="drnd54", **kwargs) def drnd105(**kwargs): """ DRN-D-105 model from 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_drn(blocks=105, simplified=True, model_name="drnd105", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ drnc26, drnc42, drnc58, drnd22, drnd38, drnd54, drnd105, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != drnc26 or weight_count == 21126584) assert (model != drnc42 or weight_count == 31234744) assert (model != drnc58 or weight_count == 40542008) # 41591608 assert (model != drnd22 or weight_count == 16393752) assert (model != drnd38 or weight_count == 26501912) assert (model != drnd54 or weight_count == 35809176) assert (model != drnd105 or weight_count == 54801304) if __name__ == "__main__": _test()
21,693
30.44058
119
py
imgclsmob
imgclsmob-master/tensorflow2/tf2cv/models/mixnet.py
""" MixNet for ImageNet-1K, implemented in TensorFlow. Original paper: 'MixConv: Mixed Depthwise Convolutional Kernels,' https://arxiv.org/abs/1907.09595. """ __all__ = ['MixNet', 'mixnet_s', 'mixnet_m', 'mixnet_l'] import os import tensorflow as tf import tensorflow.keras.layers as nn from .common import round_channels, get_activation_layer, Conv2d, BatchNorm, conv1x1_block,\ conv3x3_block, dwconv3x3_block, SEBlock, SimpleSequential, flatten, is_channels_first, get_channel_axis class MixConv(nn.Layer): """ Mixed convolution layer from 'MixConv: Mixed Depthwise Convolutional Kernels,' https://arxiv.org/abs/1907.09595. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int or tuple/list of int, or tuple/list of 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 int, or tuple/list of 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. axis : int, default 1 The axis on which to concatenate the outputs. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, strides, padding, dilation=1, groups=1, use_bias=False, axis=1, data_format="channels_last", **kwargs): super(MixConv, self).__init__(**kwargs) kernel_size = kernel_size if isinstance(kernel_size, list) else [kernel_size] padding = padding if isinstance(padding, list) else [padding] kernel_count = len(kernel_size) self.splitted_in_channels = self.split_channels(in_channels, kernel_count) splitted_out_channels = self.split_channels(out_channels, kernel_count) self.axis = axis self.convs = [] for i, kernel_size_i in enumerate(kernel_size): in_channels_i = self.splitted_in_channels[i] out_channels_i = splitted_out_channels[i] padding_i = padding[i] self.convs.append( Conv2d( in_channels=in_channels_i, out_channels=out_channels_i, kernel_size=kernel_size_i, strides=strides, padding=padding_i, dilation=dilation, groups=(out_channels_i if out_channels == groups else groups), use_bias=use_bias, data_format=data_format, name="conv{}".format(i + 1))) def call(self, x, training=None): xx = tf.split(x, num_or_size_splits=self.splitted_in_channels, axis=self.axis) out = [conv_i(x_i, training=training) for x_i, conv_i in zip(xx, self.convs)] x = tf.concat(out, axis=self.axis) return x @staticmethod def split_channels(channels, kernel_count): splitted_channels = [channels // kernel_count] * kernel_count splitted_channels[0] += channels - sum(splitted_channels) return splitted_channels class MixConvBlock(nn.Layer): """ Mixed 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 int, or tuple/list of 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 int, or tuple/list of 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_eps : float, default 1e-5 Small float added to variance in Batch norm. activation : function or str or None, default nn.Activation("relu") Activation function or name of activation function. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, kernel_size, strides, padding, dilation=1, groups=1, use_bias=False, use_bn=True, bn_eps=1e-5, activation=(lambda: nn.ReLU()), data_format="channels_last", **kwargs): super(MixConvBlock, self).__init__(**kwargs) self.activate = (activation is not None) self.use_bn = use_bn self.conv = MixConv( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, strides=strides, padding=padding, dilation=dilation, groups=groups, use_bias=use_bias, axis=get_channel_axis(data_format), data_format=data_format, name="conv") if self.use_bn: self.bn = BatchNorm( epsilon=bn_eps, data_format=data_format, name="bn") if self.activate: self.activ = get_activation_layer(activation) def call(self, x, training=None): x = self.conv(x) if self.use_bn: x = self.bn(x, training=training) if self.activate: x = self.activ(x) return x def mixconv1x1_block(in_channels, out_channels, kernel_count, strides=1, groups=1, use_bias=False, use_bn=True, bn_eps=1e-5, activation=(lambda: nn.Activation("relu")), data_format="channels_last", **kwargs): """ 1x1 version of the mixed convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_count : int Kernel count. 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_bn : bool, default True Whether to use BatchNorm layer. bn_eps : float, default 1e-5 Small float added to variance in Batch norm. activation : function or str, or None, default nn.Activation("relu") Activation function or name of activation function. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ return MixConvBlock( in_channels=in_channels, out_channels=out_channels, kernel_size=([1] * kernel_count), strides=strides, padding=([0] * kernel_count), groups=groups, use_bias=use_bias, use_bn=use_bn, bn_eps=bn_eps, activation=activation, data_format=data_format, **kwargs) class MixUnit(nn.Layer): """ MixNet 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. exp_kernel_count : int Expansion convolution kernel count for each unit. conv1_kernel_count : int Conv1 kernel count for each unit. conv2_kernel_count : int Conv2 kernel count for each unit. exp_factor : int Expansion factor for each unit. se_factor : int SE reduction factor for each unit. activation : str Activation function or name of activation function. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, strides, exp_kernel_count, conv1_kernel_count, conv2_kernel_count, exp_factor, se_factor, activation, data_format="channels_last", **kwargs): super(MixUnit, self).__init__(**kwargs) assert (exp_factor >= 1) assert (se_factor >= 0) self.residual = (in_channels == out_channels) and (strides == 1) self.use_se = se_factor > 0 mid_channels = exp_factor * in_channels self.use_exp_conv = exp_factor > 1 if self.use_exp_conv: if exp_kernel_count == 1: self.exp_conv = conv1x1_block( in_channels=in_channels, out_channels=mid_channels, activation=activation, data_format=data_format, name="exp_conv") else: self.exp_conv = mixconv1x1_block( in_channels=in_channels, out_channels=mid_channels, kernel_count=exp_kernel_count, activation=activation, data_format=data_format, name="exp_conv") if conv1_kernel_count == 1: self.conv1 = dwconv3x3_block( in_channels=mid_channels, out_channels=mid_channels, strides=strides, activation=activation, data_format=data_format, name="conv1") else: self.conv1 = MixConvBlock( in_channels=mid_channels, out_channels=mid_channels, kernel_size=[3 + 2 * i for i in range(conv1_kernel_count)], strides=strides, padding=[1 + i for i in range(conv1_kernel_count)], groups=mid_channels, activation=activation, data_format=data_format, name="conv1") if self.use_se: self.se = SEBlock( channels=mid_channels, reduction=(exp_factor * se_factor), round_mid=False, mid_activation=activation, data_format=data_format, name="se") if conv2_kernel_count == 1: self.conv2 = conv1x1_block( in_channels=mid_channels, out_channels=out_channels, activation=None, data_format=data_format, name="conv2") else: self.conv2 = mixconv1x1_block( in_channels=mid_channels, out_channels=out_channels, kernel_count=conv2_kernel_count, activation=None, data_format=data_format, name="conv2") def call(self, x, training=None): if self.residual: identity = x if self.use_exp_conv: x = self.exp_conv(x, training=training) x = self.conv1(x, training=training) if self.use_se: x = self.se(x) x = self.conv2(x, training=training) if self.residual: x = x + identity return x class MixInitBlock(nn.Layer): """ MixNet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, in_channels, out_channels, data_format="channels_last", **kwargs): super(MixInitBlock, self).__init__(**kwargs) self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=out_channels, strides=2, data_format=data_format, name="conv1") self.conv2 = MixUnit( in_channels=out_channels, out_channels=out_channels, strides=1, exp_kernel_count=1, conv1_kernel_count=1, conv2_kernel_count=1, exp_factor=1, se_factor=0, activation="relu", data_format=data_format, name="conv2") def call(self, x, training=None): x = self.conv1(x, training=training) x = self.conv2(x, training=training) return x class MixNet(tf.keras.Model): """ MixNet model from 'MixConv: Mixed Depthwise Convolutional Kernels,' https://arxiv.org/abs/1907.09595. 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. exp_kernel_counts : list of list of int Expansion convolution kernel count for each unit. conv1_kernel_counts : list of list of int Conv1 kernel count for each unit. conv2_kernel_counts : list of list of int Conv2 kernel count for each unit. exp_factors : list of list of int Expansion factor for each unit. se_factors : list of list of int SE reduction factor for each unit. 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. data_format : str, default 'channels_last' The ordering of the dimensions in tensors. """ def __init__(self, channels, init_block_channels, final_block_channels, exp_kernel_counts, conv1_kernel_counts, conv2_kernel_counts, exp_factors, se_factors, in_channels=3, in_size=(224, 224), classes=1000, data_format="channels_last", **kwargs): super(MixNet, self).__init__(**kwargs) self.in_size = in_size self.classes = classes self.data_format = data_format self.features = SimpleSequential(name="features") self.features.add(MixInitBlock( in_channels=in_channels, out_channels=init_block_channels, data_format=data_format, name="init_block")) in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): stage = SimpleSequential(name="stage{}".format(i + 1)) 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 exp_kernel_count = exp_kernel_counts[i][j] conv1_kernel_count = conv1_kernel_counts[i][j] conv2_kernel_count = conv2_kernel_counts[i][j] exp_factor = exp_factors[i][j] se_factor = se_factors[i][j] activation = "relu" if i == 0 else "swish" stage.add(MixUnit( in_channels=in_channels, out_channels=out_channels, strides=strides, exp_kernel_count=exp_kernel_count, conv1_kernel_count=conv1_kernel_count, conv2_kernel_count=conv2_kernel_count, exp_factor=exp_factor, se_factor=se_factor, activation=activation, data_format=data_format, name="unit{}".format(j + 1))) in_channels = out_channels self.features.add(stage) self.features.add(conv1x1_block( in_channels=in_channels, out_channels=final_block_channels, activation=activation, data_format=data_format, name="final_block")) in_channels = final_block_channels self.features.add(nn.AveragePooling2D( pool_size=7, strides=1, data_format=data_format, name="final_pool")) self.output1 = nn.Dense( units=classes, input_dim=in_channels, name="output1") def call(self, x, training=None): x = self.features(x, training=training) x = flatten(x, self.data_format) x = self.output1(x) return x def get_mixnet(version, width_scale, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create MixNet model with specific parameters. Parameters: ---------- version : str Version of MobileNetV3 ('s' or 'm'). 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. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ if version == "s": init_block_channels = 16 channels = [[24, 24], [40, 40, 40, 40], [80, 80, 80], [120, 120, 120, 200, 200, 200]] exp_kernel_counts = [[2, 2], [1, 2, 2, 2], [1, 1, 1], [2, 2, 2, 1, 1, 1]] conv1_kernel_counts = [[1, 1], [3, 2, 2, 2], [3, 2, 2], [3, 4, 4, 5, 4, 4]] conv2_kernel_counts = [[2, 2], [1, 2, 2, 2], [2, 2, 2], [2, 2, 2, 1, 2, 2]] exp_factors = [[6, 3], [6, 6, 6, 6], [6, 6, 6], [6, 3, 3, 6, 6, 6]] se_factors = [[0, 0], [2, 2, 2, 2], [4, 4, 4], [2, 2, 2, 2, 2, 2]] elif version == "m": init_block_channels = 24 channels = [[32, 32], [40, 40, 40, 40], [80, 80, 80, 80], [120, 120, 120, 120, 200, 200, 200, 200]] exp_kernel_counts = [[2, 2], [1, 2, 2, 2], [1, 2, 2, 2], [1, 2, 2, 2, 1, 1, 1, 1]] conv1_kernel_counts = [[3, 1], [4, 2, 2, 2], [3, 4, 4, 4], [1, 4, 4, 4, 4, 4, 4, 4]] conv2_kernel_counts = [[2, 2], [1, 2, 2, 2], [1, 2, 2, 2], [1, 2, 2, 2, 1, 2, 2, 2]] exp_factors = [[6, 3], [6, 6, 6, 6], [6, 6, 6, 6], [6, 3, 3, 3, 6, 6, 6, 6]] se_factors = [[0, 0], [2, 2, 2, 2], [4, 4, 4, 4], [2, 2, 2, 2, 2, 2, 2, 2]] else: raise ValueError("Unsupported MixNet version {}".format(version)) final_block_channels = 1536 if width_scale != 1.0: channels = [[round_channels(cij * width_scale) for cij in ci] for ci in channels] init_block_channels = round_channels(init_block_channels * width_scale) net = MixNet( channels=channels, init_block_channels=init_block_channels, final_block_channels=final_block_channels, exp_kernel_counts=exp_kernel_counts, conv1_kernel_counts=conv1_kernel_counts, conv2_kernel_counts=conv2_kernel_counts, exp_factors=exp_factors, se_factors=se_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 in_channels = kwargs["in_channels"] if ("in_channels" in kwargs) else 3 input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == "channels_first" else\ (1,) + net.in_size + (in_channels,) net.build(input_shape=input_shape) net.load_weights( filepath=get_model_file( model_name=model_name, local_model_store_dir_path=root)) return net def mixnet_s(**kwargs): """ MixNet-S model from 'MixConv: Mixed Depthwise Convolutional Kernels,' https://arxiv.org/abs/1907.09595. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mixnet(version="s", width_scale=1.0, model_name="mixnet_s", **kwargs) def mixnet_m(**kwargs): """ MixNet-M model from 'MixConv: Mixed Depthwise Convolutional Kernels,' https://arxiv.org/abs/1907.09595. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mixnet(version="m", width_scale=1.0, model_name="mixnet_m", **kwargs) def mixnet_l(**kwargs): """ MixNet-L model from 'MixConv: Mixed Depthwise Convolutional Kernels,' https://arxiv.org/abs/1907.09595. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.tensorflow/models' Location for keeping the model parameters. """ return get_mixnet(version="m", width_scale=1.3, model_name="mixnet_l", **kwargs) def _test(): import numpy as np import tensorflow.keras.backend as K data_format = "channels_last" pretrained = False models = [ mixnet_s, mixnet_m, mixnet_l, ] for model in models: net = model(pretrained=pretrained, data_format=data_format) batch = 14 x = tf.random.normal((batch, 3, 224, 224) if is_channels_first(data_format) else (batch, 224, 224, 3)) y = net(x) assert (tuple(y.shape.as_list()) == (batch, 1000)) weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights]) print("m={}, {}".format(model.__name__, weight_count)) assert (model != mixnet_s or weight_count == 4134606) assert (model != mixnet_m or weight_count == 5014382) assert (model != mixnet_l or weight_count == 7329252) if __name__ == "__main__": _test()
23,110
34.886646
116
py