深度學習之遷移學習


遷移學習概述
背景
隨着越來越多的機器學習應用場景的出現,而現有表現比較好的監督學習需要大量的標注數據,標注數據是一項枯燥無味且花費巨大的任務,所以遷移學習受到越來越多的關注。
傳統機器學習(主要指監督學習)

  • 基於同分布假設
  • 需要大量標注數據

然而實際使用過程中不同數據集可能存在一些問題,比如

  • 數據分布差異
  • 標注數據過期

訓練數據過期,也就是好不容易標定的數據要被丟棄,有些應用中數據是分布隨着時間推移會有變化。如何充分利用之前標注好的數據(廢物利用),同時又保證在新的任務上的模型精度?基於這樣的問題,所以就有了對於遷移學習的研究。


概念

遷移學習是把一個領域(即源領域)的知識,遷移到另外一個領域(即目標領域),使得目標領域能夠取得更好的學習效果。通常,源領域數據量充足,而目標領域數據量較小,遷移學習需要將在數據量充足的情況下學習到的知識,遷移到數據量小的新環境中。

為什么需要遷移學習:

  1. 數據的標簽很難獲取,當有些任務的數據標簽很難獲取時,就可以通過其他容易獲取標簽且和該任務相似的任務來遷移學習。

  2. 從頭建立模型是復雜和耗時的,也即是需要通過遷移學習來加快學習效率。

如何進行遷移:

  • 基於實例的遷移學習
  • 基於特征的遷移學習
  • 基於共享參數的遷移學習
  • 基於模型的遷移學習
  • 基於關系的遷移學習

基於實例的遷移

基於實例的遷移學習研究的是,如何從源領域中挑選出,對目標領域的訓練有用的實例,比如對源領域的有標記數據實例進行有效的權重分配,讓源域實例分布接近目標域的實例分布,從而在目標領域中建立一個分類精度較高的、可靠地學習模型。
因為,遷移學習中源領域與目標領域的數據分布是不一致,所以源領域中所有有標記的數據實例不一定都對目標領域有用。該方法優點是簡單,實現容易,缺點在於權重的選擇與相似度的度量依賴經驗,且源域與目標域的數據分布往往不同。

基於特征的遷移學習

基於特征選擇的遷移學習算法,關注的是如何找出源領域與目標領域之間共同的特征表示,然后利用這些特征進行知識遷移。基於特征映射的遷移學習算法,關注的是如何將源領域和目標領域的數據從原始特征空間映射到新的特征空間中去。優點對大多數方法適用,效果較好。缺點在於難以求解,容易發生過適配。

 

需要注意的的是基於特征的遷移學習方法和基於實例的遷移學習方法的不同是基於特征的遷移學習需要進行特征變換來使得源域和目標域數據到到同一特征空間,而基於實例的遷移學習只是從實際數據中進行選擇來得到與目標域相似的部分數據,然后直接學習。

基於共享參數的遷移學習

基於共享參數的遷移研究的是如何找到源數據和目標數據的空間模型之間的共同參數或者先驗分布,從而可以通過進一步處理,達到知識遷移的目的,假設前提是,學習任務中的的每個相關模型會共享一些相同的參數或者先驗分布。

基於模型的遷移學習

源域和目標域共享模型參數,也就是將之前在源域中通過大量數據訓練好的模型應用到目標域上進行預測。基於模型的遷移學習方法比較直接,這樣的方法優點是可以充分利用模型之間存在的相似性。缺點在於模型參數不易收斂。

舉個例子:比如利用上千萬的圖象來訓練好一個圖象識別的系統,當我們遇到一個新的圖象領域問題的時候,就不用再去找幾千萬個圖象來訓練了,只需把原來訓練好的模型遷移到新的領域,在新的領域往往只需幾萬張圖片就夠,同樣可以得到很高的精度。

 基於關系的遷移學習

當兩個域是相似的時候,那么它們之間會共享某種相似關系,將源域中學習到的邏輯網絡關系應用到目標域上來進行遷移,比方說生物病毒傳播規律到計算機病毒傳播規律的遷移。這部分的研究工作比較少。典型方法就是mapping的方法。

螞蟻蜜蜂分類

 

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
import copy

plt.ion()   # interactive mode

data_transforms = {
    'train': transforms.Compose([
        #隨機在圖像上裁剪出224*224大小的圖像
        transforms.RandomResizedCrop(224),
        #將圖像隨機翻轉
        transforms.RandomHorizontalFlip(),
        #將圖像數據轉換為網絡訓練所需的tensor向量
        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 = '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

use_gpu = torch.cuda.is_available()

#顯示一些圖片,以便理解數據增強
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])

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':
                #學習率更新方式
                scheduler.step()
                model.train(True)  # Set model to training mode
            else:
                model.train(False)  # Set model to evaluate mode

            running_loss = 0.0
            running_corrects = 0

            # Iterate over data.
            for data in dataloaders[phase]:
                # get the inputs
                inputs, labels = data

                # wrap them in Variable
                if use_gpu:
                    inputs = Variable(inputs.cuda())
                    labels = Variable(labels.cuda())
                else:
                    inputs, labels = Variable(inputs), Variable(labels)

                # zero the parameter gradients
                optimizer.zero_grad()

                # forward
                outputs = model(inputs)
                _, preds = torch.max(outputs.data, 1)
                loss = criterion(outputs, labels)

                # backward + optimize only if in training phase
                if phase == 'train':
                    loss.backward()
                    optimizer.step()

                # 計算一個epoch的loss和准確率
                running_loss += loss.item() * inputs.size(0)
                running_corrects += torch.sum(preds == labels.data)

            #計算loss和准確率的均值
            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 = copy.deepcopy(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))

    # load best model weights
    model.load_state_dict(best_model_wts)
    return model

#可視化一些模型
def visualize_model(model, num_images=6):
    was_training = model.training
    model.eval()
    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:
                model.train(mode=was_training)
                return
    model.train(mode=was_training)

#微調convnet,加載預測模型並重寫全連接層
#導入pytorch中自帶的resnet18網絡模型
model_ft = models.resnet18(pretrained=True)
# 修改網絡模型的最后一個全連接層
# 獲取最后一個全連接層的輸入通道數
num_ftrs = model_ft.fc.in_features
# 修改最后一個全連接層的的輸出數為2
model_ft.fc = nn.Linear(num_ftrs, 2)

if use_gpu:
    model_ft = model_ft.cuda()

criterion = nn.CrossEntropyLoss()

# Observe that all parameters are being optimized
optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)

# 定義學習率的更新方式,每7個epoch修改一次學習率
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)

visualize_model(model_ft)

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)

if use_gpu:
    model_conv = model_conv.cuda()

criterion = nn.CrossEntropyLoss()

# Observe that only parameters of final layer are being optimized as
# opoosed 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)

visualize_model(model_conv)

 

參考博客:https://www.cnblogs.com/jiqibuxuexi/p/8403986.html

                 https://ptorch.com/news/138.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM