當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。