国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

pytorch完整模型訓練套路

這篇具有很好參考價值的文章主要介紹了pytorch完整模型訓練套路。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。


本文以 CIFAR10數(shù)據(jù)集為例,介紹一個完整的模型訓練套路。

CIFAR10數(shù)據(jù)集簡介

CIFAR-10數(shù)據(jù)集包含60000張32x32彩色圖像,分為10個類,每類6000張。有50000張訓練圖片和10000張測試圖片。

數(shù)據(jù)集分為五個訓練batches和一個測試batch,每個batch有10000張圖像。測試batch包含從每個類中隨機選擇的1000個圖像。訓練batches以隨機順序包含剩余的圖像,但有些訓練batches可能包含一個類的圖像多于另一個類的圖像。在它們之間,訓練batches包含來自每個類的5000張圖像。

下面是數(shù)據(jù)集中的類,以及每個類的10張隨機圖片:
pytorch完整模型訓練套路

一共包含10 個類別的RGB 彩色圖片:飛機( airplane )、汽車( automobile )、鳥類( bird )、貓( cat )、鹿( deer )、狗( dog )、蛙類( frog )、馬( horse )、船( ship )和卡車( truck )。

訓練模型套路

1、準備數(shù)據(jù)集

# 準備數(shù)據(jù)集
train_data = torchvision.datasets.CIFAR10(root="./source", train=True, transform=torchvision.transforms.ToTensor(), download=True)

test_data = torchvision.datasets.CIFAR10(root="./source", train=False, transform=torchvision.transforms.ToTensor(), download=True)
# length 長度
train_data_size = len(train_data)
test_data_size = len(test_data)
print(f"訓練數(shù)據(jù)集的長度為:{train_data_size}")
print(f"測試數(shù)據(jù)集的長度為:{test_data_size}")

pytorch完整模型訓練套路

2、加載數(shù)據(jù)集

# 利用 DataLoader 來加載數(shù)據(jù)集
train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)

3、搭建神經(jīng)網(wǎng)絡(luò)

我們準備搭建一個這樣的網(wǎng)絡(luò)模型結(jié)構(gòu):

pytorch完整模型訓練套路

