Ejemplo n.º 1
0
    def _make_layer(block,
                    num_filters,
                    blocklayers,
                    strides=1,
                    dilate=False,
                    use_bias=use_bias,
                    layer_name=''):
        conv_shortcut = False
        if strides != 1 or block is bottleneck:
            conv_shortcut = True
        layers = []
        layers.append(
            block(num_filters=num_filters,
                  strides=strides,
                  expansion=4,
                  conv_shortcut=conv_shortcut,
                  use_bias=use_bias,
                  name=layer_name + '_0'))

        for k in range(1, blocklayers):
            layers.append(
                block(num_filters=num_filters,
                      strides=1,
                      expansion=4,
                      conv_shortcut=False,
                      use_bias=use_bias,
                      name=layer_name + '_{0}'.format(k)))

        laters_block = Sequential(*layers)
        laters_block.name = layer_name
        return laters_block
Ejemplo n.º 2
0
def DenseNet(blocks,
             growth_rate=32,
             initial_filters=64,
             include_top=True,
             pretrained=True,
             input_shape=(3,224,224),
             num_classes=1000,
             name='',
             **kwargs):
    """'
    Instantiates the DenseNet architecture.
    Optionally loads weights pre-trained on ImageNet.

    Args
        blocks (tuple/ list of int ): numbers of building blocks for the dense layers.

        growth_rate (int):The growth rate regulates how much new information each layer contributes to the global state

        initial_filters (int): the channel of the first convolution layer

        pretrained (bool): If True, returns a model pre-trained on ImageNet.

        input_shape (tuple or list): the default input image size in CHW order (C, H, W)

        num_classes (int): number of classes

        name (string): anme of the model

    Returns
        A trident image classification model instance.

    """
    densenet=Sequential()
    densenet.add_module('conv1/conv',Conv2d_Block((7,7),initial_filters,strides=2,use_bias=False,auto_pad=True,padding_mode='zero',activation='relu',normalization='batch', name='conv1/conv'))
    densenet.add_module('maxpool', (MaxPool2d((3, 3), strides=2, auto_pad=True, padding_mode='zero')))
    densenet.add_module('denseblock1', DenseBlock(blocks[0],growth_rate=growth_rate))
    densenet.add_module('transitiondown1', Transition(0.5))
    densenet.add_module('denseblock2', DenseBlock(blocks[1], growth_rate=growth_rate))
    densenet.add_module('transitiondown2', Transition(0.5))
    densenet.add_module('denseblock3', DenseBlock(blocks[2], growth_rate=growth_rate))
    densenet.add_module('transitiondown3', Transition(0.5))
    densenet.add_module('denseblock4', DenseBlock(blocks[3], growth_rate=growth_rate))
    densenet.add_module('classifier_norm',BatchNorm2d(name='classifier_norm'))
    densenet.add_module('classifier_relu', Relu(name='classifier_relu'))
    if include_top:
        densenet.add_module('avg_pool', GlobalAvgPool2d(name='avg_pool'))
        densenet.add_module('classifier', Dense(num_classes, activation=None, name='classifier'))
        densenet.add_module('softmax', SoftMax( name='softmax'))
    densenet.name = name

    model=ImageClassificationModel(input_shape=input_shape,output=densenet)

    #model.model.to(_device)
    with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'imagenet_labels1.txt'), 'r',encoding='utf-8-sig') as f:
        labels = [l.rstrip() for l in f]
        model.class_names = labels
    model.preprocess_flow = [resize((input_shape[2], input_shape[1]), keep_aspect=True), normalize(0, 255),  normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]
    # model.summary()
    return model
