【PyTorch】教程:Transfer learning

news2025/1/18 10:49:57

Transfer learning

实际工作中,只有很少的人从头开始训练 CNN,因为很难获得大量的样本。一般情况下,会通过调用预训练模型,例如 ConvNetImageNet1.2 M 图像 1000 个类别),可以用 ConvNet 初始化,也可以作为特征提取器 用于感兴趣的任务或领域。

有两种主要的迁移学习:

  • 微调 Convnet : 代替随机初始化,用预训练的网络模型进行初始化,就像在 ImageNet1000 的数据集上训练,剩下的训练就很常见了。
  • ConvNet 作为固定的特征提取器: 冻结网络的权重,除了最后的全连接层,最后的全连接层被替换新的随机权重,然后只训练这一层。

加载数据

我们利用 torchvision 和 torch.utils.data 包加载数据。

今天的任务是训练 ants 和 bees 分类器模型,每个类别 120 张训练图,75 张图验证图,

数据集下载地址

Finetune

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 

# 对训练数据进行增强和归一化
# 对验证数据做归一化
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]),
    ]),
}

# dataset and dataloader
data_dir = "../../../datasets/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") if torch.cuda.is_available() else torch.device("cpu")

# Visualize a few images
# Let’s visualize a few training images so as to understand the data augmentations.
# 
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)
  
# 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])

# training
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':
                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()

                # statisitc
                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'Traing 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
  
# Generic function to display predictions for a few images
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(model=was_training)


# Load a pretrained model and reset final fully connected layer.
model_finetune = models.resnet18(pretrained=True)
num_ftrs = model_finetune.fc.in_features

# here the size of each output sample is set to 2
# it can be generalized to nn.Linear
model_finetune.fc = nn.Linear(num_ftrs, 2)

model_finetune = model_finetune.to(device)

criterion = nn.CrossEntropyLoss()

# Observe that all parameters are being optimized
optimizer_finetune = optim.SGD(
    model_finetune.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_finetune, step_size=7, gamma=0.1)

# train and evaluate
model_finetune = train_model(model=model_finetune,
                            criterion=criterion, optimizer=optimizer_finetune,
                            scheduler=exp_lr_scheduler, num_epochs=25)
                          
# 可视化模型效果
visualize_model(model_finetune)

Output exceeds the size limit. Open the full output data in a text editor
train Loss: 0.6425 Acc: 0.6230
val Loss: 0.2763 Acc: 0.9150

Epoch 1/24
----------
train Loss: 0.4966 Acc: 0.8074
val Loss: 0.3128 Acc: 0.8693

Epoch 2/24
----------
train Loss: 0.4395 Acc: 0.8402
val Loss: 0.2923 Acc: 0.8562

Epoch 3/24
----------
train Loss: 0.3743 Acc: 0.8402
val Loss: 0.2049 Acc: 0.9281

Epoch 4/24
----------
train Loss: 0.2655 Acc: 0.8852
val Loss: 0.1841 Acc: 0.9346

Epoch 5/24
----------
...
val Loss: 0.1862 Acc: 0.9412

Traing complete in 1m 0 s
Best val Acc: 0.9477

在这里插入图片描述

固定为特征提取器

现在我们来冻结网络,除了最后一层。我们需要设置 requires_grad = False 来冻结参数,这样的话就不会计算梯度。查看更多

关键代码

# set requires_grad = False
for param in model_conv.parameters():
    param.requires_grad = False
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

# 对训练数据进行增强和归一化
# 对验证数据做归一化
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]),
    ]),
}

# dataset and dataloader
data_dir = "../../../datasets/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") if torch.cuda.is_available() else torch.device("cpu")

# Visualize a few images
# Let’s visualize a few training images so as to understand the data augmentations.
#


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)

# 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])

# training


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':
                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()

                # statisitc
                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'Traing 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

# Generic function to display predictions for a few images


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(model=was_training)



### 不同的地方
# Load a pretrained model and reset final fully connected layer.
# model_finetune = models.resnet18(pretrained=True)
# num_ftrs = model_finetune.fc.in_features

model_conv = models.resnet18(pretrained=True)
# set requires_grad = False
for param in model_conv.parameters():
    param.requires_grad = False
    
