迁移学习
迁移学习是深度学习中一种常用的方法,核心思想为利用一个已经在其他训练集训练好的模型的材料(权重值或者特征层)来对目标训练集进行训练。
利用另一个训练集训练好的模型,我们可以:
- 提取其训练好的特征层(fixed feature extractor),去除其最后的分类层(全连接层)。注意,去除最后一层后保留的最后一层中是激活层,举个例子,在AlexNet中此层的维数为4096,这一层是非常重要的,因为它包含了分类信息值(通过Relu进行阈值提取)。在对于一个新的数据集来说,只需要在刚才提取出来的模型,在最后一层加上自己的分类层,一般为线性分类器(SVM或者softmax分类器),只对最后的那一层进行参数调整。
- 我们也可以对该网络进行Fine-tuning,与之前方法的提取特征方式相同,但调整参数的方式不同。finetuning即微调,这里即对模型中的所有参数在训练的过程中进行微调,不光光是调整最后一层的数据。在实际中也可以专门对整个网络层中的“表面”层进行调整,这是因为在整个网络层中,每层的特征在对整个训练集的训练中,特殊度会越来越高。也就是说,浅层的特征适用于大部分的数据集(比如边缘检测),但是深层的特征则与之前训练的数据集密切相关(假如你之前训练识别猫,那么这些层中包括了很多猫的独有特征)。
1、Funetuning演示:
演示平台:
python3.6、pytorch0.2
from __future__ import print_function, division import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler from torch.autograd import Variable import numpy as np import torchvision from torchvision import datasets, models, transforms import matplotlib.pyplot as plt import time import os plt.ion() # 开启plt的交互模式
接下来对数据进行部分展示,注意torch.utils.data.Dataloaders读取之后的数据为Tensor型,数据格式为C×W×H(C为颜色通道,W、H为图像宽和高),但是如果要用plt.imshow工具箱进行显示则必须转化为W×H×C的格式,另外也要进行反规范化。
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) # 进行少量延时来确保图像正确显示 # 获取训练数据中的一个 batch inputs, classes = next(iter(dataloaders['train'])) # 创建网格,注意之前的batch_size = 4 out = torchvision.utils.make_grid(inputs) imshow(out, title=[class_names[x] for x in classes])
接下来定义一个训练函数实现以下功能:
1、可以对学习率进行调控;
2、寻找并保存最佳的模型。
def train_model(model, criterion, optimizer, scheduler, num_epochs=25): since = time.time() # 计时开始 best_model_wts = model.state_dict() # 读取训练好的模型权重 best_acc = 0.0 for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, num_epochs - 1)) print('-' * 10) # 每个epoch中游训练和验证部分 for phase in ['train', 'val']: if phase == 'train': scheduler.step() model.train(True) else: model.train(False) running_loss = 0.0 running_corrects = 0 for data in dataloaders[phase]: inputs, labels = data # 如果使用GPU,则使用Variable if use_gpu: inputs = Variable(inputs.cuda()) labels = Variable(labels.cuda()) else: inputs, labels = Variable(inputs), Variable(labels) # 初始化梯度值 optimizer.zero_grad() # 前向 outputs = model(inputs) _, preds = torch.max(outputs.data, 1) loss = criterion(outputs, labels) # 后向,如果为训练集则进行梯度优化 if phase == 'train': loss.backward() optimizer.step() # 统计损失 running_loss += loss.data[0] running_corrects += torch.sum(preds == labels.data) epoch_loss = running_loss / dataset_sizes[phase] epoch_acc = running_corrects / dataset_sizes[phase] print('{} Loss: {:.4f} Acc: {:.4f}'.format( phase, epoch_loss, epoch_acc)) # 深度复制该模型 if phase == 'val' and epoch_acc > best_acc: best_acc = epoch_acc best_model_wts = 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)) # 载入最佳的模型 model.load_state_dict(best_model_wts) return model
对预测的图像数据进行可视化
定义一个可视化函数
def visualize_model(model, num_images=6): images_so_far = 0 fig = plt.figure() for i, data in enumerate(dataloaders['val']): inputs, labels = data if use_gpu: inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda()) else: inputs, labels = Variable(inputs), Variable(labels) outputs = model(inputs) _, preds = torch.max(outputs.data, 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: return
接下来对模型进行训练,在训练过程中对已经训练好的模型中的参数继续进行训练,然后在每个epoch中记录此刻最好的模型参数。
model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=25)
以下是训练结果,程序执行时间带CPU中为10-25分钟,GPU为1-2分钟。
(GTX1060为2分钟)
Epoch 0/24 ---------- train Loss: 0.1660 Acc: 0.6762 val Loss: 0.0445 Acc: 0.9542 Epoch 1/24 ---------- train Loss: 0.1141 Acc: 0.8033 val Loss: 0.0877 Acc: 0.8693 Epoch 2/24 ---------- train Loss: 0.1440 Acc: 0.7623 val Loss: 0.0484 Acc: 0.9346 Epoch 3/24 ---------- train Loss: 0.1082 Acc: 0.8074 val Loss: 0.0787 Acc: 0.8824 Epoch 4/24 ---------- train Loss: 0.1751 Acc: 0.7500 val Loss: 0.2313 Acc: 0.7647 Epoch 5/24 ---------- train Loss: 0.1367 Acc: 0.8074 val Loss: 0.1766 Acc: 0.7908 Epoch 6/24 ---------- train Loss: 0.1456 Acc: 0.8156 val Loss: 0.1116 Acc: 0.7908 Epoch 7/24 ---------- train Loss: 0.1259 Acc: 0.8033 val Loss: 0.0793 Acc: 0.8627 Epoch 8/24 ---------- train Loss: 0.0807 Acc: 0.8607 val Loss: 0.0781 Acc: 0.8758 Epoch 9/24 ---------- train Loss: 0.0618 Acc: 0.8730 val Loss: 0.0778 Acc: 0.8824 Epoch 10/24 ---------- train Loss: 0.0804 Acc: 0.8566 val Loss: 0.0876 Acc: 0.8758 Epoch 11/24 ---------- train Loss: 0.0751 Acc: 0.8607 val Loss: 0.0945 Acc: 0.8693 Epoch 12/24 ---------- train Loss: 0.0695 Acc: 0.8770 val Loss: 0.0950 Acc: 0.8824 Epoch 13/24 ---------- train Loss: 0.0596 Acc: 0.8852 val Loss: 0.0907 Acc: 0.8889 Epoch 14/24 ---------- train Loss: 0.0624 Acc: 0.9016 val Loss: 0.0785 Acc: 0.8824 Epoch 15/24 ---------- train Loss: 0.0546 Acc: 0.9139 val Loss: 0.0810 Acc: 0.8824 Epoch 16/24 ---------- train Loss: 0.0982 Acc: 0.8484 val Loss: 0.1054 Acc: 0.8824 Epoch 17/24 ---------- train Loss: 0.0659 Acc: 0.8893 val Loss: 0.0839 Acc: 0.8889 Epoch 18/24 ---------- train Loss: 0.0645 Acc: 0.8893 val Loss: 0.0760 Acc: 0.8824 Epoch 19/24 ---------- train Loss: 0.0723 Acc: 0.8934 val Loss: 0.0699 Acc: 0.8758 Epoch 20/24 ---------- train Loss: 0.0689 Acc: 0.8852 val Loss: 0.0733 Acc: 0.8627 Epoch 21/24 ---------- train Loss: 0.0656 Acc: 0.8893 val Loss: 0.0915 Acc: 0.8954 Epoch 22/24 ---------- train Loss: 0.0756 Acc: 0.8770 val Loss: 0.0772 Acc: 0.8889 Epoch 23/24 ---------- train Loss: 0.0695 Acc: 0.8934 val Loss: 0.0724 Acc: 0.8627 Epoch 24/24 ---------- train Loss: 0.0556 Acc: 0.9139 val Loss: 0.0821 Acc: 0.8889 Training complete in 1m 26s Best val Acc: 0.954248
由此可知,第一次epoch中的参数为最好参数,将其记录下来。
观察结果:
visualize_model(model_ft)
可以看到,95%的正确率还是很高的。
2、Fixed feature extractor演示
与之前的步骤类似,不同的是除了自己添加的全连接层需要更新外,其他的卷积层保持之前训练好的参数,不进行更新。
model_conv = torchvision.models.resnet18(pretrained=True) for param in model_conv.parameters(): param.requires_grad = False # 设置为false则梯度不会进行更新 # 新创建的parameters,默认param.requires_grad = True num_ftrs = model_conv.fc.in_features model_conv.fc = nn.Linear(num_ftrs, 2) if use_gpu: model_conv = model_conv.cuda() criterion = nn.CrossEntropyLoss() # 注意这里仅仅对fc进行参数更新(fc为整个网络中的最后一层) optimizer_conv = optim.SGD(model_conv.fc.parameters(), lr=0.001, momentum=0.9) # 学习率每7个epoch下降0.1 exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)
开始进行训练
model_conv = train_model(model_conv, criterion, optimizer_conv, exp_lr_scheduler, num_epochs=25)
Epoch 0/24 ---------- train Loss: 0.1913 Acc: 0.5738 val Loss: 0.1566 Acc: 0.6732 Epoch 1/24 ---------- train Loss: 0.1469 Acc: 0.7295 val Loss: 0.0659 Acc: 0.9085 Epoch 2/24 ---------- train Loss: 0.1189 Acc: 0.7623 val Loss: 0.0458 Acc: 0.9477 Epoch 3/24 ---------- train Loss: 0.1191 Acc: 0.8033 val Loss: 0.0463 Acc: 0.9281 Epoch 4/24 ---------- train Loss: 0.1470 Acc: 0.7582 val Loss: 0.1730 Acc: 0.7255 Epoch 5/24 ---------- train Loss: 0.1590 Acc: 0.7746 val Loss: 0.0451 Acc: 0.9346 Epoch 6/24 ---------- train Loss: 0.0950 Acc: 0.8361 val Loss: 0.0486 Acc: 0.9412 Epoch 7/24 ---------- train Loss: 0.0734 Acc: 0.8975 val Loss: 0.0502 Acc: 0.9412 Epoch 8/24 ---------- train Loss: 0.0821 Acc: 0.8689 val Loss: 0.0417 Acc: 0.9477 Epoch 9/24 ---------- train Loss: 0.1085 Acc: 0.7910 val Loss: 0.0513 Acc: 0.9346 Epoch 10/24 ---------- train Loss: 0.0908 Acc: 0.8443 val Loss: 0.0468 Acc: 0.9477 Epoch 11/24 ---------- train Loss: 0.0803 Acc: 0.8484 val Loss: 0.0416 Acc: 0.9477 Epoch 12/24 ---------- train Loss: 0.0907 Acc: 0.8525 val Loss: 0.0425 Acc: 0.9477 Epoch 13/24 ---------- train Loss: 0.0811 Acc: 0.8443 val Loss: 0.0433 Acc: 0.9542 Epoch 14/24 ---------- train Loss: 0.1185 Acc: 0.8115 val Loss: 0.0460 Acc: 0.9542 Epoch 15/24 ---------- train Loss: 0.0851 Acc: 0.8361 val Loss: 0.0434 Acc: 0.9542 Epoch 16/24 ---------- train Loss: 0.0975 Acc: 0.8361 val Loss: 0.0431 Acc: 0.9542 Epoch 17/24 ---------- train Loss: 0.0756 Acc: 0.8730 val Loss: 0.0518 Acc: 0.9346 Epoch 18/24 ---------- train Loss: 0.0938 Acc: 0.8361 val Loss: 0.0448 Acc: 0.9477 Epoch 19/24 ---------- train Loss: 0.0837 Acc: 0.8402 val Loss: 0.0462 Acc: 0.9412 Epoch 20/24 ---------- train Loss: 0.0849 Acc: 0.8443 val Loss: 0.0448 Acc: 0.9477 Epoch 21/24 ---------- train Loss: 0.0701 Acc: 0.8934 val Loss: 0.0470 Acc: 0.9477 Epoch 22/24 ---------- train Loss: 0.0822 Acc: 0.8525 val Loss: 0.0403 Acc: 0.9477 Epoch 23/24 ---------- train Loss: 0.0934 Acc: 0.8525 val Loss: 0.0433 Acc: 0.9412 Epoch 24/24 ---------- train Loss: 0.0872 Acc: 0.8361 val Loss: 0.0393 Acc: 0.9477 Training complete in 0m 51s Best val Acc: 0.954248
总结
Transfer Learning关心的问题是:什么是“知识”以及如何更好地运用之前得到的“知识”。这可以有很多方法和手段。fine-tune是其中的一种手段。在实际操作中有很多的方法可以使用,也可以对不同的特征层进行不同策略的参数调整。
迁移学习是一种思想,在众多方法的修饰下,可以很好的完成任务。
参考资料:
1、http://cs231n.github.io/transfer-learning/
2、http://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html#convnet-as-fixed-feature-extractor
3、https://www.zhihu.com/question/49534423