1. 程式人生 > >PyTorch官方教程(四)-Transfer_Learning_Tutorial

PyTorch官方教程(四)-Transfer_Learning_Tutorial

通常情況下, 我們不會從頭訓練整個神經網路, 更常用的做法是先讓模型在一個非常大的資料集上進行預訓練, 然後將預訓練模型的權重作為當前任務的初始化引數, 或者作為固定的特徵提取器來使用. 既通常我們需要面對的是下面兩種情形:

  • Finetuning the convnet: 在一個已經訓練好的模型上面進行二次訓練
  • ConvNet as fixed feature extractor: 此時, 我們會將整個網路模型的權重引數固定, 並且將最後一層全連線層替換為我們希望的網路層. 此時, 相當於是將前面的整個網路當做是一個特徵提取器使用.

Load Data

我們將會使用torch.utils.data

包來載入資料. 我們接下來需要解決的問題是訓練一個模型來分類螞蟻和蜜蜂. 我們總共擁有120張訓練圖片, 具有75張驗證圖片.

data_transforms = {
    "train": transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(), # 注意轉換成tensor後, 畫素會變成[0,1]之間的浮點數
        transforms.Normalize([0.485
,0.456,0.406],[0.229,0.224,0.225]) ]), "val": transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225]) ]) } data_dir = "hymenoptera_data" # from torchvision import datasets
image_datasets = {x:datasets.ImageFolder(root=os.path.join(data_dir, x), transform=data_transforms[x]) for x in ["train", "val"]} dataloaders = {x:torch.utils.data.DataLoader(image_datasets[x]), batch_size=4, shuffle=True, num_workers=4) for x in ["train", "val"]} dataset_sizes = {x:len(image_datasets[x]) for x in ["train", "val"]} class_names = image_datasets["train"].classes device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

Visualize a few images

def imshow(inp, title=None):
    inp = inp.numpy().transpose((1,2,0))
    mean = np.array([0.485, 0.456, 0.406])
    std = np.array([0.229, 0.224, 0.225])
    inp = std * inp + mean
    inp = np.clip(inp, 0, 1)
    plt.imshow(inp)
    if title is not None:
        plt.title(title)
    plt.pause(0.001)  # pause a bit so that plots are updated

inputs, class_ids = next(iter(dataloaders["train"])) # 獲取一個batch
out = torchvision.utils.make_grid(inputs)
imshow(out, title=[class_names[x] for x in class_ids])

Training the model

接下來, 讓我們定義一個簡單的函式來訓練模型, 我們會利用LR scheduler物件torch.optim.lr_scheduler設定lr scheduler, 並且儲存最好的模型.

def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
    since = time.time()

    best_model_wts = copy.deepcopy(model.state_dict())
    best_acc = 0.0

    for epoch in range(num_epochs):
        print(epoch)

        for phase in ["train", "val"]:
            if phase == "train":
                model.train()
            else:
                model.eval()

            running_loss = 0.0
            running_corrects = 0

            for inputs, labels in dataloaders[phase]:
                inputs = inputs.to(device)
                labels = labels.to(device)

                optimizer.zero_grad()

                # forward
                with torch.set_grad_enabled(phase == "train"):
                    outputs = model(inputs)
                    _, preds = torch.max(outputs,1) # preds代表最大值的座標, 相當於獲取了最大值對應的類別
                    loss = criterion(outputs, labels)

                    if phase = "train": # 只有處於train模式時, 來更新權重
                        loss.backward()
                        optimizer.step()
                # 統計狀態
                running_loss += loss.item() * inputs.size(0)
                running_corrects += torch.sum(preds==labels.data)

            epoch_loss = running_loss / dataset_sizes[phase]
            epoch_acc = running_corrects.double() / dataset_sizes[phase]
            print(phase, epoch_loss, epoch_acc)

            if phase == "val" and epoch_acc > best_acc:
                best_acc = epoch_acc
                best_model_wts = copy.deepcopy(model.state_dict())

    time_elapsed = time.time() - since
    print(time_elapsed)
    print(best_acc)

    # load best model weights
    model.load_state_dic(best_model_wts)
    return model

Visualizing the model predictions

下面的程式碼用於顯示預測結果

def visualize_model(model, num_images=6):
    was_training = model.training
    model.eval()
    images_so_far = 0
    fig = plt.figure()

    with torch.no_grad(): # 不計算梯度
        for i, (inputs, labels) in enumerate(dataloaders["val"]):
            inputs = inputs.to(device)
            labels = labels.to(device)

            outputs = model(inputs)
            _, preds = torch.max(outputs,1)

            for j in range(inputs.size()[0]): # 或者batch size
                images_so_far += 1
                ax = plt.subplot(num_images//2, 2, images_so_far)
                ax.axis("off")
                ax.set_title(class_names[preds[j]])
                imshow(inputs.cpu().data[j]) # 由於imshow不能作用在gpu的資料上, 因此需要先將其移動到cpu上.

                if images_so_far == num_images:
                    model.train(mode = was_training)
                    return
        model.train(mode=was_training)

FineTuning the convnet

載入預訓練模型, 並重置最後一層全連線層

# from torchvisioin import models
model_ft = models.resnet18(pretrained=True)
num_ftrs = model_ft.fc.in_features
model_ft = model_ft.to(device)

criterion = nn.CrossEntropyLoss()


# 這裡是讓所有的引數都進行更新迭代
optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)

exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)

Train and evaluate

呼叫剛剛定義的訓練函式對模型進行訓練

model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=25)

visualize_model(model_ft)

Convnet as Fixed Feature Extractor

假設我們需要將除了最後一層的其它層網路的引數固定(freeze), 為此, 我們需要將這些引數的requires_grad屬性設定為False.

model_conv = torchvision.models.resnet18(pretrained=True)
for param in model_conv.parameters():
    param.requires_grad = False

# 將最後一層fc層重新指向一個新的Module, 其內部引數的requires_grad屬性預設為True
num_ftrs = model_conv.fc.in_features
model_conv.fc = nn.Linear(num_ftrs,2)

model_conv = model.to(device)

criterion = nn.CrossEntropyLoss()

optimizer_conv = optim.SGD(model_conv.fc.parameters(), lr=0.001, momentum=0.9)

exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)

Train and evaluate

model_conv = train_model(model_conv, criterion, optimizer_conv, exp_lr_scheduler, num_eopch=25)
visualize_model(model_conv)