当前位置: 首页>>代码示例>>Python>>正文


Python models.densenet121方法代码示例

本文整理汇总了Python中torchvision.models.densenet121方法的典型用法代码示例。如果您正苦于以下问题:Python models.densenet121方法的具体用法?Python models.densenet121怎么用?Python models.densenet121使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在torchvision.models的用法示例。


在下文中一共展示了models.densenet121方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_untargeted_densenet121

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import densenet121 [as 别名]
def test_untargeted_densenet121(image, label=None):
    import torch
    import torchvision.models as models
    from perceptron.models.classification import PyTorchModel
    mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))
    std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))
    model_pyt = models.densenet121(pretrained=True).eval()
    if torch.cuda.is_available():
        model_pyt = model_pyt.cuda()
    model = PyTorchModel(
        model_pyt, bounds=(0, 1), num_classes=1000, preprocessing=(mean, std))
    print(np.argmax(model.predictions(image)))
    attack = Attack(model, criterion=Misclassification())
    adversarial_obj = attack(image, label, unpack=False, epsilons=10000)
    distance = adversarial_obj.distance
    adversarial = adversarial_obj.image
    return distance, adversarial 
开发者ID:advboxes,项目名称:perceptron-benchmark,代码行数:19,代码来源:test_attack_Gaussian_blur.py

示例2: densenet121

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import densenet121 [as 别名]
def densenet121(num_classes=1000, pretrained='imagenet'):
    r"""Densenet-121 model from
    `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
    """
    model = models.densenet121(num_classes=num_classes, pretrained=False)
    if pretrained is not None:
        # '.'s are no longer allowed in module names, but pervious _DenseLayer
        # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.
        # They are also in the checkpoints in model_urls. This pattern is used
        # to find such keys.
        settings = pretrained_settings['densenet121'][pretrained]
        pattern = re.compile(
            r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$')
        state_dict = model_zoo.load_url(settings['url'])
        for key in list(state_dict.keys()):
            res = pattern.match(key)
            if res:
                new_key = res.group(1) + res.group(2)
                state_dict[new_key] = state_dict[key]
                del state_dict[key]
        model.load_state_dict(state_dict)
    model = modify_densenets(model)
    return model 
开发者ID:alexandonian,项目名称:pretorched-x,代码行数:25,代码来源:torchvision_models.py

示例3: __init__

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import densenet121 [as 别名]
def __init__(self, class_num ):
        super(ft_net_dense,self).__init__()
        model_ft = models.densenet121(pretrained=True)
        # add pooling to the model
        # in the originial version, pooling is written in the forward function 
        model_ft.features.avgpool = nn.AdaptiveAvgPool2d((1,1))

        add_block = []
        num_bottleneck = 1024
        add_block += [nn.BatchNorm1d(num_bottleneck)]
        add_block = nn.Sequential(*add_block)
        add_block.apply(weights_init_kaiming)
        model_ft.bn = add_block
        self.model = model_ft


        self.fc0 = nn.Linear(num_bottleneck, class_num, bias = True)
        init.normal(self.fc0.weight.data, std=0.001)
        if hasattr(self.fc0.bias, 'data'):
            init.constant(self.fc0.bias.data, 0.0) 
开发者ID:SongBaiHust,项目名称:Adversarial_Metric_Attack,代码行数:22,代码来源:model.py

示例4: Dense121

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import densenet121 [as 别名]
def Dense121(config):
    return models.densenet121(pretrained=True) 
开发者ID:ngessert,项目名称:isic2019,代码行数:4,代码来源:models.py

示例5: _load_pytorch_model

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import densenet121 [as 别名]
def _load_pytorch_model(model_name, summary):
    import torchvision.models as models
    switcher = {
        'alexnet': lambda: models.alexnet(pretrained=True).eval(),
        "vgg11": lambda: models.vgg11(pretrained=True).eval(),
        "vgg11_bn": lambda: models.vgg11_bn(pretrained=True).eval(),
        "vgg13": lambda: models.vgg13(pretrained=True).eval(),
        "vgg13_bn": lambda: models.vgg13_bn(pretrained=True).eval(),
        "vgg16": lambda: models.vgg16(pretrained=True).eval(),
        "vgg16_bn": lambda: models.vgg16_bn(pretrained=True).eval(),
        "vgg19": lambda: models.vgg19(pretrained=True).eval(),
        "vgg19_bn": lambda: models.vgg19_bn(pretrained=True).eval(),
        "resnet18": lambda: models.resnet18(pretrained=True).eval(),
        "resnet34": lambda: models.resnet34(pretrained=True).eval(),
        "resnet50": lambda: models.resnet50(pretrained=True).eval(),
        "resnet101": lambda: models.resnet101(pretrained=True).eval(),
        "resnet152": lambda: models.resnet152(pretrained=True).eval(),
        "squeezenet1_0": lambda: models.squeezenet1_0(pretrained=True).eval(),
        "squeezenet1_1": lambda: models.squeezenet1_1(pretrained=True).eval(),
        "densenet121": lambda: models.densenet121(pretrained=True).eval(),
        "densenet161": lambda: models.densenet161(pretrained=True).eval(),
        "densenet201": lambda: models.densenet201(pretrained=True).eval(),
        "inception_v3": lambda: models.inception_v3(pretrained=True).eval(),
    }

    _load_model = switcher.get(model_name, None)
    _model = _load_model()
    import torch
    if torch.cuda.is_available():
        _model = _model.cuda()
    from perceptron.models.classification.pytorch import PyTorchModel as ClsPyTorchModel
    import numpy as np
    mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))
    std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))
    pmodel = ClsPyTorchModel(
        _model, bounds=(
            0, 1), num_classes=1000, preprocessing=(
            mean, std))
    return pmodel 
