Beispiel #1
0
    def __init__(self):
        super().__init__()

        base_net = resnet.resnet34(pretrained=True)

        self.in_block = nn.Sequential(base_net.conv1, base_net.bn1,
                                      base_net.relu, base_net.maxpool)

        self.encoder = nn.ModuleList([
            base_net.layer1, base_net.layer2, base_net.layer3, base_net.layer4
        ])

        enc_channels = list(reversed([64, 128, 256, 512]))

        self.decoder = nn.ModuleList([])
        self.lateral = nn.ModuleList([])
        for in_channel, out_channel in zip(enc_channels[:-1],
                                           enc_channels[1:]):
            d = DecoderBlock(in_channel, out_channel, 3, 2)
            l = nn.Sequential(nn.Conv2d(out_channel, 256, 3, padding=1),
                              nn.BatchNorm2d(256), nn.ReLU(inplace=True))
            self.decoder.append(d)
            self.lateral.append(l)

        self.classifier = nn.ModuleList([
            nn.Sequential(nn.Conv2d(256, 256, 3, padding=1),
                          nn.BatchNorm2d(256), nn.ReLU(inplace=True)),
            nn.Sequential(nn.Conv2d(256, 256, 3, padding=1),
                          nn.BatchNorm2d(256), nn.ReLU(inplace=True)),
            nn.Sequential(nn.Conv2d(256, 256, 3, padding=1),
                          nn.BatchNorm2d(256), nn.ReLU(inplace=True)),
            nn.Sequential(nn.Conv2d(256, 256, 3, padding=1),
                          nn.BatchNorm2d(256), nn.ReLU(inplace=True)),
            nn.Conv2d(256, 68, 3, padding=1)
        ])
Beispiel #2
0
    def __init__(
        self,
        num_claasses=28,
        pretrained_resnet=True,
        sng_args=SNG_ARGS,
        qsdf_args=QSDF_ARGS,
    ):
        super().__init__()

        self.sng_args = sng_args
        self.qsdf_args = qsdf_args
        self.num_classes = num_claasses

        self.resnet = resnet.resnet34(pretrained=pretrained_resnet)
        self.resnet.layer4 = nn.Identity()
        self.resnet.avgpool = nn.Identity()
        self.resnet.fc = nn.Identity()

        self.scene_graph = SceneGraph(**sng_args)

        self.reasoning = qs.DifferentiableReasoning(
            self._make_vse_concepts(qsdf_args.vse_large_scale,
                                    qsdf_args.vse_known_belong),
            self.scene_graph.output_dims,
            qsdf_args.vse_hidden_dims,
        )
Beispiel #3
0
    def __init__(self, resnet_layer, pretrained=None):
        super(ResNetFPN, self).__init__()
        self.lateral_conv1 = nn.Conv2d(2048, 256, kernel_size=1)
        self.lateral_conv2 = nn.Conv2d(1024, 256, kernel_size=1)
        self.lateral_conv3 = nn.Conv2d(512, 256, kernel_size=1)
        self.lateral_conv4 = nn.Conv2d(256, 256, kernel_size=1)

        self.anti_aliasing_conv1 = nn.Conv2d(256,
                                             256,
                                             kernel_size=3,
                                             padding=1)
        self.anti_aliasing_conv2 = nn.Conv2d(256,
                                             256,
                                             kernel_size=3,
                                             padding=1)
        self.anti_aliasing_conv3 = nn.Conv2d(256,
                                             256,
                                             kernel_size=3,
                                             padding=1)
        self._init_parameters()

        assert resnet_layer in [18, 34, 50, 101, 152]
        pretrained = True if pretrained is not None else False
        if resnet_layer == 18:
            self.resnet = resnet.resnet18(pretrained)
        elif resnet_layer == 34:
            self.resnet = resnet.resnet34(pretrained)
        elif resnet_layer == 50:
            self.resnet = resnet.resnet50(pretrained)
        elif resnet_layer == 101:
            self.resnet = resnet.resnet101(pretrained)
        elif resnet_layer == 152:
            self.resnet = resnet.resnet152(pretrained)
