99精品伊人亚洲|最近国产中文炮友|九草在线视频支援|AV网站大全最新|美女黄片免费观看|国产精品资源视频|精彩无码视频一区|91大神在线后入|伊人终合在线播放|久草综合久久中文

0
  • 聊天消息
  • 系統(tǒng)消息
  • 評論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

PyTorch教程-14.2. 微調(diào)

jf_pJlTbmA9 ? 來源:PyTorch ? 作者:PyTorch ? 2023-06-05 15:44 ? 次閱讀
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

在前面的章節(jié)中,我們討論了如何在只有 60000 張圖像的 Fashion-MNIST 訓(xùn)練數(shù)據(jù)集上訓(xùn)練模型。我們還描述了 ImageNet,這是學(xué)術(shù)界使用最廣泛的大規(guī)模圖像數(shù)據(jù)集,它有超過 1000 萬張圖像和 1000 個對象。然而,我們通常遇到的數(shù)據(jù)集的大小介于這兩個數(shù)據(jù)集之間。

假設(shè)我們要從圖片中識別出不同類型的椅子,然后向用戶推薦購買鏈接。一種可能的方法是首先識別 100 把普通椅子,為每把椅子拍攝 1000 張不同角度的圖像,然后在收集的圖像數(shù)據(jù)集上訓(xùn)練分類模型。雖然這個椅子數(shù)據(jù)集可能比 Fashion-MNIST 數(shù)據(jù)集大,但示例數(shù)量仍然不到 ImageNet 中的十分之一。這可能會導(dǎo)致適用于 ImageNet 的復(fù)雜模型在此椅子數(shù)據(jù)集上過度擬合。此外,由于訓(xùn)練示例數(shù)量有限,訓(xùn)練模型的準(zhǔn)確性可能無法滿足實際要求。

為了解決上述問題,一個顯而易見的解決方案是收集更多的數(shù)據(jù)。然而,收集和標(biāo)記數(shù)據(jù)可能會花費大量時間和金錢。例如,為了收集 ImageNet 數(shù)據(jù)集,研究人員花費了數(shù)百萬美元的研究經(jīng)費。雖然目前的數(shù)據(jù)采集成本已經(jīng)大幅降低,但這一成本仍然不容忽視。

另一種解決方案是應(yīng)用遷移學(xué)習(xí),將從源數(shù)據(jù)集中學(xué)到的知識遷移到目標(biāo)數(shù)據(jù)集中。例如,盡管 ImageNet 數(shù)據(jù)集中的大部分圖像與椅子無關(guān),但在此數(shù)據(jù)集上訓(xùn)練的模型可能會提取出更一般的圖像特征,這有助于識別邊緣、紋理、形狀和物體組成。這些相似的特征也可能對識別椅子有效。

14.2.1。腳步

在本節(jié)中,我們將介紹遷移學(xué)習(xí)中的一種常用技術(shù):微調(diào)。如圖 14.2.1所示,微調(diào)包括以下四個步驟:

在源數(shù)據(jù)集(例如,ImageNet 數(shù)據(jù)集)上預(yù)訓(xùn)練神經(jīng)網(wǎng)絡(luò)模型,即源模型。

創(chuàng)建一個新的神經(jīng)網(wǎng)絡(luò)模型,即目標(biāo)模型。這將復(fù)制源模型上除輸出層之外的所有模型設(shè)計及其參數(shù)。我們假設(shè)這些模型參數(shù)包含從源數(shù)據(jù)集中學(xué)到的知識,并且這些知識也適用于目標(biāo)數(shù)據(jù)集。我們還假設(shè)源模型的輸出層與源數(shù)據(jù)集的標(biāo)簽密切相關(guān);因此它不在目標(biāo)模型中使用。

向目標(biāo)模型添加一個輸出層,其輸出數(shù)量為目標(biāo)數(shù)據(jù)集中的類別數(shù)量。然后隨機初始化該層的模型參數(shù)。

