ADVANCE Day43

@浙大疏锦行

Day43作业:迁移学习


1. 简介

在本次作业中,我们将探索迁移学习(Transfer Learning)的概念和应用。迁移学习是一种机器学习方法,其中为一项任务开发的模型被用作第二项任务的起点。这种方法在深度学习中尤其流行,因为它可以显著减少训练时间和数据需求。

我们将使用预训练的卷积神经网络(CNN)模型,并在其基础上进行微调(Fine-tuning),以解决一个特定的图像分类问题。


2. 环境设置

首先,我们需要导入所有必要的库。

python 复制代码
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import datasets, models, transforms
import matplotlib.pyplot as plt
import numpy as np
import os
import time
import copy

plt.ion()   # interactive mode

3. 数据加载与预处理

我们使用 torchvision 提供的 datasets.ImageFolder 来加载数据,并使用 transforms 进行数据增强和标准化。

python 复制代码
# 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")

3.1 可视化部分图像

让我们看看一些训练图像。

python 复制代码
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])

4. 模型训练函数

我们定义一个通用的训练函数,它将在训练和验证阶段执行模型的前向传播、反向传播和优化。

python 复制代码
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

5. 迁移学习策略

我们将尝试两种主要的迁移学习策略:

  1. 特征提取(Feature Extraction):冻结预训练模型的所有权重,只训练新添加的分类器层。
  2. 微调(Fine-tuning):解冻整个模型或部分预训练层,并与新分类器一起进行端到端的训练。

5.1 方法一:特征提取

我们加载一个预训练好的 ResNet18 模型,并重置其最终的全连接层。

python 复制代码
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)
训练模型
python 复制代码
model_conv = train_model(model_conv, criterion, optimizer_conv,
                         exp_lr_scheduler, num_epochs=25)

5.2 方法二:微调模型

这次,我们将训练所有参数。

python 复制代码
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)
训练模型
python 复制代码
model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=25)

6. 结果可视化

最后,我们创建一个函数来预测单个图像并展示结果。

python 复制代码
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)

visualize_model(model_conv)
plt.ioff()
plt.show()

7. 总结

通过本次作业,我们成功地应用了迁移学习来解决一个二分类问题。我们比较了特征提取和微调两种策略,并观察到它们都能在相对较少的数据和训练轮次下达到很好的效果。微调通常能获得更好的性能,但需要更多的计算资源和更小心的学习率调整。


复制代码
相关推荐
雨大王5121 天前
汽车焊接工艺自适应控制技术的系统解析与工业实践
人工智能·python·汽车
小途软件1 天前
基于深度学习的垃圾识别分类研究与实现
人工智能·pytorch·python·深度学习·语言模型
DisonTangor1 天前
UltraShape 1.0: 高保真三维形状生成:基于可扩展几何优化
人工智能·3d·开源·aigc
Salt_07281 天前
DAY 58 经典时序预测模型 1
人工智能·python·深度学习·神经网络·机器学习
乾元1 天前
企业无线的 AI 频谱与功率自动优化——从人工勘测到“可学习的无线网络”(含真实室内工程案例)
服务器·网络·人工智能·网络协议·安全·信息与通信
数说星榆1811 天前
农业智能化:作物识别与生长模拟
人工智能
X_Cosmic1 天前
从零开始:YOLO11 训练 DOTA OBB 遥感数据旋转框目标检测
python·yolo·目标检测
Hello.Reader1 天前
PyFlink 向量化 UDF(Vectorized UDF)Arrow 批传输原理、pandas 标量/聚合函数、配置与内存陷阱、五种写法一网打尽
python·flink·pandas
Warren2Lynch1 天前
如何使用Visual Paradigm AI Chatbot创建3D打印机UML状态机图:综合指南
人工智能·uml