Beispiel #4
0
    def __init__(self, backbone='resnet50'):
        super().__init__()
        if backbone == 'resnet18':
            backbone = resnet18(pretrained=True)
            self.out_channels = [256, 512, 512, 256, 256, 128]
        elif backbone == 'resnet34':
            backbone = resnet34(pretrained=True)
            self.out_channels = [256, 512, 512, 256, 256, 256]
        elif backbone == 'resnet50':
            backbone = resnet50(pretrained=True)
            self.out_channels = [1024, 512, 512, 256, 256, 256]
        elif backbone == 'resnet101':
            backbone = resnet101(pretrained=True)
            self.out_channels = [1024, 512, 512, 256, 256, 256]
        else:  # backbone == 'resnet152':
            backbone = resnet152(pretrained=True)
            self.out_channels = [1024, 512, 512, 256, 256, 256]


        self.feature_extractor = nn.Sequential(*list(backbone.children())[:7])

        conv4_block1 = self.feature_extractor[-1][0]

        conv4_block1.conv1.stride = (1, 1)
        conv4_block1.conv2.stride = (1, 1)
        conv4_block1.downsample[0].stride = (1, 1)
Beispiel #5
0
    def __init__(self, name="resnet34", pretrain=True):
        super().__init__()
        if name == "resnet50":
            base_net = resnet.resnet50(pretrained=False)

            if pretrain:
                print("load the {} weight from ./cache".format(name))
                base_net.load_state_dict(model_zoo.load_url(model_urls["resnet50"], model_dir="./cache"))
        if name == "resnet34":
            base_net = resnet.resnet34(pretrained=False)

            if pretrain:
                print("load the {} weight from ./cache".format(name))
                base_net.load_state_dict(model_zoo.load_url(model_urls["resnet34"], model_dir="./cache"))

        self.stage1 = nn.Sequential(
            base_net.conv1,
            base_net.bn1,
            base_net.relu,
            base_net.maxpool
        )
        self.stage2 = base_net.layer1
        self.stage3 = base_net.layer2
        self.stage4 = base_net.layer3
        self.stage5 = base_net.layer4
Beispiel #6
0
 def __init__(self, mode_name='wide_resnet50_2'):
     super(Backbone, self).__init__()
     assert mode_name in ('resnet18', 'resnet34', 'resnet50', 'resnet101',
                          'resnet152', 'resnext50_32x4d',
                          'resnext101_32x8d', 'wide_resnet50_2',
                          'wide_resnet101_2')
     if mode_name == 'resnet18':
         self.res_back_bone = resnet.resnet18()
     elif mode_name == 'resnet34':
         self.res_back_bone = resnet.resnet34()
     elif mode_name == 'resnet50':
         self.res_back_bone = resnet.resnet50()
     elif mode_name == 'resnet101':
         self.res_back_bone = resnet.resnet101()
     elif mode_name == 'resnet152':
         self.res_back_bone = resnet.resnet152()
     elif mode_name == 'resnext50_32x4d':
         self.res_back_bone = resnet.resnext50_32x4d()
     elif mode_name == 'resnext101_32x8d':
         self.res_back_bone = resnet.resnext101_32x8d()
     elif mode_name == 'wide_resnet50_2':
         self.res_back_bone = resnet.wide_resnet50_2()
     else:
         self.res_back_bone = resnet.wide_resnet101_2()
     self.backbone = nn.Module()
     layer0 = nn.Sequential(*list(self.res_back_bone.children())[:4])
     self.backbone.add_module('layer0', layer0)
     self.backbone.add_module('layer1', self.res_back_bone.layer1)
     self.backbone.add_module('layer2', self.res_back_bone.layer2)
     self.backbone.add_module('layer3', self.res_back_bone.layer3)
     self.backbone.add_module('layer4', self.res_back_bone.layer4)