在目標(biāo)數(shù)據(jù)集(例如椅子數(shù)據(jù)集)上訓(xùn)練目標(biāo)模型。輸出層將從頭開始訓(xùn)練,而所有其他層的參數(shù)將根據(jù)源模型的參數(shù)進(jìn)行微調(diào)。

pYYBAGR9O0iAB3lVAAL7dtPCjdU591.svg

圖 14.2.1微調(diào)。

當(dāng)目標(biāo)數(shù)據(jù)集遠(yuǎn)小于源數(shù)據(jù)集時,微調(diào)有助于提高模型的泛化能力。

14.2.2。熱狗識別

讓我們通過一個具體案例來演示微調(diào):熱狗識別。我們將在一個小型數(shù)據(jù)集上微調(diào) ResNet 模型,該數(shù)據(jù)集是在 ImageNet 數(shù)據(jù)集上預(yù)訓(xùn)練的。這個小數(shù)據(jù)集包含數(shù)千張有熱狗和沒有熱狗的圖像。我們將使用微調(diào)模型從圖像中識別熱狗。

%matplotlib inline
import os
import torch
import torchvision
from torch import nn
from d2l import torch as d2l

%matplotlib inline
import os
from mxnet import gluon, init, np, npx
from mxnet.gluon import nn
from d2l import mxnet as d2l

npx.set_np()

14.2.2.1。讀取數(shù)據(jù)集

我們使用的熱狗數(shù)據(jù)集取自在線圖像。該數(shù)據(jù)集包含 1400 張包含熱狗的正類圖像,以及包含其他食物的大量負(fù)類圖像。兩個類別的 1000 張圖像用于訓(xùn)練,其余用于測試。

解壓下載的數(shù)據(jù)集后,我們得到兩個文件夾 hotdog/train和hotdog/test. 這兩個文件夾都有hotdog和 not-hotdog子文件夾,其中任何一個都包含相應(yīng)類別的圖像。

#@save
d2l.DATA_HUB['hotdog'] = (d2l.DATA_URL + 'hotdog.zip',
             'fba480ffa8aa7e0febbb511d181409f899b9baa5')

data_dir = d2l.download_extract('hotdog')

#@save
d2l.DATA_HUB['hotdog'] = (d2l.DATA_URL + 'hotdog.zip',
             'fba480ffa8aa7e0febbb511d181409f899b9baa5')

data_dir = d2l.download_extract('hotdog')

Downloading ../data/hotdog.zip from http://d2l-data.s3-accelerate.amazonaws.com/hotdog.zip...

我們創(chuàng)建兩個實例來分別讀取訓(xùn)練和測試數(shù)據(jù)集中的所有圖像文件。

train_imgs = torchvision.datasets.ImageFolder(os.path.join(data_dir, 'train'))
test_imgs = torchvision.datasets.ImageFolder(os.path.join(data_dir, 'test'))

train_imgs = gluon.data.vision.ImageFolderDataset(
  os.path.join(data_dir, 'train'))
test_imgs = gluon.data.vision.ImageFolderDataset(
  os.path.join(data_dir, 'test'))

前 8 個正面示例和最后 8 個負(fù)面圖像如下所示。如您所見,圖像的大小和縱橫比各不相同。

hotdogs = [train_imgs[i][0] for i in range(8)]
not_hotdogs = [train_imgs[-i - 1][0] for i in range(8)]
d2l.show_images(hotdogs + not_hotdogs, 2, 8, scale=1.4);

pYYBAGR4YniAE6iUAAOFYlOAqlA349.png

hotdogs = [train_imgs[i][0] for i in range(8)]
not_hotdogs = [train_imgs[-i - 1][0] for i in range(8)]
d2l.show_images(hotdogs + not_hotdogs, 2, 8, scale=1.4);

pYYBAGR4YniAE6iUAAOFYlOAqlA349.png