Ejemplo n.º 3
0
def resnet(block, layers, input_shape=(3, 224, 224), num_classes=1000, use_bias=False,  include_top=True, model_name='',
           **kwargs):
    """Instantiates the ResNet, ResNetV2, and ResNeXt architecture.

    Args
        block: a function that returns output tensor for the stacked residual blocks.
        layers: list of integer, the number of  repeat units in each blocks.
        input_shape: optional shape tuple, only to be specified
            if `include_top` is False (otherwise the input shape
            has to be`(3, 224, 224)` (with `channels_first` data format).
            It should have exactly 3 inputs channels.
        num_classes: optional number of classes to classify images
            into, only to be specified if `include_top` is True, and
            if no `weights` argument is specified.
        use_bias: whether to use biases for convolutional layers or not
            (True for ResNet and ResNetV2, False for ResNeXt).
        include_top: whether to include the fully-connected layer at the top of the network.
        model_name: string, model name.

    Returns
        A Keras model instance.

    Raises
        ValueError: in case of invalid argument for `weights`,  or invalid input shape.

    """


    def _make_layer(block, num_filters, blocklayers, strides=1, dilate=False,use_bias=use_bias,layer_name=''):
        conv_shortcut=False
        if strides!=1 or block is bottleneck:
            conv_shortcut=True
        layers = []
        layers.append(block(num_filters=num_filters, strides=strides, expansion = 4, conv_shortcut=conv_shortcut,use_bias=use_bias, name=layer_name+'_0'))

        for k in range(1, blocklayers):
            layers.append(block(num_filters=num_filters,  strides=1, expansion = 4, conv_shortcut=False, use_bias=use_bias,name=layer_name+'_{0}'.format(k)))

        laters_block=Sequential(*layers)
        laters_block.name=layer_name
        return laters_block

    flow_list=[]
    resnet = Sequential()
    resnet.add_module('first_block',Conv2d_Block((7,7),64,strides=2,use_bias=use_bias,auto_pad=True,padding_mode='zero',normalization='batch',activation='relu',name='first_block'))
    resnet.add_module('maxpool',(MaxPool2d((3,3),strides=2,auto_pad=True,padding_mode='zero')))
    resnet.add_module('layer1',(_make_layer(block, 64, layers[0],strides=1, dilate=None,use_bias=use_bias,layer_name='layer1' )))
    resnet.add_module('layer2',(_make_layer(block, 128, layers[1], strides=2, dilate=None,use_bias=use_bias,layer_name='layer2' )))
    resnet.add_module('layer3',(_make_layer(block, 256, layers[2], strides=2, dilate=None,use_bias=use_bias,layer_name='layer3' )))
    resnet.add_module('layer4' ,(_make_layer(block, 512, layers[3], strides=2, dilate=None,use_bias=use_bias,layer_name='layer4' )))
    if include_top:
        resnet.add_module('avg_pool', GlobalAvgPool2d(name='avg_pool'))
        resnet.add_module('fc',Dense(num_classes,activation=None,name='fc'))
        resnet.add_module('softmax', SoftMax(name='softmax'))
    resnet.name=model_name
    return resnet
Ejemplo n.º 4
0
def SEResNet_IR(include_top=True,num_layers=50,Bottleneck=BottleNeck_IR_SE,drop_ratio=0.4,feature_dim=128,input_shape=(3,112,112)):
    blocks=OrderedDict()
    blocks['input_layer']=Conv2d_Block((3,3),64,strides=1,auto_pad=True,use_bias=False,activation=PRelu(64),normalization='batch',name='input_layer')
    blocks['body']=Sequential(
        get_block(Bottleneck, out_channel=64, num_units=3,keep_filter=True)+
        get_block(Bottleneck, out_channel=128, num_units=4,keep_filter=False)+
        get_block(Bottleneck, out_channel=256, num_units=14,keep_filter=False)+
        get_block(Bottleneck, out_channel=512, num_units=3,keep_filter=False)
    )
    blocks['output_layer']=Sequential(
        BatchNorm2d(),
        Dropout(drop_ratio),
        Flatten(),
        Dense(feature_dim),
        BatchNorm(),
        name='output_layer'
    )
    facenet=Sequential(blocks).to(_device)
    facenet.name=camel2snake('SEResNet_IR')
    model=FaceRecognitionModel(input_shape=input_shape,output=facenet)
    model.preprocess_flow=[Resize((input_shape[1],input_shape[2]),keep_aspect=True),Normalize(0,255),Normalize([0.485, 0.456, 0.406],[0.229, 0.224, 0.225])]
    #model.summary()
    return model