Beispiel #7
0
 def __init__(self):
     self.resnet = resnet34(pretrained=True)
     self.linear = nn.Linear(1000, 3)
     self.optimiser = torch.optim.Adam(list(self.resnet.parameters()) +
                                       list(self.linear.parameters()),
                                       lr=.0003,
                                       eps=1e-6)
Beispiel #8
0
def resnet34_reid(features=128, classes=1502):
    resnet = resnet34(pretrained=True)
    resnet.layer4[0].downsample[0].stride = (1, 1)
    resnet.layer4[0].conv1.stride = (1, 1)
    resnet.fc = None
    model = ReIDResnet(resnet, 512, features, classes)
    return model
    def __init__(
            self,
            voxel_dimension=(9, 180,
                             240),  # dimension of voxel will be C x 2 x H x W
            crop_dimension=(
                224, 224),  # dimension of crop before it goes into classifier
            num_classes=101,
            mlp_layers=[1, 30, 30, 1],
            activation=nn.LeakyReLU(negative_slope=0.1),
            pretrained=True):

        nn.Module.__init__(self)
        self.quantization_layer = QuantizationLayer(voxel_dimension,
                                                    mlp_layers, activation)
        self.classifier = resnet34(pretrained=pretrained)

        self.crop_dimension = crop_dimension

        # replace fc layer and first convolutional layer
        input_channels = 2 * voxel_dimension[0]
        self.classifier.conv1 = nn.Conv2d(input_channels,
                                          64,
                                          kernel_size=7,
                                          stride=2,
                                          padding=3,
                                          bias=False)
        self.classifier.fc = nn.Linear(self.classifier.fc.in_features,
                                       num_classes)
Beispiel #10
0
    def __init__(self, out_channels=64, pretrained=True):
        super(UNetResNet34, self).__init__()
        self.out_channels = out_channels

        # ----------------------------------------------------------------------------- #
        # Encoder
        # ----------------------------------------------------------------------------- #
        net = resnet34(pretrained)
        # Note that we do not downsample for conv1
        # self.conv1 = net.conv1
        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=1, padding=3, bias=False)
        self.conv1.weight.data = net.conv1.weight.data
        self.bn1 = net.bn1
        self.relu = net.relu
        self.maxpool = net.maxpool
        self.layer1 = net.layer1
        self.layer2 = net.layer2
        self.layer3 = net.layer3
        self.layer4 = net.layer4

        # ----------------------------------------------------------------------------- #
        # Decoder
        # ----------------------------------------------------------------------------- #
        _, self.dec_t_conv_stage5 = self.dec_stage(self.layer4, num_concat=1)
        self.dec_conv_stage4, self.dec_t_conv_stage4 = self.dec_stage(self.layer3, num_concat=2)
        self.dec_conv_stage3, self.dec_t_conv_stage3 = self.dec_stage(self.layer2, num_concat=2)
        self.dec_conv_stage2, self.dec_t_conv_stage2 = self.dec_stage(self.layer1, num_concat=2)
        self.dec_conv_stage1 = nn.Conv2d(2 * 64, out_channels, kernel_size=3, padding=1)

        # dropout
        self.dropout = nn.Dropout(p=0.4)
    def __init__(self, backbone='resnet50', pretrained_path=None):
        super().__init__()
        if backbone == 'resnet18':
            backbone = resnet18(pretrained=not pretrained_path)
            self.final_out_channels = 256
            self.low_level_inplanes = 64
        elif backbone == 'resnet34':
            backbone = resnet34(pretrained=not pretrained_path)
            self.final_out_channels = 256
            self.low_level_inplanes = 64
        elif backbone == 'resnet50':
            backbone = resnet50(pretrained=not pretrained_path)
            self.final_out_channels = 1024
            self.low_level_inplanes = 256
        elif backbone == 'resnet101':
            backbone = resnet101(pretrained=not pretrained_path)
            self.final_out_channels = 1024
            self.low_level_inplanes = 256
        else:  # backbone == 'resnet152':
            backbone = resnet152(pretrained=not pretrained_path)
            self.final_out_channels = 1024
            self.low_level_inplanes = 256
        if pretrained_path:
            backbone.load_state_dict(torch.load(pretrained_path))


        self.early_extractor = nn.Sequential(*list(backbone.children())[:5])
        self.later_extractor = nn.Sequential(*list(backbone.children())[5:7])

        conv4_block1 = self.later_extractor[-1][0]

        conv4_block1.conv1.stride = (1, 1)
        conv4_block1.conv2.stride = (1, 1)
        conv4_block1.downsample[0].stride = (1, 1)