在訓(xùn)練過程中,我們首先從圖像中裁剪出一個隨機大小和隨機縱橫比的隨機區(qū)域,然后將這個區(qū)域縮放到 224×224輸入圖像。在測試過程中,我們將圖像的高度和寬度都縮放到 256 像素,然后裁剪一個中心 224×224區(qū)域作為輸入。此外,對于三個 RGB(紅色、綠色和藍(lán)色)顏色通道,我們逐通道標(biāo)準(zhǔn)化它們的值。具體來說,就是用該通道的每個值減去該通道的平均值,然后除以該通道的標(biāo)準(zhǔn)差。

# Specify the means and standard deviations of the three RGB channels to
# standardize each channel
normalize = torchvision.transforms.Normalize(
  [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])

train_augs = torchvision.transforms.Compose([
  torchvision.transforms.RandomResizedCrop(224),
  torchvision.transforms.RandomHorizontalFlip(),
  torchvision.transforms.ToTensor(),
  normalize])

test_augs = torchvision.transforms.Compose([
  torchvision.transforms.Resize([256, 256]),
  torchvision.transforms.CenterCrop(224),
  torchvision.transforms.ToTensor(),
  normalize])

# Specify the means and standard deviations of the three RGB channels to
# standardize each channel
normalize = gluon.data.vision.transforms.Normalize(
  [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])

train_augs = gluon.data.vision.transforms.Compose([
  gluon.data.vision.transforms.RandomResizedCrop(224),
  gluon.data.vision.transforms.RandomFlipLeftRight(),
  gluon.data.vision.transforms.ToTensor(),
  normalize])

test_augs = gluon.data.vision.transforms.Compose([
  gluon.data.vision.transforms.Resize(256),
  gluon.data.vision.transforms.CenterCrop(224),
  gluon.data.vision.transforms.ToTensor(),
  normalize])

14.2.2.2。定義和初始化模型

我們使用在 ImageNet 數(shù)據(jù)集上預(yù)訓(xùn)練的 ResNet-18 作為源模型。在這里,我們指定pretrained=True自動下載預(yù)訓(xùn)練模型參數(shù)。如果是第一次使用這個模型,需要連接互聯(lián)網(wǎng)才能下載。

pretrained_net = torchvision.models.resnet18(pretrained=True)

預(yù)訓(xùn)練源模型實例包含多個特征層和一個輸出層fc。這種劃分的主要目的是為了便于微調(diào)除輸出層之外的所有層的模型參數(shù)。fc下面給出源模型的成員變量。

pretrained_net.fc

Linear(in_features=512, out_features=1000, bias=True)

pretrained_net = gluon.model_zoo.vision.resnet18_v2(pretrained=True)

The pretrained source model instance contains two member variables: features and output. The former contains all layers of the model except the output layer, and the latter is the output layer of the model. The main purpose of this division is to facilitate the fine-tuning of model parameters of all layers but the output layer. The member variable output of source model is shown below.

pretrained_net.output

Dense(512 -> 1000, linear)

作為全連接層,它將 ResNet 最終的全局平均池化輸出轉(zhuǎn)化為 ImageNet 數(shù)據(jù)集的 1000 類輸出。然后我們構(gòu)建一個新的神經(jīng)網(wǎng)絡(luò)作為目標(biāo)模型。它的定義方式與預(yù)訓(xùn)練源模型相同,不同之處在于它在最后一層的輸出數(shù)量設(shè)置為目標(biāo)數(shù)據(jù)集中的類數(shù)(而不是 1000)。

在下面的代碼中,目標(biāo)模型實例的輸出層之前的模型參數(shù)finetune_net被初始化為源模型中相應(yīng)層的模型參數(shù)。由于這些模型參數(shù)是通過在 ImageNet 上進(jìn)行預(yù)訓(xùn)練獲得的,因此它們是有效的。因此,我們只能使用較小的學(xué)習(xí)率來 微調(diào)此類預(yù)訓(xùn)練參數(shù)。相比之下,輸出層中的模型參數(shù)是隨機初始化的,通常需要更大的學(xué)習(xí)率才能從頭開始學(xué)習(xí)。讓基礎(chǔ)學(xué)習(xí)率成為η, 學(xué)習(xí)率10η將用于迭代輸出層中的模型參數(shù)。

