我正在参加「掘金·启航计划」
在本教程中,您将学习如何使用迁移学习训练卷积神经网络进行图像分类。您可以在cs231n 笔记中阅读有关迁移学习的更多信息
摘要一些重要的内容:
在实践中,很少有人从头开始训练整个卷积网络(随机初始化),因为拥有足够多的数据用于训练的情况相对较少。相反,通常在非常大的数据集(例如 ImageNet,包含 120 万张图像和 1000 个类别)上预训练 ConvNet,然后将 ConvNet 用作感兴趣任务的初始化或固定特征提取器。
以下是两个主要的迁移学习场景:
- 微调卷积网络:不是随机初始化,而是使用预训练网络初始化,就像在 imagenet 1000 数据集上训练的网络一样。其余的训练看起来和往常一样。
- ConvNet 作为固定特征提取器:在这里,我们将冻结除最后一个全连接层之外的所有网络的权重。最后一个全连接层被替换为具有随机权重的新层,并且只训练这一层。
# 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 torch.backends.cudnn as cudnn
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
import matplotlib.pyplot as plt
import time
import os
import copy
cudnn.benchmark = True
plt.ion() # interactive mode
<matplotlib.pyplot._IonContext object at 0x7fe6d6d63890>
1. 加载数据
我们将使用 torchvision 和 torch.utils.data 包来加载数据。
要解决的问题是训练一个模型来对 蚂蚁和蜜蜂进行分类。大约有 120 个蚂蚁和蜜蜂的训练图像。每个类有 75 个验证图像。通常,如果从头开始训练,这是一个非常小的数据集进行泛化。由于使用的是迁移学习,训练完成后应该能够很好地泛化。
该数据集是 imagenet 的一个非常小的子集。
笔记
从这里下载数据 并将其解压缩到当前目录。
# Data augmentation and normalization for training
# Just normalization for validation
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
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 = 'data/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 可视化一些图像
可视化一些训练图像,以增强对数据集的了解。
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. 训练模型
现在,开始编写一个通用函数来训练模型。此后,将会完成:
- 调度学习率
- 保存最佳模型
在下文中,参数scheduler
是来自torch.optim.lr_scheduler
的 LR 调度程序对象 。
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(f'Epoch {epoch}/{num_epochs - 1}')
print('-' * 10)
# Each epoch has a training and validation phase
for phase in ['train', 'val']:
if phase == 'train':
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)
if phase == 'train':
scheduler.step()
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
print(f'{phase} Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')
# 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(f'Training complete in {time_elapsed // 60:.0f}m {time_elapsed % 60:.0f}s')
print(f'Best val Acc: {best_acc:4f}')
# load best model weights 加载最有模型的参数
model.load_state_dict(best_model_wts)
return model
2.1 可视化模型预测
写一个函数用于可视化一些预测结果和图像
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(f'predicted: {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. 微调卷积网络
加载预训练模型并重置最后一层的全连接层。
model_ft = models.resnet18(pretrained=True)
num_ftrs = model_ft.fc.in_features
# Here the size of each output sample is set to 2.
# Alternatively, it can be generalized to nn.Linear(num_ftrs, len(class_names)).
# 重置最后一层的全连接层
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)
/opt/conda/lib/python3.7/site-packages/torchvision/models/_utils.py:209: UserWarning:
The parameter 'pretrained' is deprecated since 0.13 and will be removed in 0.15, please use 'weights' instead.
/opt/conda/lib/python3.7/site-packages/torchvision/models/_utils.py:223: UserWarning:
Arguments other than a weight enum or `None` for 'weights' are deprecated since 0.13 and will be removed in 0.15. The current behavior is equivalent to passing `weights=ResNet18_Weights.IMAGENET1K_V1`. You can also use `weights=ResNet18_Weights.DEFAULT` to get the most up-to-date weights.
Downloading: "https://download.pytorch.org/models/resnet18-f37072fd.pth" to /var/lib/jenkins/.cache/torch/hub/checkpoints/resnet18-f37072fd.pth
0%| | 0.00/44.7M [00:00<?, ?B/s]
11%|# | 4.86M/44.7M [00:00<00:00, 50.9MB/s]
23%|##3 | 10.4M/44.7M [00:00<00:00, 55.0MB/s]
71%|####### | 31.6M/44.7M [00:00<00:00, 131MB/s]
100%|##########| 44.7M/44.7M [00:00<00:00, 132MB/s]
3.1 训练和评估
CPU 大约需要 15-25 分钟。但在 GPU 上,需要不到一分钟的时间。
model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,
num_epochs=25)
Epoch 0/24
----------
train Loss: 0.6132 Acc: 0.6926
val Loss: 0.5789 Acc: 0.7255
Epoch 1/24
----------
train Loss: 0.4050 Acc: 0.8402
val Loss: 0.2714 Acc: 0.9085
Epoch 2/24
----------
train Loss: 0.6136 Acc: 0.7295
val Loss: 0.8891 Acc: 0.6405
Epoch 3/24
----------
train Loss: 0.5100 Acc: 0.8115
val Loss: 0.3516 Acc: 0.8431
Epoch 4/24
----------
train Loss: 0.4475 Acc: 0.8115
val Loss: 0.3633 Acc: 0.8497
Epoch 5/24
----------
train Loss: 0.4221 Acc: 0.8525
val Loss: 0.2715 Acc: 0.9020
Epoch 6/24
----------
train Loss: 0.6089 Acc: 0.7951
val Loss: 0.3743 Acc: 0.8758
Epoch 7/24
----------
train Loss: 0.2927 Acc: 0.8975
val Loss: 0.3007 Acc: 0.8824
Epoch 8/24
----------
train Loss: 0.2809 Acc: 0.9057
val Loss: 0.2833 Acc: 0.8954
Epoch 9/24
----------
train Loss: 0.3687 Acc: 0.8934
val Loss: 0.2710 Acc: 0.9020
Epoch 10/24
----------
train Loss: 0.3821 Acc: 0.8525
val Loss: 0.2831 Acc: 0.8954
Epoch 11/24
----------
train Loss: 0.2220 Acc: 0.9303
val Loss: 0.2839 Acc: 0.8954
Epoch 12/24
----------
train Loss: 0.3685 Acc: 0.8607
val Loss: 0.2736 Acc: 0.9085
Epoch 13/24
----------
train Loss: 0.2422 Acc: 0.9180
val Loss: 0.3110 Acc: 0.8758
Epoch 14/24
----------
train Loss: 0.3219 Acc: 0.8648
val Loss: 0.3817 Acc: 0.8693
Epoch 15/24
----------
train Loss: 0.3273 Acc: 0.8730
val Loss: 0.2646 Acc: 0.9085
Epoch 16/24
----------
train Loss: 0.2359 Acc: 0.9098
val Loss: 0.2885 Acc: 0.8954
Epoch 17/24
----------
train Loss: 0.3401 Acc: 0.8156
val Loss: 0.2633 Acc: 0.9216
Epoch 18/24
----------
train Loss: 0.2560 Acc: 0.8770
val Loss: 0.2620 Acc: 0.9020
Epoch 19/24
----------
train Loss: 0.3121 Acc: 0.8811
val Loss: 0.2613 Acc: 0.9216
Epoch 20/24
----------
train Loss: 0.3615 Acc: 0.8443
val Loss: 0.2584 Acc: 0.9150
Epoch 21/24
----------
train Loss: 0.3113 Acc: 0.8770
val Loss: 0.2586 Acc: 0.9150
Epoch 22/24
----------
train Loss: 0.3119 Acc: 0.8689
val Loss: 0.2583 Acc: 0.9085
Epoch 23/24
----------
train Loss: 0.2458 Acc: 0.8811
val Loss: 0.2455 Acc: 0.9150
Epoch 24/24
----------
train Loss: 0.2875 Acc: 0.8648
val Loss: 0.2770 Acc: 0.8954
Training complete in 1m 6s
Best val Acc: 0.921569
visualize_model(model_ft)
4. ConvNet 作为固定特征提取器
在此,需要冻结除最后一层之外的所有网络参数。需要设置冻结参数requires_grad = False
,以便在backward()
不计算梯度。
在此处的文档中阅读有关此内容的更多信息 。
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
# opposed 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)
/opt/conda/lib/python3.7/site-packages/torchvision/models/_utils.py:209: UserWarning:
The parameter 'pretrained' is deprecated since 0.13 and will be removed in 0.15, please use 'weights' instead.
/opt/conda/lib/python3.7/site-packages/torchvision/models/_utils.py:223: UserWarning:
Arguments other than a weight enum or `None` for 'weights' are deprecated since 0.13 and will be removed in 0.15. The current behavior is equivalent to passing `weights=ResNet18_Weights.IMAGENET1K_V1`. You can also use `weights=ResNet18_Weights.DEFAULT` to get the most up-to-date weights.
4.1 训练和评估
在 CPU 上,与之前的情况相比,这将花费大约一半的时间。这是预期的,因为不需要为大多数网络参数计算梯度。当然,前向传播计算是免不了的。
model_conv = train_model(model_conv, criterion, optimizer_conv,
exp_lr_scheduler, num_epochs=25)
Epoch 0/24
----------
train Loss: 0.8283 Acc: 0.6680
val Loss: 0.2313 Acc: 0.9412
Epoch 1/24
----------
train Loss: 0.3411 Acc: 0.8566
val Loss: 0.2130 Acc: 0.9085
Epoch 2/24
----------
train Loss: 0.4557 Acc: 0.7951
val Loss: 0.2120 Acc: 0.9346
Epoch 3/24
----------
train Loss: 0.3622 Acc: 0.8402
val Loss: 0.2383 Acc: 0.9085
Epoch 4/24
----------
train Loss: 0.5417 Acc: 0.7623
val Loss: 0.1973 Acc: 0.9412
Epoch 5/24
----------
train Loss: 0.4069 Acc: 0.8402
val Loss: 0.2052 Acc: 0.9477
Epoch 6/24
----------
train Loss: 0.4072 Acc: 0.7869
val Loss: 0.2844 Acc: 0.8824
Epoch 7/24
----------
train Loss: 0.3897 Acc: 0.8361
val Loss: 0.1749 Acc: 0.9477
Epoch 8/24
----------
train Loss: 0.3548 Acc: 0.8197
val Loss: 0.1757 Acc: 0.9477
Epoch 9/24
----------
train Loss: 0.3292 Acc: 0.8484
val Loss: 0.1728 Acc: 0.9477
Epoch 10/24
----------
train Loss: 0.4108 Acc: 0.8115
val Loss: 0.1748 Acc: 0.9412
Epoch 11/24
----------
train Loss: 0.4019 Acc: 0.8033
val Loss: 0.1815 Acc: 0.9477
Epoch 12/24
----------
train Loss: 0.4609 Acc: 0.7869
val Loss: 0.1933 Acc: 0.9281
Epoch 13/24
----------
train Loss: 0.4383 Acc: 0.7828
val Loss: 0.1774 Acc: 0.9477
Epoch 14/24
----------
train Loss: 0.2799 Acc: 0.8730
val Loss: 0.1831 Acc: 0.9412
Epoch 15/24
----------
train Loss: 0.3141 Acc: 0.8443
val Loss: 0.1811 Acc: 0.9477
Epoch 16/24
----------
train Loss: 0.2609 Acc: 0.9139
val Loss: 0.1956 Acc: 0.9346
Epoch 17/24
----------
train Loss: 0.3234 Acc: 0.8279
val Loss: 0.1788 Acc: 0.9477
Epoch 18/24
----------
train Loss: 0.3325 Acc: 0.8607
val Loss: 0.1541 Acc: 0.9477
Epoch 19/24
----------
train Loss: 0.3555 Acc: 0.8361
val Loss: 0.1735 Acc: 0.9477
Epoch 20/24
----------
train Loss: 0.3300 Acc: 0.8443
val Loss: 0.1767 Acc: 0.9608
Epoch 21/24
----------
train Loss: 0.3155 Acc: 0.8607
val Loss: 0.1737 Acc: 0.9477
Epoch 22/24
----------
train Loss: 0.3697 Acc: 0.8443
val Loss: 0.1803 Acc: 0.9281
Epoch 23/24
----------
train Loss: 0.2814 Acc: 0.8648
val Loss: 0.1667 Acc: 0.9477
Epoch 24/24
----------
train Loss: 0.3470 Acc: 0.8525
val Loss: 0.2084 Acc: 0.9281
Training complete in 0m 39s
Best val Acc: 0.960784
visualize_model(model_conv)
plt.ioff()
plt.show()
5. 进一步学习
如果您想了解有关迁移学习应用的更多信息,请查看计算机视觉量化迁移学习教程。