原官方網(wǎng)頁:https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
通過本教程,你將學到如何使用遷移學習訓練你的網(wǎng)絡(luò)孵稽。你可以在cs231n notes了解更多關(guān)于遷移學習
引用一些筆記:
- 實際中,基本沒有人會從零開始(隨機初始化)訓練一個完整的卷積網(wǎng)絡(luò)莉撇,因為相對于網(wǎng)絡(luò),很難得到一個足夠大的數(shù)據(jù)集[網(wǎng)絡(luò)很深, 需要足夠大數(shù)據(jù)集]譬胎。通常的做法是在一個很大的數(shù)據(jù)集上進行預(yù)訓練得到卷積網(wǎng)絡(luò)
ConvNet
, 然后將這個ConvNet
的參數(shù)作為目標任務(wù)的初始化參數(shù)或者固定這些參數(shù)
以下是應(yīng)用遷移學習的兩種場景:
- 微調(diào)
Convnet
:使用預(yù)訓練的網(wǎng)絡(luò)(如在imagenet 1000
上訓練而來的網(wǎng)絡(luò))來初始化自己的網(wǎng)絡(luò)磕蛇,而不是隨機初始化。其他的訓練步驟不變囱桨。 - 將
Convnet
看成固定的特征提取器仓犬。首先固定ConvNet
除了最后的全連接層外的其他所有層。最后的全連接層被替換成一個新的隨機初始化的層舍肠,只有這個新的層會被訓練[只有這層參數(shù)會在反向傳播時更新]
# License: BSD
# Author: Sasank Chilamkurthy
from __future__ import print_function, division
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
import matplotlib.pyplot as plt
import time
import os
import copy
plt.ion() # interactive mode
1. 數(shù)據(jù)加載
我們通常會使用torchvision和torch .utils.data
包來加載數(shù)據(jù)
今天要解決的問題是訓練一個模型來分類螞蟻ants
和蜜蜂bees
搀继。ants和bees各有約120張訓練圖片窘面。每個類有75張驗證圖片。從零開始在如此小的數(shù)據(jù)集上進行訓練通常是很難泛化的叽躯。由于我們使用遷移學習财边,模型的泛化能力會相當好
這個數(shù)據(jù)集是imagenet
的子集,可以在這里下載
# 訓練集數(shù)據(jù)增廣和歸一化
# 在驗證集上僅僅歸一化
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224), # 隨機裁剪一個area之后再resize
transforms.RandomHorizontalFlip(), # 隨機水平翻轉(zhuǎn)
transforms.ToTensor(),
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'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
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")
1.1 可視化一些數(shù)據(jù)
我們可視化了一些訓練圖片來明白數(shù)據(jù)增廣操作
def imshow(inp, title=None):
"""Imshow for Tensor."""
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
# Get a batch of training data
inputs, classes = next(iter(dataloaders['train']))
# Make a grid from batch
out = torchvision.utils.make_grid(inputs)
imshow(out, title=[class_names[x] for x in classes])
2. 訓練網(wǎng)絡(luò)
現(xiàn)在我們寫一個通用的函數(shù)來訓練網(wǎng)絡(luò)点骑。我們將展示:
- 調(diào)整學習速率
- 保存最好的模型
如下制圈,參數(shù)scheduler
是一個來自torch.optim.lr_scheduler
的學習速率調(diào)整類的對象(LR scheduler object
)
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 {}/{}'.format(epoch, num_epochs - 1))
print('-' * 10)
# Each epoch has a training and validation phase
for phase in ['train', 'val']:
if phase == 'train':
scheduler.step()
model.train() # Set model to training mode
else:
model.eval() # Set model to evaluate mode
running_loss = 0.0
running_corrects = 0
# Iterate over data.
for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward
# track history if only in train
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
# backward + optimize only if in training phase
if phase == 'train':
loss.backward()
optimizer.step()
# statistics
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('{} Loss: {:.4f} Acc: {:.4f}'.format(
phase, epoch_loss, epoch_acc))
# deep copy the model
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
best_model_wts = copy.deepcopy(model.state_dict())
print()
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(
time_elapsed // 60, time_elapsed % 60))
print('Best val Acc: {:4f}'.format(best_acc))
# load best model weights
model.load_state_dict(best_model_wts)
return model
2.1 可視化模型的預(yù)測結(jié)果
一個通用的展示少量預(yù)測圖片的函數(shù)
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]):
images_so_far += 1
ax = plt.subplot(num_images//2, 2, images_so_far)
ax.axis('off')
ax.set_title('predicted: {}'.format(class_names[preds[j]]))
imshow(inputs.cpu().data[j])
if images_so_far == num_images:
model.train(mode=was_training)
return
model.train(mode=was_training)
3. 微調(diào)convnent
加載預(yù)訓練模型并且重置最后一個全連接層
model_ft = models.resnet18(pretrained=True)
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, 2)
model_ft = model_ft.to(device)
criterion = nn.CrossEntropyLoss()
# Observe that all parameters are being optimized
optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)
# Decay LR by a factor of 0.1 every 7 epochs
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)
3.1 訓練并評估
在CPU上將耗時大約15-25分鐘,在GPU上將花少于1分鐘的時間
- 訓練
model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,
num_epochs=25)
- output
Epoch 0/24
----------
train Loss: 0.6849 Acc: 0.6762
val Loss: 0.2146 Acc: 0.9281
.
.
.
Epoch 23/24
----------
train Loss: 0.2282 Acc: 0.9139
val Loss: 0.2709 Acc: 0.8954
Epoch 24/24
----------
train Loss: 0.3081 Acc: 0.8566
val Loss: 0.3045 Acc: 0.9020
Training complete in 0m 58s
Best val Acc: 0.928105
- 可視化
visualize_model(model_ft)
4. 將convnent
看成特征提取器
這里畔况,我們將凍結(jié)全部網(wǎng)絡(luò),除了最后一層慧库。我們應(yīng)該將需要設(shè)置欲凍結(jié)的參數(shù)的requires_grad == False
跷跪,這樣在反向傳播backward()
的時候他們的梯度就不會被計算
更多關(guān)于grad
的文檔在這里
model_conv = torchvision.models.resnet18(pretrained=True)
# 最重要的一步
for param in model_conv.parameters():
param.requires_grad = False
# Parameters of newly constructed modules have requires_grad=True by default
num_ftrs = model_conv.fc.in_features
model_conv.fc = nn.Linear(num_ftrs, 2)
model_conv = model_conv.to(device)
criterion = nn.CrossEntropyLoss()
# Observe that only parameters of final layer are being optimized as
# opoosed to before.
optimizer_conv = optim.SGD(model_conv.fc.parameters(), lr=0.001, momentum=0.9)
# Decay LR by a factor of 0.1 every 7 epochs
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)
4.1 訓練和評估
在CPU上,固定參數(shù)相比于之前的作為初始化參數(shù)的做法齐板,會節(jié)約大約一半的時間吵瞻。這是可以預(yù)期的,因為網(wǎng)絡(luò)的絕大部分參數(shù)的梯度不會在反向傳播中計算甘磨。(但是這些參數(shù)是參與前向傳播的)
- 訓練
model_conv = train_model(model_conv, criterion, optimizer_conv,
exp_lr_scheduler, num_epochs=25)
- output
Epoch 0/24
----------
train Loss: 0.6421 Acc: 0.6557
val Loss: 0.4560 Acc: 0.7451
Epoch 1/24
----------
train Loss: 0.4694 Acc: 0.7746
val Loss: 0.1616 Acc: 0.9608
Epoch 2/24
----------
train Loss: 0.4500 Acc: 0.7746
val Loss: 0.3041 Acc: 0.8627
.
.
.
Epoch 24/24
----------
train Loss: 0.3382 Acc: 0.8566
val Loss: 0.1605 Acc: 0.9542
Training complete in 0m 46s
Best val Acc: 0.967320
- 可視化
visualize_model(model_conv)
plt.ioff()
plt.show()