开发者ID:advboxes,项目名称:perceptron-benchmark,代码行数:41,代码来源:tools.py

示例6: load_pytorch_model

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import densenet121 [as 别名]
def load_pytorch_model(model_name):
    import torchvision.models as models
    switcher = {
        'alexnet': lambda: models.alexnet(pretrained=True).eval(),
        "vgg11": lambda: models.vgg11(pretrained=True).eval(),
        "vgg11_bn": lambda: models.vgg11_bn(pretrained=True).eval(),
        "vgg13": lambda: models.vgg13(pretrained=True).eval(),
        "vgg13_bn": lambda: models.vgg13_bn(pretrained=True).eval(),
        "vgg16": lambda: models.vgg16(pretrained=True).eval(),
        "vgg16_bn": lambda: models.vgg16_bn(pretrained=True).eval(),
        "vgg19": lambda: models.vgg19(pretrained=True).eval(),
        "vgg19_bn": lambda: models.vgg19_bn(pretrained=True).eval(),
        "resnet18": lambda: models.resnet18(pretrained=True).eval(),
        "resnet34": lambda: models.resnet34(pretrained=True).eval(),
        "resnet50": lambda: models.resnet50(pretrained=True).eval(),
        "resnet101": lambda: models.resnet101(pretrained=True).eval(),
        "resnet152": lambda: models.resnet152(pretrained=True).eval(),
        "squeezenet1_0": lambda: models.squeezenet1_0(pretrained=True).eval(),
        "squeezenet1_1": lambda: models.squeezenet1_1(pretrained=True).eval(),
        "densenet121": lambda: models.densenet121(pretrained=True).eval(),
        "densenet161": lambda: models.densenet161(pretrained=True).eval(),
        "densenet201": lambda: models.densenet201(pretrained=True).eval(),
        "inception_v3": lambda: models.inception_v3(pretrained=True).eval(),
    }

    _load_model = switcher.get(model_name, None)
    _model = _load_model()
    return _model 
开发者ID:advboxes,项目名称:perceptron-benchmark,代码行数:30,代码来源:tools.py

示例7: dn121

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import densenet121 [as 别名]
def dn121(pre): return children(densenet121(pre))[0] 
开发者ID:alecrubin,项目名称:pytorch-serverless,代码行数:3,代码来源:torch_imports.py

示例8: densenet121

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import densenet121 [as 别名]
def densenet121(num_classes=1000, pretrained='imagenet'):
    r"""Densenet-121 model from
    `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
    """
    model = models.densenet121(pretrained=False)
    if pretrained is not None:
        settings = pretrained_settings['densenet121'][pretrained]
        model = load_pretrained(model, num_classes, settings)
    model = modify_densenets(model)
    return model 