# 新的结构模块默认 requires_grad=True
num_ftrs = model_conv.fc.in_features
# here the size of each output sample is set to 2
# it can be generalized to nn.Linear
model_conv.fc = nn.Linear(num_ftrs, 2)

model_conv = model_conv.to(device)

criterion = nn.CrossEntropyLoss()

# Observe that all parameters are being optimized
optimizer_finetune = optim.SGD(
    model_conv.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_finetune, step_size=7, gamma=0.1)

# train and evaluate
model_conv = train_model(model=model_conv,
                            criterion=criterion, optimizer=optimizer_finetune,
                            scheduler=exp_lr_scheduler, num_epochs=25)
visualize_model(model_conv)

Output exceeds the size limit. Open the full output data in a text editor
Epoch 0/24
----------
train Loss: 0.6819 Acc: 0.6270
val Loss: 0.1885 Acc: 0.9477

Epoch 1/24
----------
train Loss: 0.4212 Acc: 0.7992
val Loss: 0.1760 Acc: 0.9477

Epoch 2/24
----------
train Loss: 0.5423 Acc: 0.7828
val Loss: 0.7761 Acc: 0.7059

Epoch 3/24
----------
train Loss: 0.6406 Acc: 0.7377
val Loss: 0.2656 Acc: 0.9216

Epoch 4/24
----------
train Loss: 0.5401 Acc: 0.7951
val Loss: 0.2485 Acc: 0.8954
...
val Loss: 0.1679 Acc: 0.9542

Traing complete in 0m 45 s
Best val Acc: 0.9542

在这里插入图片描述

【参考】

TRANSFER LEARNING FOR COMPUTER VISION TUTORIAL

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/335179.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Verilog 组合逻辑一些注意事项

reg型变量不一定会被综合成触发器 【参考链接】 以下是verilog-2001的标准中对wire和reg的定义如下: wire: A wire net can be used for nets that are driven by a single gate or continuous assignment. reg: Assignments to a reg are…

微信小程序 Springboot java nodejs图书馆图书借阅系统

图书借阅管理系统用户端是基于微信小程序,管理员端是基于java编程语言,mysql数据库, idea工具开发,本系统是分为用户和管理员两个角色,其中用户的主要功能有注册登陆小程序,查看系统功能,图书搜…

VB 消息、消息队列、事件

windows是图像化界面,多任务消息windows系统将消息(大的结构)发给其他应用程序Windows消息包含了所有的外部输入或者计算机内部信息,应用程序的消息队列先进先出,Windows消息的循环--每个应用程序里有自己的消息循环外…

微信卸载后重装的聊天记录还能找回吗?

很多人微信卸载后,问能不能恢复之前的聊天记录? 我想大家肯定都去百度搜索了,能搜出来可行的办法了么,没有是吧,那就看看我能不能帮到你,根据我的经验来解决。 答:理论上是不能的,因…

SpringBoot集成swagger3(CD2207)(内含教学视频+源代码)

SpringBoot集成swagger3(CD2207)(内含教学视频源代码) 教学视频源代码下载链接地址:https://download.csdn.net/download/weixin_46411355/87435564 目录SpringBoot集成swagger3(CD2207)&#…

LeetCode栈与队列相关解法