# 搭建神經(jīng)網(wǎng)絡(luò)
class Aniu(nn.Module):
    def __init__(self):
        super(Aniu, self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(3, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 64, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Linear(64 * 4 * 4, 64),
            nn.Linear(64, 10)
        )

    def forward(self, x):
        x = self.model(x)
        return x
if __name__ == '__main__':
    aniu = Aniu()
    input = torch.ones((64, 3, 32, 32))
    output = aniu(input)
    print(output.shape)

我們在一個新的文件下搭建并簡單測試神經(jīng)網(wǎng)絡(luò)。

4、創(chuàng)建網(wǎng)絡(luò)模型、定義損失函數(shù)、優(yōu)化器

# 創(chuàng)建網(wǎng)絡(luò)模型
aniu = Aniu()
# 損失函數(shù)
loss_fn = nn.CrossEntropyLoss()
# 優(yōu)化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(aniu.parameters(), lr=learning_rate)

5、訓練網(wǎng)絡(luò)

# 設(shè)置訓練網(wǎng)絡(luò)的一些參數(shù)
# 記錄訓練的次數(shù)
total_train_step = 0
# 記錄測試的次數(shù)
total_test_step = 0
# 訓練的輪數(shù)
epoch = 10

for i in range(epoch):
    print(f"----------第{i+1}輪訓練開始-----------")

    # 訓練開始
    for data in train_dataloader:
        imgs, targets = data
        output = aniu(imgs)
        loss = loss_fn(output, targets)

        # 優(yōu)化器優(yōu)化模型
        optimizer.zero_grad() # 優(yōu)化器梯度清零
        loss.backward()
        optimizer.step()

        total_train_step = total_train_step + 1
        print(f"訓練次數(shù):{total_train_step},loss:{loss.item()}") # .item()可以將tensor數(shù)據(jù)類型轉(zhuǎn)化

6、測試數(shù)據(jù)集

我們可以通過with torch.mo_grad():來測試

for i in range(epoch):
    print(f"----------第{i+1}輪訓練開始-----------")

    # 訓練開始
    for data in train_dataloader:
        imgs, targets = data
        output = aniu(imgs)
        loss = loss_fn(output, targets)

        # 優(yōu)化器優(yōu)化模型
        optimizer.zero_grad() # 優(yōu)化器梯度清零
        loss.backward()
        optimizer.step()

        total_train_step = total_train_step + 1
        if total_train_step % 100 == 0:
            print(f"訓練次數(shù):{total_train_step},loss:{loss.item()}") # .item()可以將tensor數(shù)據(jù)類型轉(zhuǎn)化

    # 測試步驟開始
    total_test_loss = 0
    with torch.no_grad():
        for data in test_dataloader:
            imgs, targets = data
            output = aniu(imgs)
            loss = loss_fn(output, targets)
            total_test_loss = total_test_loss + loss.item()
    print(f"整體測試集上的Loss:{total_test_loss}")

pytorch完整模型訓練套路

7、添加tensorboard

我們在以上的代碼基礎(chǔ)上添加tensorboard,并通過tensorboard畫圖進行觀察:

# 添加tensorboard
writer = SummaryWriter("./log_train")

for i in range(epoch):
    print(f"----------第{i+1}輪訓練開始-----------")

    # 訓練開始
    for data in train_dataloader:
        imgs, targets = data
        output = aniu(imgs)
        loss = loss_fn(output, targets)

        # 優(yōu)化器優(yōu)化模型
        optimizer.zero_grad() # 優(yōu)化器梯度清零
        loss.backward()
        optimizer.step()

        total_train_step = total_train_step + 1
        if total_train_step % 100 == 0:
            print(f"訓練次數(shù):{total_train_step},loss:{loss.item()}") # .item()可以將tensor數(shù)據(jù)類型轉(zhuǎn)化
            writer.add_scalar("train_loss", loss.item(), total_train_step)

    # 測試步驟開始
    total_test_loss = 0
    with torch.no_grad():
        for data in test_dataloader:
            imgs, targets = data
            output = aniu(imgs)
            loss = loss_fn(output, targets)
            total_test_loss = total_test_loss + loss.item()
    print(f"整體測試集上的Loss:{total_test_loss}")
    writer.add_scalar("test_loss", total_test_loss, total_test_step)
    total_test_step = total_test_step + 1

writer.close()

運行并在終端輸入:

tensorboard --logdir="log_train"

可以觀察到圖像:

pytorch完整模型訓練套路

8、轉(zhuǎn)化為正確率

添加一段代碼,算出測試集上的正確率:

# 整體正確的個數(shù)
total_accuracy = 0

with torch.no_grad():
    for data in test_dataloader:
        imgs, targets = data
        output = aniu(imgs)
        loss = loss_fn(output, targets)
        total_test_loss = total_test_loss + loss.item()
        accuracy = (output.argmax(1) == targets).sum()
        total_accuracy = total_accuracy + accuracy
print(f"整體測試集上的Loss:{total_test_loss}")
print(f"整體測試集上的正確率:{total_accuracy/test_data_size}")
writer.add_scalar("test_loss", total_test_loss, total_test_step)
writer.add_scalar("test_accuracy", total_accuracy/test_data_size, total_test_step)
total_test_step = total_test_step + 1

9、保存模型

每輪保存一下模型:

torch.save(aniu, f"aniu_{i}.pth")
print("模型已保存")

完整代碼

train.py文件:

import torch.cuda
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

from model import *
# 準備數(shù)據(jù)集
train_data = torchvision.datasets.CIFAR10(root="./source", train=True,
                                          transform=torchvision.transforms.ToTensor(), download=True)

test_data = torchvision.datasets.CIFAR10(root="./source", train=False,
                                          transform=torchvision.transforms.ToTensor(), download=True)

# length 長度
train_data_size = len(train_data)
test_data_size = len(test_data)
print(f"訓練數(shù)據(jù)集的長度為:{train_data_size}")
print(f"測試數(shù)據(jù)集的長度為:{test_data_size}")

# 利用 DataLoader 來加載數(shù)據(jù)集
train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)