finetune_net = torchvision.models.resnet18(pretrained=True)
finetune_net.fc = nn.Linear(finetune_net.fc.in_features, 2)
nn.init.xavier_uniform_(finetune_net.fc.weight);

finetune_net = gluon.model_zoo.vision.resnet18_v2(classes=2)
finetune_net.features = pretrained_net.features
finetune_net.output.initialize(init.Xavier())
# The model parameters in the output layer will be iterated using a learning
# rate ten times greater
finetune_net.output.collect_params().setattr('lr_mult', 10)

14.2.2.3。微調(diào)模型

首先,我們定義了一個train_fine_tuning使用微調(diào)的訓(xùn)練函數(shù),因此它可以被多次調(diào)用。

# If `param_group=True`, the model parameters in the output layer will be
# updated using a learning rate ten times greater
def train_fine_tuning(net, learning_rate, batch_size=128, num_epochs=5,
           param_group=True):
  train_iter = torch.utils.data.DataLoader(torchvision.datasets.ImageFolder(
    os.path.join(data_dir, 'train'), transform=train_augs),
    batch_size=batch_size, shuffle=True)
  test_iter = torch.utils.data.DataLoader(torchvision.datasets.ImageFolder(
    os.path.join(data_dir, 'test'), transform=test_augs),
    batch_size=batch_size)
  devices = d2l.try_all_gpus()
  loss = nn.CrossEntropyLoss(reduction="none")
  if param_group:
    params_1x = [param for name, param in net.named_parameters()
       if name not in ["fc.weight", "fc.bias"]]
    trainer = torch.optim.SGD([{'params': params_1x},
                  {'params': net.fc.parameters(),
                  'lr': learning_rate * 10}],
                lr=learning_rate, weight_decay=0.001)
  else:
    trainer = torch.optim.SGD(net.parameters(), lr=learning_rate,
                 weight_decay=0.001)
  d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs,
          devices)

def train_fine_tuning(net, learning_rate, batch_size=128, num_epochs=5):
  train_iter = gluon.data.DataLoader(
    train_imgs.transform_first(train_augs), batch_size, shuffle=True)
  test_iter = gluon.data.DataLoader(
    test_imgs.transform_first(test_augs), batch_size)
  devices = d2l.try_all_gpus()
  net.collect_params().reset_ctx(devices)
  net.hybridize()
  loss = gluon.loss.SoftmaxCrossEntropyLoss()
  trainer = gluon.Trainer(net.collect_params(), 'sgd', {
    'learning_rate': learning_rate, 'wd': 0.001})
  d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs,
          devices)

我們將基礎(chǔ)學(xué)習(xí)率設(shè)置為一個較小的值,以便微調(diào) 通過預(yù)訓(xùn)練獲得的模型參數(shù)。基于前面的設(shè)置,我們將使用十倍大的學(xué)習(xí)率從頭開始訓(xùn)練目標(biāo)模型的輸出層參數(shù)。

train_fine_tuning(finetune_net, 5e-5)

loss 0.201, train acc 0.930, test acc 0.948
888.0 examples/sec on [device(type='cuda', index=0), device(type='cuda', index=1)]

poYBAGR9O1GACPLaAAEAcN7DI9k186.svg

train_fine_tuning(finetune_net, 0.01)

loss 0.190, train acc 0.931, test acc 0.946
19.3 examples/sec on [gpu(0), gpu(1)]

pYYBAGR9O1OARuFHAAEBjUEc-aY687.svg

為了進(jìn)行比較,我們定義了一個相同的模型,但將其所有模型參數(shù)初始化為隨機值。由于整個模型需要從頭開始訓(xùn)練,我們可以使用更大的學(xué)習(xí)率。