Beispiel #12
0
    def __init__(self, backbone="resnet50", backbone_path=None):
        super().__init__()
        if backbone == "resnet18":
            backbone = resnet18(pretrained=not backbone_path)
            self.out_channels = [256, 512, 512, 256, 256, 128]
        elif backbone == "resnet34":
            backbone = resnet34(pretrained=not backbone_path)
            self.out_channels = [256, 512, 512, 256, 256, 256]
        elif backbone == "resnet50":
            backbone = resnet50(pretrained=not backbone_path)
            self.out_channels = [1024, 512, 512, 256, 256, 256]
        elif backbone == "resnet101":
            backbone = resnet101(pretrained=not backbone_path)
            self.out_channels = [1024, 512, 512, 256, 256, 256]
        else:
            backbone = resnet152(pretrained=not backbone_path)
            self.out_channels = [1024, 512, 512, 256, 256, 256]
        if backbone_path:
            backbone.load_state_dict(torch.load(backbone_path))

        self.feature_extractor = nn.Sequential(*list(backbone.children())[:7])

        conv4_block1 = self.feature_extractor[-1][0]

        conv4_block1.conv1.stride = (1, 1)
        conv4_block1.conv2.stride = (1, 1)
        conv4_block1.downsample[0].stride = (1, 1)
Beispiel #13
0
    def __init__(self, resnet_layer, pretrained=None):
        super(ResNet, self).__init__()
        assert resnet_layer in [18, 34, 50, 101, 152]
        pretrained = True if pretrained is not None else False
        if resnet_layer == 18:
            self.resnet = resnet.resnet18(pretrained)
        elif resnet_layer == 34:
            self.resnet = resnet.resnet34(pretrained)
        elif resnet_layer == 50:
            self.resnet = resnet.resnet50(pretrained)
        elif resnet_layer == 101:
            self.resnet = resnet.resnet101(pretrained)
        else:
            self.resnet = resnet.resnet152(pretrained)

        # fix layer grad
        for p in self.resnet.conv1.parameters():
            p.requires_grad = False
        for p in self.resnet.layer1.parameters():
            p.requires_grad = False
        for p in self.resnet.layer2.parameters():
            p.requires_grad = True
        for p in self.resnet.layer3.parameters():
            p.requires_grad = True

        # fix batch norm layer
        for m in self.resnet.modules():
            if isinstance(m, nn.BatchNorm2d):
                for p in m.parameters():
                    p.requires_grad = False
Beispiel #14
0
    def __init__(self, backbone='resnet50', backbone_path=None):
        super().__init__()
        if backbone == 'resnet18':
            backbone = resnet18(pretrained=not backbone_path)
            self.out_channels = [256, 512, 512, 256, 256, 128]
        elif backbone == 'resnet34':
            backbone = resnet34(pretrained=not backbone_path)
            self.out_channels = [256, 512, 512, 256, 256, 256]
        elif backbone == 'resnet50':
            backbone = resnet50(pretrained=not backbone_path)
            self.out_channels = [1024, 512, 512, 256, 256, 256]
        elif backbone == 'resnet101':
            backbone = resnet101(pretrained=not backbone_path)
            self.out_channels = [1024, 512, 512, 256, 256, 256]
        else:  # backbone == 'resnet152':
            backbone = resnet152(pretrained=not backbone_path)
            self.out_channels = [1024, 512, 512, 256, 256, 256]
        if backbone_path:
            backbone.load_state_dict(torch.load(backbone_path))

        for name, parameter in backbone.named_parameters():
            if 'layer2' not in name and 'layer3' not in name and 'layer4' not in name:
                parameter.requires_grad_(False)
        self.feature_extractor = nn.Sequential(*list(backbone.children())[:7])

        conv4_block1 = self.feature_extractor[-1][0]

        conv4_block1.conv1.stride = (1, 1)
        conv4_block1.conv2.stride = (1, 1)
        conv4_block1.downsample[0].stride = (1, 1)
def load_model():
    '''Download the pretrained model'''
    model = resnet34(pretrained=True).to('cuda')
    # summary(model, input_size=(3, 224, 224))
    #print('Number of Residual blocks: ', len(list(model.children())))
    # print('\n', list(model.children())[:-4])
    return model
Beispiel #16
0
    def __init__(self, cfg: Namespace, **kwargs):
        super(BaseModel, self).__init__()

        pretrained_base = getattr(cfg, "pretrained_base", False)
        in_channels = getattr(cfg, "in_channels", 3)

        # Spatial transformer localization-network
        self.image_conv = resnet34(pretrained=pretrained_base)

        self.localization_2 = nn.Sequential(nn.Conv2d(3, 8, kernel_size=7),
                                            nn.MaxPool2d(2, stride=2),
                                            nn.ReLU(True),
                                            nn.Conv2d(8, 10, kernel_size=5),
                                            nn.MaxPool2d(2, stride=2),
                                            nn.ReLU(True))

        self.localization = nn.Sequential(nn.Conv2d(10, 8, kernel_size=7),
                                          nn.MaxPool2d(2, stride=2),
                                          nn.ReLU(True),
                                          nn.Conv2d(8, 10, kernel_size=5),
                                          nn.MaxPool2d(2, stride=2),
                                          nn.ReLU(True))

        # Regressor for the 3 * 2 affine matrix
        self.fc_loc = nn.Sequential(nn.Linear(10 * 3 * 3, 32), nn.ReLU(True),
                                    nn.Linear(32, 3 * 2))

        # Initialize the weights/bias with identity transformation
        self.fc_loc[2].weight.data.zero_()
        self.fc_loc[2].bias.data.copy_(
            torch.tensor([1, 0, 0, 0, 1, 0], dtype=torch.float))

        self.layer = make_layer(3, BasicBlock, 6, 3)
    def __init__(self, n_styles=18, opts=None):
        super(ResNetBackboneEncoder, self).__init__()

        self.conv1 = nn.Conv2d(opts.input_nc,
                               64,
                               kernel_size=7,
                               stride=2,
                               padding=3,
                               bias=False)
        self.bn1 = BatchNorm2d(64)
        self.relu = PReLU(64)

        resnet_basenet = resnet34(pretrained=True)
        blocks = [
            resnet_basenet.layer1, resnet_basenet.layer2,
            resnet_basenet.layer3, resnet_basenet.layer4
        ]
        modules = []
        for block in blocks:
            for bottleneck in block:
                modules.append(bottleneck)
        self.body = Sequential(*modules)

        self.styles = nn.ModuleList()
        self.style_count = n_styles
        for i in range(self.style_count):
            style = GradualStyleBlock(512, 512, 16)
            self.styles.append(style)