# 創(chuàng)建網(wǎng)絡(luò)模型 搭建神經(jīng)網(wǎng)絡(luò)
class Aniu(nn.Module):
    def __init__(self):
        super(Aniu, self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(3, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 64, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Linear(64 * 4 * 4, 64),
            nn.Linear(64, 10)
        )

    def forward(self, x):
        x = self.model(x)
        return x

aniu = Aniu()
# if torch.cuda.is_available():
#     aniu = aniu.cuda()


# 損失函數(shù)
loss_fn = nn.CrossEntropyLoss()
# if torch.cuda.is_available():
#     loss_fn = loss_fn.cuda()
# 優(yōu)化器
learning_rate = 1e-2
optimizer = torch.optim.SGD(aniu.parameters(), lr=learning_rate)

# 設(shè)置訓練網(wǎng)絡(luò)的一些參數(shù)
# 記錄訓練的次數(shù)
total_train_step = 0
# 記錄測試的次數(shù)
total_test_step = 0
# 訓練的輪數(shù)
epoch = 10


# 添加tensorboard
writer = SummaryWriter("./log_train")

for i in range(epoch):
    print(f"----------第{i+1}輪訓練開始-----------")

    # 訓練開始
    aniu.train()
    for data in train_dataloader:
        imgs, targets = data
        # if torch.cuda.is_available():
        #     imgs = imgs.cuda()
        #     targets = targets.cuda()
        output = aniu(imgs)
        loss = loss_fn(output, targets)

        # 優(yōu)化器優(yōu)化模型
        optimizer.zero_grad() # 優(yōu)化器梯度清零
        loss.backward()
        optimizer.step()

        total_train_step = total_train_step + 1
        if total_train_step % 100 == 0:
            print(f"訓練次數(shù):{total_train_step},loss:{loss.item()}") # .item()可以將tensor數(shù)據(jù)類型轉(zhuǎn)化
            writer.add_scalar("train_loss", loss.item(), total_train_step)


    # 測試步驟開始
    aniu.eval()
    total_test_loss = 0
    # 整體正確的個數(shù)
    total_accuracy = 0

    with torch.no_grad():
        for data in test_dataloader:
            imgs, targets = data
            # if torch.cuda.is_available():
            #     imgs = imgs.cuda()
            #     targets = targets.cuda()
            output = aniu(imgs)
            loss = loss_fn(output, targets)
            total_test_loss = total_test_loss + loss.item()
            accuracy = (output.argmax(1) == targets).sum()
            total_accuracy = total_accuracy + accuracy
    print(f"整體測試集上的Loss:{total_test_loss}")
    print(f"整體測試集上的正確率:{total_accuracy/test_data_size}")
    writer.add_scalar("test_loss", total_test_loss, total_test_step)
    writer.add_scalar("test_accuracy", total_accuracy/test_data_size, total_test_step)
    total_test_step = total_test_step + 1

    # torch.save(aniu.state_dict(), f"aniu_{}.pth") 官方推薦保存方式
    torch.save(aniu, f"aniu_{i}.pth")
    print("模型已保存")

writer.close()

model.py:文章來源地址http://www.zghlxwxcb.cn/news/detail-468637.html

import torch
from torch import nn
# 搭建神經(jīng)網(wǎng)絡(luò)
class Aniu(nn.Module):
    def __init__(self):
        super(Aniu, self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(3, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 32, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 64, 5, 1, 2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Linear(64 * 4 * 4, 64),
            nn.Linear(64, 10)
        )

    def forward(self, x):
        x = self.model(x)
        return x

if __name__ == '__main__':
    aniu = Aniu()
    input = torch.ones((64, 3, 32, 32))
    output = aniu(input)
    print(output.shape)

到了這里,關(guān)于pytorch完整模型訓練套路的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 【深度學習】pytorch——實現(xiàn)CIFAR-10數(shù)據(jù)集的分類

    【深度學習】pytorch——實現(xiàn)CIFAR-10數(shù)據(jù)集的分類

    筆記為自我總結(jié)整理的學習筆記,若有錯誤歡迎指出喲~ 往期文章: 【深度學習】pytorch——快速入門 CIFAR-10是一個常用的圖像分類數(shù)據(jù)集,每張圖片都是 3×32×32,3通道彩色圖片,分辨率為 32×32。 它包含了10個不同類別,每個類別有6000張圖像,其中5000張用于訓練,1000張用于

    2024年02月06日
    瀏覽(53)
  • CNN實現(xiàn)與訓練--------------以cifar10數(shù)據(jù)集為例進行演示(基于Tensorflow)

    本文以cifar10數(shù)據(jù)集為例進行演示 (cifar10數(shù)據(jù)集有5萬張32 32像素點的彩色圖片,用于訓練有1萬張32 32像素點的彩色圖片,用于測試)

    2024年02月08日
    瀏覽(22)
  • 【PyTorch】使用PyTorch創(chuàng)建卷積神經(jīng)網(wǎng)絡(luò)并在CIFAR-10數(shù)據(jù)集上進行分類

    【PyTorch】使用PyTorch創(chuàng)建卷積神經(jīng)網(wǎng)絡(luò)并在CIFAR-10數(shù)據(jù)集上進行分類

    在深度學習的世界中,圖像分類任務(wù)是一個經(jīng)典的問題,它涉及到識別給定圖像中的對象類別。CIFAR-10數(shù)據(jù)集是一個常用的基準數(shù)據(jù)集,包含了10個類別的60000張32x32彩色圖像。在本博客中,我們將探討如何使用PyTorch框架創(chuàng)建一個簡單的卷積神經(jīng)網(wǎng)絡(luò)(CNN)來對CIFAR-10數(shù)據(jù)集中

    2024年01月24日
    瀏覽(32)
  • 【Python機器學習】實驗15 將Lenet5應(yīng)用于Cifar10數(shù)據(jù)集(PyTorch實現(xiàn))

    【Python機器學習】實驗15 將Lenet5應(yīng)用于Cifar10數(shù)據(jù)集(PyTorch實現(xiàn))

    CIFAR-10 數(shù)據(jù)集由10個類別的60000張32x32彩色圖像組成,每類6000張圖像。有50000張訓練圖像和10000張測試圖像。數(shù)據(jù)集分為五個訓練批次 和一個測試批次,每個批次有10000張圖像。測試批次包含從每個類別中隨機選擇的1000張圖像。訓練批次包含隨機順序的剩余圖像,但一些訓練批

    2024年02月11日
    瀏覽(25)
  • 3.pytorch cifar10

    CIFAR10 是由 Hinton 的學生 Alex Krizhevsky、Ilya Sutskever 收集的一個用于普適物體識別的計算機視覺數(shù)據(jù)集,它包含 60000 張 32 X 32 的 RGB 彩色圖片,總共 10 個分類。 這些類別分別是飛機、汽車、鳥類、貓、鹿、狗、青蛙、馬、船和卡車。其中,包括 50000 張用于訓練集,10000 張用于

    2024年02月04日
    瀏覽(27)
  • 基于 PyTorch 的 cifar-10 圖像分類

    基于 PyTorch 的 cifar-10 圖像分類

    本文的主要內(nèi)容是基于 PyTorch 的 cifar-10 圖像分類,文中包括 cifar-10 數(shù)據(jù)集介紹、環(huán)境配置、實驗代碼、運行結(jié)果以及遇到的問題這幾個部分,本實驗采用了基本網(wǎng)絡(luò)和VGG加深網(wǎng)絡(luò)模型,其中VGG加深網(wǎng)絡(luò)模型的識別準確率是要優(yōu)于基本網(wǎng)絡(luò)模型的。 cifar-10 數(shù)據(jù)集由 60000 張分辨

    2023年04月24日
    瀏覽(21)
  • Resnet18訓練CIFAR10 準確率95%

    準確率 95.31% 幾個關(guān)鍵點: 1、改模型:原始的resnet18首層使用的7x7的卷積核,CIFAR10圖片太小不適合,要改成3x3的,步長和padding都要一并改成1。因為圖太小,最大池化層也同樣沒用,刪掉。最后一個全連接層輸出改成10。 2、圖片增強不要太多,只要訓練集和驗證集結(jié)果沒有出

    2024年02月02日
    瀏覽(28)
  • Pytorch CIFAR10圖像分類 SENet篇

    2024年02月07日
    瀏覽(21)
  • TensorFlow2進行CIFAR-10數(shù)據(jù)集動物識別,保存模型并且進行外部下載圖片測試

    TensorFlow2進行CIFAR-10數(shù)據(jù)集動物識別,保存模型并且進行外部下載圖片測試

    首先,你已經(jīng)安裝好anaconda3、創(chuàng)建好環(huán)境、下載好TensorFlow2模塊并且下載好jupyter了,那么我們就直接打開jupyter開始進行CIFAR10數(shù)據(jù)集的訓練。 第一步:下載CIFAR10數(shù)據(jù)集 下載網(wǎng)址:http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz 將數(shù)據(jù)集下載到合適的路徑,方便模型訓練的時候調(diào)用

    2024年02月08日
    瀏覽(26)
  • PyTorch實戰(zhàn):實現(xiàn)Cifar10彩色圖片分類

    PyTorch實戰(zhàn):實現(xiàn)Cifar10彩色圖片分類

    目錄 前言 一、Cifar10數(shù)據(jù)集 class torch.utils.data.Dataset ?torch.utils.data.DataLoader 二、定義神經(jīng)網(wǎng)絡(luò) 普通神經(jīng)網(wǎng)絡(luò): 定義損失函數(shù)和優(yōu)化器 ?訓練網(wǎng)絡(luò)-Net CPU訓練 模型準確率 ?編輯 GPU訓練 訓練網(wǎng)絡(luò)-LeNet 模型準確率 點關(guān)注,防走丟,如有紕漏之處,請留言指教,非常感謝 PyTorch可以

    2024年02月07日
    瀏覽(21)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包