pytorch学习——第四章迁移学习

迁移学习

迁移学习是在已有模型上进行学习
使用resnet18进行迁移学习,实现蚂蚁和蜜蜂的二分类任务

  1. 可以在resnet18参数权重基础上继续训练
  2. 可以冻结resnet18的卷积层,仅训练最后的全连接层
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

transforms

注意,transform是在每次按批次读取dataset时起作用,如果加入随机变换项可以扩充数据集。

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

datasets

datasets.ImageFolder能够读取图片文件夹中的数据,并按照文件名作为分类classes
torch.utils.data.DataLoader能够按批次加载数据

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)#num_workers是线程数
               for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_names = image_datasets['train'].classes

训练模块

def train_model(model, loss_fun, opt, sche, epoches=25):
    since = time.time()
    best_model_wts = copy.deepcopy(model.state_dict())
    best_acc = 0.0
    
    for epoch in range(epoches):
        for phase in ['train', 'val']:
            if phase == 'train':
                model.train()
            else:
                model.eval()
            e_loss = 0
            e_corrects = 0
            for x, y in dataloaders[phase]:
                x = x.cuda()
                y = y.cuda()
                
                opt.zero_grad()
                with torch.set_grad_enabled(phase == 'train'):
                    outputs = model(x)
                    _,preds = torch.max(outputs, 1)
                    loss = loss_fun(outputs, y)
                    
                    if phase == 'train':
                        loss.backward()
                        opt.step()
                e_loss += loss.item() * inputs.size(0)
                e_corrects += torch.sum(preds == y.data)
            if phase == 'train':
                sche.step()
            e_loss = e_loss / dataset_sizes[phase]
            e_acc = e_corrects.double() / dataset_sizes[phase]
            print('epch:{} {} Loss:{:.4f} Acc {:.4f}'.format(
                epoch, phase, e_loss, e_acc))
            if phase == 'val' and e_acc > best_acc:
                best_acc = e_acc
                best_model_wts = copy.deepcopy(model.state_dict())
   
    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))
    model.load_state_dict(best_model_wts)
    return model

主函数和训练参数

model_conv = train_model(model_conv, criterion, opt_conv,
                         sche_conv, 25)

最终训练准确率在0.97左右

全部训练
model_ft = models.resnet18(pretrained=True)
num_ftrs = model_ft.fc.in_features#最后fc层的输入
model_ft.fc = nn.Linear(num_ftrs, 2)

model_ft = model_ft.cuda()
loss_fun = nn.CrossEntropyLoss().cuda()

opt = optim.SGD(model_ft.parameters(), lr = 0.001, momentum=0.9)
sche = lr_scheduler.StepLR(opt, step_size=7, gamma=0.1)
仅训练fc层
model_conv = torchvision.models.resnet18(pretrained=True)
for param in model_conv.parameters():
    param.requires_grad = False
num_ftrs = model_conv.fc.in_features
model_conv.fc = nn.Linear(num_ftrs, 2)
model_conv = model_conv.cuda()
criterion = nn.CrossEntropyLoss()
opt_conv = optim.SGD(model_conv.fc.parameters(), lr=0.001, momentum=0.9)
sche_conv = exp_lr_scheduler = lr_scheduler.StepLR(opt_conv, step_size=7, gamma=0.1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值