Beispiel #18
0
    def __init__(self, n_classes):
        """The definition of our network

        Arguments:
            n_classes {int} -- The number of classes in the dataset
        """
        super(Model, self).__init__()
        self.n_features = 512  # The dimension of features before the classification layer
        self.feature_size = 8  # The size of feature map extracted from self.features
        self.resnet = resnet34(pretrained=True)
        self.features = nn.Sequential(
            self.resnet.conv1,
            self.resnet.bn1,
            self.resnet.relu,
            self.resnet.maxpool,
            self.resnet.layer1,
            self.resnet.layer2,
            self.resnet.layer3,
            self.resnet.layer4,
            # nn.AvgPool2d(7, stride=1)     # We replace this layer by nn.AdaptiveAvgPool2d
            nn.AdaptiveAvgPool2d((self.feature_size, self.feature_size)))
        # Adaptation layer
        self.fc = nn.Sequential(
            nn.Linear(self.n_features * self.feature_size**2, self.n_features),
            # nn.ReLU(True) # ReLU will lead to feature disappearance, while Sigmoid will not.
            nn.Sigmoid())
        self.fc[0].weight.data.normal_(0, 0.5)
        # Classfication layer
        self.classifier = nn.Linear(self.n_features, n_classes)
Beispiel #19
0
 def __init__(self, pretrained=None):
     super(HeadCommon, self).__init__()
     self.config = ConfigParser()
     config_path = os.path.abspath(
         os.path.join(__file__, "../../", "config.ini"))
     assert os.path.exists(config_path), "config.ini not exists!"
     self.config.read(config_path)
     self.backbone_type = self.config['BACKBONE']['BACKBONE_TYPE']
     _pretrained = True if pretrained is not None else False
     assert self.backbone_type in ['resnet', 'vgg16']
     if self.backbone_type == 'resnet':
         resnet_layer = int(self.config['BACKBONE']['RESNET_LAYER'])
         assert resnet_layer in [18, 34, 50, 101, 152]
         if resnet_layer == 18:
             _resnet = resnet.resnet18(_pretrained)
         elif resnet_layer == 34:
             _resnet = resnet.resnet34(_pretrained)
         elif resnet_layer == 50:
             _resnet = resnet.resnet50(_pretrained)
         elif resnet_layer == 101:
             _resnet = resnet.resnet101(_pretrained)
         else:
             _resnet = resnet.resnet152(_pretrained)
         # using resnet_c5 the last bottle neck of resnet
         _resnet.layer4[0].conv2.stride = (1, 1)
         _resnet.layer4[0].downsample[0].stride = (1, 1)
         self.resnet_c5 = _resnet.layer4
         self.resnet_c5_avg = _resnet.avgpool
     elif self.backbone_type == 'vgg16':
         assert not bool(int(self.config['HEAD']['MASK_HEAD_ON'])), (
             "When mask head on, not support vgg16 backbone.")
         vgg = vgg16(pretrained=True)
         self.vgg_fc = nn.Sequential(
             *list(vgg.classifier._modules.values())[:-1])
Beispiel #20
0
    def __init__(self, feature_dim=128, resnet_depth=18):
        super(Model, self).__init__()

        self.f = []
        if resnet_depth == 18:
            my_resnet = resnet18()
            resnet_output_dim = 512
        elif resnet_depth == 34:
            my_resnet = resnet34()
            resnet_output_dim = 512
        elif resnet_depth == 50:
            my_resnet = resnet50()
            resnet_output_dim = 2048

        for name, module in my_resnet.named_children():
            if name == 'conv1':
                module = nn.Conv2d(3,
                                   64,
                                   kernel_size=3,
                                   stride=1,
                                   padding=1,
                                   bias=False)
            if not isinstance(module, nn.Linear) and not isinstance(
                    module, nn.MaxPool2d):
                self.f.append(module)
        # encoder
        self.f = nn.Sequential(*self.f)
        # projection head
        self.g = nn.Sequential(nn.Linear(resnet_output_dim, 512, bias=False),
                               nn.BatchNorm1d(512), nn.ReLU(inplace=True),
                               nn.Linear(512, feature_dim, bias=True))
    def __init__(self, backbone, num_classes=21):
        super().__init__()
        if backbone == 'resnet-18':
            self.backbone = resnet18()
            self.in_channel = [512, 128, 64, 64]
            self.out_channel = [256, 64, 64, 64]
        elif backbone == 'resnet-34':
            self.backbone = resnet34()
            self.in_channel = [512, 128, 64, 64]
            self.out_channel = [256, 64, 64, 64]
        elif backbone == 'resnet-50':
            self.backbone = resnet50()
            self.in_channel = [2048, 512, 256, 64]
            self.out_channel = [1024, 256, 64, 64]
        elif backbone == 'resnet-101':
            self.backbone = resnet101()
            self.in_channel = [2048, 512, 256, 64]
            self.out_channel = [1024, 256, 64, 64]
        elif backbone == 'resnet-152':
            self.backbone = resnet152()
            self.in_channel = [2048, 512, 256, 64]
            self.out_channel = [1024, 256, 64, 64]
        else:
            raise NotImplementedError

        self.encoder = Encoder(self.backbone)
        self.decoder = Decoder(self.in_channel, self.out_channel)
        self.out = nn.Conv2d(64, num_classes, 1)

        self._init_weight()
def get_classification_model(classifier_name='resnet18',
                             num_classes=1000,
                             pretrained=True):
    """
    Get the detection model
    :param pretrained:
    :param classifier_name:
    :param num_classes:
    :return:
    """
    if classifier_name == 'resnet18':
        model = resnet18(pretrained, num_classes=num_classes)

    elif classifier_name == 'resnet34':
        model = resnet34(pretrained, num_classes=num_classes)

    elif classifier_name == 'resnet50':
        model = resnet50(pretrained, num_classes=num_classes)

    elif classifier_name == 'resnet101':
        model = resnet101(pretrained, num_classes=num_classes)

    elif classifier_name == 'resnet152':
        model = resnet152(pretrained, num_classes=num_classes)

    else:
        raise ValueError('Unsupported resnet type.')

    return model
Beispiel #23
0
 def __init__(self, num_classes: int = 250):
     super(ResNet34, self).__init__()
     self.backbone = resnet34(pretrained=True)
     self.backbone.fc = nn.Linear(self.backbone.fc.in_features, num_classes)
     self._fc2 = None
     self._fc3 = None
     self._bn1d = None
     self._relu = nn.ReLU()
Beispiel #24
0
def main():
    # set the random seeds
    # torch.manual_seed(42)
    # random.seed(42)

    resnet = resnet34()
    dataset = Cifar10Dataset()
    kubenet = KubeResnet34(resnet, dataset)
    return kubenet.start()
Beispiel #25
0
 def initModel(self, model, preTrain):
     if model == "18":
         return resnet.resnet18(
             preTrain, num_classes=config.frontend["resnet"]["size"])
     elif model == "34":
         return resnet.resnet34(
             preTrain, num_classes=config.frontend["resnet"]["size"])
     elif model == "50":
         return resnet.resnet50(
             preTrain, num_classes=config.frontend["resnet"]["size"])
Beispiel #26
0
 def initModel(self, model, preTrain):
     if model == "18":
         return resnet.resnet18(preTrain,
                                num_classes=ENCODER_REPRESENTATION_SIZE)
     elif model == "34":
         return resnet.resnet34(preTrain,
                                num_classes=ENCODER_REPRESENTATION_SIZE)
     elif model == "50":
         return resnet.resnet50(preTrain,
                                num_classes=ENCODER_REPRESENTATION_SIZE)