scratch_net = torchvision.models.resnet18()
scratch_net.fc = nn.Linear(scratch_net.fc.in_features, 2)
train_fine_tuning(scratch_net, 5e-4, param_group=False)

loss 0.382, train acc 0.832, test acc 0.833
1571.7 examples/sec on [device(type='cuda', index=0), device(type='cuda', index=1)]

poYBAGR9O1aAbZ7FAAEBd7ggZdQ368.svg

scratch_net = gluon.model_zoo.vision.resnet18_v2(classes=2)
scratch_net.initialize(init=init.Xavier())
train_fine_tuning(scratch_net, 0.1)

loss 0.383, train acc 0.833, test acc 0.836
21.0 examples/sec on [gpu(0), gpu(1)]

pYYBAGR9O1iATZ0LAAEBxvitBe0577.svg

正如我們所看到的,微調(diào)模型在同一時期往往表現(xiàn)更好,因為它的初始參數(shù)值更有效。

14.2.3。概括

遷移學(xué)習(xí)將從源數(shù)據(jù)集學(xué)到的知識遷移到目標(biāo)數(shù)據(jù)集。微調(diào)是遷移學(xué)習(xí)的常用技術(shù)。

目標(biāo)模型從源模型中復(fù)制所有模型設(shè)計及其參數(shù)(輸出層除外),并根據(jù)目標(biāo)數(shù)據(jù)集微調(diào)這些參數(shù)。相比之下,目標(biāo)模型的輸出層需要從頭開始訓(xùn)練。

一般微調(diào)參數(shù)使用較小的學(xué)習(xí)率,而從頭訓(xùn)練輸出層可以使用較大的學(xué)習(xí)率。

14.2.4。練習(xí)

不斷提高 的學(xué)習(xí)率finetune_net。模型的準(zhǔn)確性如何變化?

在對比實驗中進(jìn)一步調(diào)整 和 的超參數(shù)finetune_net。 scratch_net它們的準(zhǔn)確性仍然不同嗎?

將輸出層之前的參數(shù)設(shè)置finetune_net為源模型的參數(shù),并且在訓(xùn)練期間不更新它們。模型的準(zhǔn)確性如何變化?您可以使用以下代碼。

事實上,ImageNet數(shù)據(jù)集中有一個“熱狗”類。其在輸出層對應(yīng)的權(quán)重參數(shù)可以通過以下代碼獲取。我們?nèi)绾卫眠@個權(quán)重參數(shù)?

聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • 數(shù)據(jù)集
    +關(guān)注

    關(guān)注

    4

    文章

    1224

    瀏覽量

    25439
  • pytorch
    +關(guān)注

    關(guān)注

    2

    文章

    809

    瀏覽量

    13945