Ejemplo n.º 5
0
def SE_ResNet(block,
              layers,
              input_shape=(3, 224, 224),
              num_classes=1000,
              use_bias=False,
              include_top=True,
              model_name='',
              **kwargs):
    """Instantiates the ResNet, ResNetV2, and ResNeXt architecture.

    Args
        block: a function that returns output tensor for the stacked residual blocks.
        layers: list of integer, the number of  repeat units in each blocks.
        input_shape: optional shape tuple, only to be specified
            if `include_top` is False (otherwise the input shape
            has to be`(3, 224, 224)` (with `channels_first` data format).
            It should have exactly 3 inputs channels.
        num_classes: optional number of classes to classify images
            into, only to be specified if `include_top` is True, and
            if no `weights` argument is specified.
        use_bias: whether to use biases for convolutional layers or not
            (True for ResNet and ResNetV2, False for ResNeXt).
        include_top: whether to include the fully-connected layer at the top of the network.
        model_name: string, model name.

    Returns
        A Keras model instance.

    Raises
        ValueError: in case of invalid argument for `weights`,  or invalid input shape.

    """
    def _make_layer(block,
                    num_filters,
                    blocklayers,
                    strides=1,
                    dilate=False,
                    use_bias=use_bias,
                    layer_name=''):
        conv_shortcut = False
        if strides != 1 or block is bottleneck or num_filters != 128:
            conv_shortcut = True

        layers = []
        layers.append(
            block(num_filters=num_filters,
                  strides=strides,
                  expansion=4,
                  conv_shortcut=conv_shortcut,
                  use_bias=use_bias,
                  name=layer_name + '.0'))

        for k in range(1, blocklayers):
            layers.append(
                block(num_filters=num_filters,
                      strides=1,
                      expansion=4,
                      conv_shortcut=False,
                      use_bias=use_bias,
                      name=layer_name + '.{0}'.format(k)))

        layers_block = Sequential(*layers)
        layers_block.name = layer_name
        return layers_block

    flow_list = []
    resnet = Sequential()
    layer0 = Sequential(name='layer0')
    layer0.add_module(
        'first_block',
        Conv2d_Block((7, 7),
                     64,
                     strides=2,
                     use_bias=use_bias,
                     auto_pad=True,
                     padding_mode='zero',
                     normalization='batch',
                     activation='relu',
                     name='first_block'))
    layer0.add_module('maxpool', (MaxPool2d(
        (3, 3), strides=2, auto_pad=True, padding_mode='zero')))
    resnet.add_module('layer0', layer0)
    resnet.add_module('layer1', (_make_layer(block,
                                             64,
                                             layers[0],
                                             strides=1,
                                             dilate=None,
                                             use_bias=use_bias,
                                             layer_name='layer1')))
    resnet.add_module('layer2', (_make_layer(block,
                                             128,
                                             layers[1],
                                             strides=2,
                                             dilate=None,
                                             use_bias=use_bias,
                                             layer_name='layer2')))
    resnet.add_module('layer3', (_make_layer(block,
                                             256,
                                             layers[2],
                                             strides=2,
                                             dilate=None,
                                             use_bias=use_bias,
                                             layer_name='layer3')))
    resnet.add_module('layer4', (_make_layer(block,
                                             512,
                                             layers[3],
                                             strides=2,
                                             dilate=None,
                                             use_bias=use_bias,
                                             layer_name='layer4')))
    resnet.add_module('avg_pool', GlobalAvgPool2d(name='avg_pool'))
    if include_top:
        resnet.add_module('fc', Dense(num_classes, activation=None, name='fc'))
        resnet.add_module('softmax', SoftMax(name='softmax'))
    resnet.name = model_name
    model = ImageClassificationModel(input_shape=input_shape, output=resnet)

    with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                           'imagenet_labels1.txt'),
              'r',
              encoding='utf-8-sig') as f:
        labels = [l.rstrip() for l in f]
        model.class_names = labels
    model.preprocess_flow = [
        resize((input_shape[1], input_shape[2]), keep_aspect=True),
        normalize(0, 255),
        normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]
    #model.summary()
    return model