Beispiel #27
0
def resnet34(pretrained=False, **kwargs):
    """Constructs a ResNet-34 model.
    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet_C5(BasicBlock, [3, 4, 6, 3], **kwargs)
    model_full = resnet.resnet34(pretrained=True)
    if pretrained:
        model.load_pretrained(model_full)
    return model
Beispiel #28
0
 def get_backbone(self, name, pretrained):
     if name == "resne34":
         return resnet34(pretrained=pretrained)
     elif name == "resnet50":
         return resnet50(pretrained=pretrained)
     elif name == "resnet101":
         return resnet101(pretrained=pretrained)
     elif name == "resnet152":
         return resnet152(pretrained=pretrained)
     else:
         return resnet18(pretrained=pretrained) #default
def resnet34(pretrained=False, fixed_feature=True):
    """ "ResNet-34 model from torchvision's resnet model.

    :param pretrained: if true, return a model pretrained on ImageNet
    :param fixed_feature: if true and pretrained is true, model features are fixed while training.
    """
    from torchvision.models.resnet import resnet34
    model = resnet34(pretrained)

    ff = True if pretrained and fixed_feature else False
    return _ResNet(model, ff)
    def __init__(self):
        super().__init__()
        rn34 = resnet34(pretrained=True)

        # discard last Resnet block, avrpooling and classification FC
        self.layer1 = nn.Sequential(*list(rn34.children())[:6])
        self.layer2 = nn.Sequential(*list(rn34.children())[6:7])
        # modify conv4 if necessary
        # Always deal with stride in first block
        modulelist = list(self.layer2.children())
        _ModifyBlock(modulelist[0], stride=(1, 1))
def create_model(model_name, num_classes=1000, pretrained=False, **kwargs):
    if 'test_time_pool' in kwargs:
        test_time_pool = kwargs.pop('test_time_pool')
    else:
        test_time_pool = True
    if 'extra' in kwargs:
        extra = kwargs.pop('extra')
    else:
        extra = True
    if model_name == 'dpn68':
        model = dpn68(
            num_classes=num_classes, pretrained=pretrained, test_time_pool=test_time_pool)
    elif model_name == 'dpn68b':
        model = dpn68b(
            num_classes=num_classes, pretrained=pretrained, test_time_pool=test_time_pool)
    elif model_name == 'dpn92':
        model = dpn92(
            num_classes=num_classes, pretrained=pretrained, test_time_pool=test_time_pool, extra=extra)
    elif model_name == 'dpn98':
        model = dpn98(
            num_classes=num_classes, pretrained=pretrained, test_time_pool=test_time_pool)
    elif model_name == 'dpn131':
        model = dpn131(
            num_classes=num_classes, pretrained=pretrained, test_time_pool=test_time_pool)
    elif model_name == 'dpn107':
        model = dpn107(
            num_classes=num_classes, pretrained=pretrained, test_time_pool=test_time_pool)
    elif model_name == 'resnet18':
        model = resnet18(num_classes=num_classes, pretrained=pretrained, **kwargs)
    elif model_name == 'resnet34':
        model = resnet34(num_classes=num_classes, pretrained=pretrained, **kwargs)
    elif model_name == 'resnet50':
        model = resnet50(num_classes=num_classes, pretrained=pretrained, **kwargs)
    elif model_name == 'resnet101':
        model = resnet101(num_classes=num_classes, pretrained=pretrained, **kwargs)
    elif model_name == 'resnet152':
        model = resnet152(num_classes=num_classes, pretrained=pretrained, **kwargs)
    elif model_name == 'densenet121':
        model = densenet121(num_classes=num_classes, pretrained=pretrained, **kwargs)
    elif model_name == 'densenet161':
        model = densenet161(num_classes=num_classes, pretrained=pretrained, **kwargs)
    elif model_name == 'densenet169':
        model = densenet169(num_classes=num_classes, pretrained=pretrained, **kwargs)
    elif model_name == 'densenet201':
        model = densenet201(num_classes=num_classes, pretrained=pretrained, **kwargs)
    elif model_name == 'inception_v3':
        model = inception_v3(
            num_classes=num_classes, pretrained=pretrained, transform_input=False, **kwargs)
    else:
        assert False, "Unknown model architecture (%s)" % model_name
    return model