开发者ID:Cadene,项目名称:pretrained-models.pytorch,代码行数:12,代码来源:torchvision_models.py

示例9: denseUnet121

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import densenet121 [as 别名]
def denseUnet121(pretrained=False, d_block_type='basic', init_method='normal', version=1, type_net="t", **kwargs):
    r"""Densenet-121 model from
    `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_
    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """

    d_block = BasicBlock
    model = DenseUNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 24, 16), d_block=d_block, **kwargs)

    if pretrained:
        w_init.init_weights(model, init_method)
        # Get state dict from the actual model
        model_dict = model.state_dict()
        pretrained_dict = models.densenet121(pretrained=True).state_dict()
        # exclude_model_dict = ["features.conv0.weight"]
        model_shapes = [v.shape for k, v in model_dict.items()]
        exclude_model_dict = []
        exclude_model_dict = [k for k, v in pretrained_dict.items() if v.shape not in model_shapes]
        pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict and k not in exclude_model_dict}

        # added to pytorch 0.4
        pattern = re.compile(
            r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$')
        # state_dict = model_zoo.load_url(model_urls['densenet121'])
        for key in list(pretrained_dict.keys()):
            res = pattern.match(key)
            if res:
                new_key = res.group(1) + res.group(2)
                pretrained_dict[new_key] = pretrained_dict[key]
                del pretrained_dict[key]

        model_dict.update(pretrained_dict)
        model.load_state_dict(model_dict)

    return model 
开发者ID:marcelampc,项目名称:aerial_mtl,代码行数:38,代码来源:dense_decoders_multitask_auto.py

示例10: D3net_shared_weights

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import densenet121 [as 别名]
def D3net_shared_weights(pretrained=False, d_block_type='basic', init_method='normal', version=1, **kwargs):
    r"""Densenet-121 model from
    `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_
    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    d_block = get_decoder_block(d_block_type)
    model = D3netSharedWeights(num_init_features=64, growth_rate=32, block_config=(6, 12, 24, 16), d_block=d_block,
                          **kwargs)

    if pretrained:
        w_init.init_weights(model, init_method)
        # Get state dict from the actual model
        model_dict = model.state_dict()
        pretrained_dict = models.densenet121(pretrained=True).state_dict()
        # exclude_model_dict = ["features.conv0.weight"]
        model_shapes = [v.shape for k, v in model_dict.items()]
        exclude_model_dict = []
        exclude_model_dict = [k for k, v in pretrained_dict.items() if v.shape not in model_shapes]
        pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict and k not in exclude_model_dict}

        # added to pytorch 0.4
        pattern = re.compile(
            r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$')
        # state_dict = model_zoo.load_url(model_urls['densenet121'])
        for key in list(pretrained_dict.keys()):
            res = pattern.match(key)
            if res:
                new_key = res.group(1) + res.group(2)
                pretrained_dict[new_key] = pretrained_dict[key]
                del pretrained_dict[key]

        model_dict.update(pretrained_dict)
        model.load_state_dict(model_dict)

    return model 
开发者ID:marcelampc,项目名称:aerial_mtl,代码行数:38,代码来源:dense_decoders.py

示例11: denseUnet169

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import densenet121 [as 别名]
def denseUnet169(pretrained=False, d_block_type='basic', init_method='normal', **kwargs):
    r"""Densenet-121 model from
    `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_
    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    d_block = get_decoder_block(d_block_type)
    model = DenseUNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 32, 32), d_block=d_block,
                      **kwargs)


    if pretrained:
        w_init.init_weights(model, init_method)
        # Get state dict from the actual model
        model_dict = model.state_dict()
        # pretrained_dict = model_zoo.load_url(model_urls['resnet50'])
        pretrained_dict = models.densenet169(pretrained=True).state_dict()
        pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
        # added to pytorch 0.4
        pattern = re.compile(
            r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$')
        # state_dict = model_zoo.load_url(model_urls['densenet121'])
        for key in list(pretrained_dict.keys()):
            res = pattern.match(key)
            if res:
                new_key = res.group(1) + res.group(2)
                pretrained_dict[new_key] = pretrained_dict[key]
                del pretrained_dict[key]

        model_dict.update(pretrained_dict)
        model.load_state_dict(model_dict)
    #     model.load_state_dict(model_zoo.load_url(model_urls['densenet121']))
    return model 
开发者ID:marcelampc,项目名称:aerial_mtl,代码行数:35,代码来源:dense_decoders.py

示例12: __init__

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import densenet121 [as 别名]
def __init__(self, depth=121, num_feature=1024, num_classes=632, num_iteration = 3):

        super(DenseNet, self).__init__()
        self.depth = depth
        self.base = models.densenet121(pretrained=True)
        self.seblock = SELayer(channel=num_feature, reduction=16)
        self.classifer1 = Classifier(num_feature=num_feature, dropout=0.25, num_classes=num_classes)
        self.classifer2 = Classifier(num_feature=num_feature, dropout=0, num_classes=num_classes)

        self.primary_capsules = CapsuleLayer(num_capsules=8, num_route_nodes=-1, in_channels=num_feature, out_channels=32,
                                             kernel_size=2, stride=2, num_iterations = num_iteration)
        self.digit_capsules = CapsuleLayer(num_capsules=num_classes, num_route_nodes=32 * 3 * 3, in_channels=8,
                                           out_channels=24, num_iterations = num_iteration) 
开发者ID:Huang-3,项目名称:Celeb-reID,代码行数:15,代码来源:dense1stream_capsule.py

示例13: get_net

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import densenet121 [as 别名]
def get_net(net_name, weight_path=None):
    """
    根据网络名称获取模型
    :param net_name: 网络名称
    :param weight_path: 与训练权重路径
    :return:
    """
    pretrain = weight_path is None  # 没有指定权重路径,则加载默认的预训练权重
    if net_name in ['vgg', 'vgg16']:
        net = models.vgg16(pretrained=pretrain)
    elif net_name == 'vgg19':
        net = models.vgg19(pretrained=pretrain)
    elif net_name in ['resnet', 'resnet50']:
        net = models.resnet50(pretrained=pretrain)
    elif net_name == 'resnet101':
        net = models.resnet101(pretrained=pretrain)
    elif net_name in ['densenet', 'densenet121']:
        net = models.densenet121(pretrained=pretrain)
    elif net_name in ['inception']:
        net = models.inception_v3(pretrained=pretrain)
    elif net_name in ['mobilenet_v2']:
        net = models.mobilenet_v2(pretrained=pretrain)
    elif net_name in ['shufflenet_v2']:
        net = models.shufflenet_v2_x1_0(pretrained=pretrain)
    else:
        raise ValueError('invalid network name:{}'.format(net_name))
    # 加载指定路径的权重参数
    if weight_path is not None and net_name.startswith('densenet'):
        pattern = re.compile(
            r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$')
        state_dict = torch.load(weight_path)
        for key in list(state_dict.keys()):
            res = pattern.match(key)
            if res:
                new_key = res.group(1) + res.group(2)
                state_dict[new_key] = state_dict[key]
                del state_dict[key]
        net.load_state_dict(state_dict)
    elif weight_path is not None:
        net.load_state_dict(torch.load(weight_path))
    return net 
开发者ID:yizt,项目名称:Grad-CAM.pytorch,代码行数:43,代码来源:main.py

示例14: build

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import densenet121 [as 别名]
def build(conf, phase='train'):

    train = phase.lower() == 'train'

    densenet121 = models.densenet121(pretrained=train)

    rpn_net = RPN(phase, densenet121.features, conf)

    if train: rpn_net.train()
    else: rpn_net.eval()

    return rpn_net 
开发者ID:garrickbrazil,项目名称:M3D-RPN,代码行数:14,代码来源:densenet121_3d_dilate.py

示例15: __init__

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import densenet121 [as 别名]
def __init__(self, device="cpu"):
        super().__init__(device=device)
        self.model = models.densenet121(pretrained=True)
        self.model.to(self.device)
        self.model.eval() 
开发者ID:ShannonAI,项目名称:service-streamer,代码行数:7,代码来源:model.py


注:本文中的torchvision.models.densenet121方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。