栈与队列1. 用栈实现队列[232. 用栈实现队列](https://leetcode.cn/problems/implement-queue-using-stacks/)2. 用队列实现栈[225. 用队列实现栈](https://leetcode.cn/problems/implement-stack-using-queues/)两个队列实现一个队列实现3. 有效括号[20. 有效的括号](https://…

mysql使用innobackupex主从同步

目录 1.用innobackupex物理备份主库数据至文件夹 2.在从库用innobackupex恢复数据库 3.配置主从并启动从库 innobackupex是一款MySQL备份工具,备份速度快(通过直接copy物理文件),而且支持压缩、流式传输、加密等功能 新安装的数据库自带innobackupex…

程序的翻译环境和执行环境

程序环境和预处理🦖程序的翻译环境和执行环境🦖详解编译链接🐳 翻译环境🐳 详解编译过程🐳 运行环境🦖预处理详解🐳 预定义符号🐳 #define🦀 #define 定义标识符&#x1…

端到端模型(end-to-end)与非端到端模型

一、端到端(end to end) 从输入端到输出端会得到一个预测结果,将预测结果和真实结果进行比较得到误差,将误差反向传播到网络的各个层之中,调整网络的权重和参数直到模型收敛或者达到预期的效果为止,中间所…

9.关系查询处理和查询优化

其他章节索引 梳理 名词解释 代数优化:是指关系代数表达式的优化,也即按照一定规则,通过对关系代数表达式进行等价变换,改变代数表达式中操作的次序和组合,使查询更高效物理优化:是指存取路径和底层操作算…

类和对象(中)(二)

类和对象(中)(二)1.赋值运算符重载1.1运算符重载1.2赋值运算符重载1.3前置和后置重载2.const成员3.取地址及const取地址操作符重载🌟🌟hello,各位读者大大们你们好呀🌟🌟…

【Linux基础知识】

Linux基础知识 Linux基础知识 系统目录结构 /bin: 命令和应用程序。 /boot: 这里存放的是启动 Linux 时使用的一些核心文件,包括一些连接文件以及镜像文件。 /dev : dev 是 Device(设备) 的缩写, 该目录下存放的是 Linux 的外…

MySQL —— 内置函数

目录 内置函数 一、日期函数 二、字符串函数 三、数学函数 四、其他函数 内置函数 一、日期函数 函数名称描述current_date()获取当前日期current_time()获取当前时间current_timestamp()获取当前时间戳now()获取当前日期时间date(datetime)获取datetime参数的日期部分d…

【C→C++】打开C++世界的大门

文章目录前言什么是CC的发展史C的重要性1. 使用广泛度2. 工作领域的应用1. C关键字(C98)2. 命名空间2.1 命名空间的定义2.2 命名空间的使用2.3 std命名空间的使用惯例3. C输入&输出3.1 输入输出3.2 说明4. 缺省参数4.1 缺省参数概念4.2 缺省参数分类5. 函数重载5.1 函数重载…

作业帮发布新款AI学习桌,引领书桌行业智能化发展

2月9日,作业帮举办AI学习桌新品沟通会,宣布其独家开创的AI学习桌推出四个月内跻身天猫书桌单品GMV前四,作业帮将加大投入,正式进军书桌市场,并发布新款AI学习桌产品。AI伴学护眼护脊,颠覆传统书桌想象力作业…

一:Datart的下载、本地运行

前言:本文只是个人在使用datart的一个记录,仅供参考。如果有不一样的地方,欢迎评论或私信进行交流。datart 是新一代数据可视化开放平台,支持各类企业数据可视化场景需求,如创建和使用报表、仪表板和大屏,进…

ASEMI三相整流模块MDS100-16图片,MDS100-16尺寸

编辑-Z ASEMI三相整流模块MDS100-16参数: 型号:MDS100-16 最大重复峰值反向电压(VRRM):1600V 最大RMS电桥输入电压(VRMS):1700V 最大平均正向整流输出电流(IF&#…

计算机网络|第二章 物理层|湖科大课程|从零开始的计网学习——物理层(计网入门就看这篇!)

图片来源于胡科大计算机网络课程,https://www.bilibili.com/video/BV1c4411d7jb?p20&vd_sourcedeb12d86dce7e419744a73045bc66364。文章非盈利商业用途,供博主与大家学习参考,如有侵权,请联系我删除!2.1物理层的基…

一起来体验一把ChatGPT,附详细的注册流程!

文章目录ChatGPT是什么ChatGPT效果体验ChatGPT详细注册流程i 步骤1ii 步骤2iii 步骤3ChatGPT是什么 ChatGPT是由人工智能实验室OpenAI 研发的通用聊天机器人,于2022年11月30日上线。ChatGPT的网页注册之后就可以免费试用。 用户与ChatGPT之间的对话互动包括了聊天…

doxygen注释生成api文档(二)

doxygen在实际项目中的应用 在上一篇文章中主要讲解了doxygen的注释规则,在本篇中将主要侧重doxygen在实际项目中的应用部署。 一、doxygen环境的安装 sudo apt install doxygen sudo apt install graphviz (生成dot时需要)二、创建Doxyge…