收藏 人收藏
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

    評論

    相關(guān)推薦
    熱點推薦

    Xilinx ISE Design Suite 14.2 安裝圖解

    電子發(fā)燒友網(wǎng)核心提示 :Xilinx ISE 14.2安裝指南,包括Xilinx ISE 14.2軟件下載、Xilinx ISE 14.2軟件安裝、Xilinx ISE 14.2相關(guān)產(chǎn)
    發(fā)表于 10-31 11:59 ?6.4w次閱讀
    Xilinx ISE Design Suite <b class='flag-5'>14.2</b> 安裝圖解

    PyTorch教程-16.7。自然語言推理:微調(diào) BERT

    16.7。自然語言推理:微調(diào) BERT? Colab [火炬]在 Colab 中打開筆記本 Colab [mxnet] Open the notebook in Colab Colab
    的頭像 發(fā)表于 06-05 15:44 ?1496次閱讀
    <b class='flag-5'>PyTorch</b>教程-16.7。自然語言推理:<b class='flag-5'>微調(diào)</b> BERT

    ISE14.2license

    求助ISE14.2license
    發(fā)表于 07-10 22:13

    E2094P IO Libraries Suite 14.2數(shù)據(jù)表

    Detailed technical description of the features and capabilities of IO Libraries Suite 14.2.
    發(fā)表于 10-09 10:05

    PyTorch如何入門

    PyTorch 入門實戰(zhàn)(一)——Tensor
    發(fā)表于 06-01 09:58

    Pytorch AI語音助手

    想做一個Pytorch AI語音助手,有沒有好的思路呀?
    發(fā)表于 03-06 13:00

    如何安裝TensorFlow2 Pytorch

    如何安裝TensorFlow2 Pytorch?
    發(fā)表于 03-07 07:32

    如何往星光2板子里裝pytorch?

    如題,想先gpu版本的pytorch只安裝cpu版本的pytorch,pytorch官網(wǎng)提供了基于conda和pip兩種安裝方式。因為咱是risc架構(gòu)沒對應(yīng)的conda,而使用pip安裝提示也沒有
    發(fā)表于 09-12 06:30

    如何讓14.2版的Differential pair Con

    如何讓14.2版的Differential pair Constraint對應(yīng)到15版的 ECset ?  1. 前言 15版Differential pair Constraint有很大的改變,當(dāng)你用15版來開啟一個原本在14.2版的設(shè)計檔,有些
    發(fā)表于 09-06 11:01 ?0次下載

    iOS 14.2被破解!Checkra1n越獄更新!

    iOS 14.2正式版才發(fā)布沒多久,有大神已經(jīng)對它進(jìn)行了越獄。 Checkra1n越獄已經(jīng)更新,支持iOS 14.2. 該版本包括A10/A10X設(shè)備的官方支持和A11設(shè)備的有限支持(iPhone
    的頭像 發(fā)表于 11-10 09:27 ?2772次閱讀

    基于PyTorch的深度學(xué)習(xí)入門教程之PyTorch簡單知識

    本文參考PyTorch官網(wǎng)的教程,分為五個基本模塊來介紹PyTorch。為了避免文章過長,這五個模塊分別在五篇博文中介紹。 Part1:PyTorch簡單知識 Part2:PyTorch
    的頭像 發(fā)表于 02-16 15:20 ?2503次閱讀

    PyTorch教程14.2微調(diào)

    電子發(fā)燒友網(wǎng)站提供《PyTorch教程14.2微調(diào).pdf》資料免費下載
    發(fā)表于 06-05 14:42 ?0次下載
    <b class='flag-5'>PyTorch</b>教程<b class='flag-5'>14.2</b>之<b class='flag-5'>微調(diào)</b>

    PyTorch教程16.6之針對序列級和令牌級應(yīng)用程序微調(diào)BERT

    電子發(fā)燒友網(wǎng)站提供《PyTorch教程16.6之針對序列級和令牌級應(yīng)用程序微調(diào)BERT.pdf》資料免費下載
    發(fā)表于 06-05 10:51 ?0次下載
    <b class='flag-5'>PyTorch</b>教程16.6之針對序列級和令牌級應(yīng)用程序<b class='flag-5'>微調(diào)</b>BERT

    PyTorch教程16.7之自然語言推理:微調(diào)BERT

    電子發(fā)燒友網(wǎng)站提供《PyTorch教程16.7之自然語言推理:微調(diào)BERT.pdf》資料免費下載
    發(fā)表于 06-05 10:52 ?0次下載
    <b class='flag-5'>PyTorch</b>教程16.7之自然語言推理:<b class='flag-5'>微調(diào)</b>BERT

    pytorch用來干嘛的

    實現(xiàn),并允許從Python等高級語言編寫神經(jīng)網(wǎng)絡(luò)的設(shè)計和訓(xùn)練。 PyTorch包含了許多用于Computer Vision和NLP等領(lǐng)域的預(yù)訓(xùn)練模型,可以對它們進(jìn)行微調(diào),以便更好地適應(yīng)特定的任務(wù)。 在機器學(xué)習(xí)和深度學(xué)習(xí)領(lǐng)域中,PyTor
    的頭像 發(fā)表于 08-21 16:41 ?1w次閱讀