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


Python models.mobilenet_v2方法代码示例

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


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

示例1: test

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import mobilenet_v2 [as 别名]
def test():
    """ Compare the classification result of WarmMobileNetV2 versus torchvision mobilenet_v2. """
    new = WarmMobileNetV2()
    from torchvision.models import mobilenet_v2
    old = mobilenet_v2()
    state = old.state_dict()
    for k in list(state.keys()): # Map parameters of old, e.g. layer2.0.conv1.weight
        s = k.split('.') # to parameters of new, e.g. layer2-0-conv1.weight
        s = '-'.join(s[:-1])+'.'+s[-1]
        state[s] = state.pop(k)
    new.load_state_dict(state)
    warm.util.summary(old)
    warm.util.summary(new)
    x = torch.randn(1, 3, 224, 224)
    with torch.no_grad():
        old.eval()
        y_old = old(x)
        new.eval()
        y_new = new(x)
        if torch.equal(y_old, y_new):
            print('Success! Same results from old and new.')
        else:
            print('Warning! New and old produce different results.') 
开发者ID:blue-season,项目名称:pywarm,代码行数:25,代码来源:mobilenet.py

示例2: get_trained_model

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import mobilenet_v2 [as 别名]
def get_trained_model(args, device, train_loader, val_loader, criterion):
    if args.model == 'LeNet':
        model = LeNet().to(device)
        optimizer = torch.optim.Adadelta(model.parameters(), lr=1)
        scheduler = StepLR(optimizer, step_size=1, gamma=0.7)
        for epoch in range(args.pretrain_epochs):
            train(args, model, device, train_loader,
                  criterion, optimizer, epoch)
            scheduler.step()
    elif args.model == 'vgg16':
        model = VGG(depth=16).to(device)
        optimizer = torch.optim.SGD(model.parameters(), lr=0.01,
                                    momentum=0.9,
                                    weight_decay=5e-4)
        scheduler = MultiStepLR(
            optimizer, milestones=[int(args.pretrain_epochs*0.5), int(args.pretrain_epochs*0.75)], gamma=0.1)
        for epoch in range(args.pretrain_epochs):
            train(args, model, device, train_loader,
                  criterion, optimizer, epoch)
            scheduler.step()
    elif args.model == 'resnet18':
        model = models.resnet18(pretrained=False, num_classes=10).to(device)
        optimizer = torch.optim.SGD(model.parameters(), lr=0.01,
                                    momentum=0.9,
                                    weight_decay=5e-4)
        scheduler = MultiStepLR(
            optimizer, milestones=[int(args.pretrain_epochs*0.5), int(args.pretrain_epochs*0.75)], gamma=0.1)
        for epoch in range(args.pretrain_epochs):
            train(args, model, device, train_loader,
                  criterion, optimizer, epoch)
            scheduler.step()
    elif args.model == 'mobilenet_v2':
        model = models.mobilenet_v2(pretrained=True).to(device)

    if args.save_model:
        torch.save(model.state_dict(), os.path.join(
            args.experiment_data_dir, 'model_trained.pth'))
        print('Model trained saved to %s', args.experiment_data_dir)

    return model, optimizer 
开发者ID:microsoft,项目名称:nni,代码行数:42,代码来源:auto_pruners_torch.py

示例3: get_net

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import mobilenet_v2 [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

示例4: test_mobilenet_v2_model

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import mobilenet_v2 [as 别名]
def test_mobilenet_v2_model(input_var):
    original_model = torchvision_models.mobilenet_v2(pretrained=True)
    finetune_model = make_model(
        'mobilenet_v2',
        num_classes=1000,
        pool=default,
        pretrained=True,
    )
    copy_module_weights(original_model.classifier[-1], finetune_model._classifier)
    assert_equal_model_outputs(input_var, original_model, finetune_model) 
开发者ID:creafz,项目名称:pytorch-cnn-finetune,代码行数:12,代码来源:test_torchvision_models.py

示例5: test_mobilenet_v2_model_with_another_input_size

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import mobilenet_v2 [as 别名]
def test_mobilenet_v2_model_with_another_input_size(input_var):
    model = make_model('mobilenet_v2', num_classes=1000, pretrained=True)
    model(input_var) 
开发者ID:creafz,项目名称:pytorch-cnn-finetune,代码行数:5,代码来源:test_torchvision_models.py

示例6: __init__

# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import mobilenet_v2 [as 别名]
def __init__(self, classes, model='resnet18'):
        super(CNN, self).__init__()
        if (model == 'resnet18'):
            self.cnn = models.resnet18(pretrained=True)
            self.cnn.fc = nn.Linear(512, classes)
        elif (model == 'resnext50_32x4d'):

            self.cnn = models.resnext50_32x4d(pretrained=True)
            self.cnn.classifier = nn.Linear(1280, classes)
        elif (model == 'mobilenet_v2'):

            self.cnn = models.mobilenet_v2(pretrained=True)
            self.cnn.classifier = nn.Linear(1280, classes) 
开发者ID:black0017,项目名称:MedicalZooPytorch,代码行数:15,代码来源:COVIDNet.py


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