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