最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

PyTorch使用GPU訓(xùn)練的兩種方法實(shí)例

 更新時間:2022年05月17日 14:39:11   作者:風(fēng)吹我亦散  
pytorch是一個非常優(yōu)秀的深度學(xué)習(xí)的框架,具有速度快,代碼簡潔,可讀性強(qiáng)的優(yōu)點(diǎn),下面這篇文章主要給大家介紹了關(guān)于PyTorch使用GPU訓(xùn)練的兩種方法,需要的朋友可以參考下

Pytorch 使用GPU訓(xùn)練

使用 GPU 訓(xùn)練只需要在原來的代碼中修改幾處就可以了。

我們有兩種方式實(shí)現(xiàn)代碼在 GPU 上進(jìn)行訓(xùn)練

方法一 .cuda()

我們可以通過對網(wǎng)絡(luò)模型,數(shù)據(jù),損失函數(shù)這三種變量調(diào)用 .cuda() 來在GPU上進(jìn)行訓(xùn)練

# 將網(wǎng)絡(luò)模型在gpu上訓(xùn)練
model = Model()
model = model.cuda()

# 損失函數(shù)在gpu上訓(xùn)練
loss_fn = nn.CrossEntropyLoss()
loss_fn = loss_fn.cuda()

# 數(shù)據(jù)在gpu上訓(xùn)練
for data in dataloader:                        
	imgs, targets = data
	imgs = imgs.cuda()
	targets = targets.cuda()

但是如果電腦沒有 GPU 就會報錯,更好的寫法是先判斷 cuda 是否可用:

# 將網(wǎng)絡(luò)模型在gpu上訓(xùn)練
model = Model()
if torch.cuda.is_available():
	model = model.cuda()

# 損失函數(shù)在gpu上訓(xùn)練
loss_fn = nn.CrossEntropyLoss()
if torch.cuda.is_available():	
	loss_fn = loss_fn.cuda()

# 數(shù)據(jù)在gpu上訓(xùn)練
for data in dataloader:                        
	imgs, targets = data
    if torch.cuda.is_available():
        imgs = imgs.cuda()
        targets = targets.cuda()

代碼案例:

# 以 CIFAR10 數(shù)據(jù)集為例,展示一下完整的模型訓(xùn)練套路,完成對數(shù)據(jù)集的分類問題

import torch
import torchvision

from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import time

# 準(zhǔn)備數(shù)據(jù)集
train_data = torchvision.datasets.CIFAR10(root="dataset", train=True, transform=torchvision.transforms.ToTensor(), download=True)
test_data = torchvision.datasets.CIFAR10(root="dataset", train=False, transform=torchvision.transforms.ToTensor(), download=True)

# 獲得數(shù)據(jù)集的長度 len(), 即length
train_data_size = len(train_data)
test_data_size = len(test_data)

# 格式化字符串, format() 中的數(shù)據(jù)會替換 {}
print("訓(xùn)練數(shù)據(jù)集及的長度為: {}".format(train_data_size))
print("測試數(shù)據(jù)集及的長度為: {}".format(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ò)模型
class Model(nn.Module):
    def __init__(self) -> None:
        super().__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, input):
        input = self.model(input)
        return input

model = Model()
if torch.cuda.is_available():
    model = model.cuda()                        # 在 GPU 上進(jìn)行訓(xùn)練

# 創(chuàng)建損失函數(shù)
loss_fn = nn.CrossEntropyLoss()
if torch.cuda.is_available():
    loss_fn = loss_fn.cuda()                    # 在 GPU 上進(jìn)行訓(xùn)練

# 優(yōu)化器
learning_rate = 1e-2        # 1e-2 = 1 * (10)^(-2) = 1 / 100 = 0.01
optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)

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

# 添加tensorboard
writer = SummaryWriter("logs_train")
start_time = time.time()                    # 開始訓(xùn)練的時間
for i in range(epoch):
    print("------第 {} 輪訓(xùn)練開始------".format(i+1))

    # 訓(xùn)練步驟開始
    for data in train_dataloader:
        imgs, targets = data
        if torch.cuda.is_available():
            imgs = imgs.cuda()
        targets = targets.cuda()            # 在gpu上訓(xùn)練
        outputs = model(imgs)               # 將訓(xùn)練的數(shù)據(jù)放入
        loss = loss_fn(outputs, targets)    # 得到損失值

        optimizer.zero_grad()               # 優(yōu)化過程中首先要使用優(yōu)化器進(jìn)行梯度清零
        loss.backward()                     # 調(diào)用得到的損失,利用反向傳播,得到每一個參數(shù)節(jié)點(diǎn)的梯度
        optimizer.step()                    # 對參數(shù)進(jìn)行優(yōu)化
        total_train_step += 1               # 上面就是進(jìn)行了一次訓(xùn)練,訓(xùn)練次數(shù) +1

        # 只有訓(xùn)練步驟是100 倍數(shù)的時候才打印數(shù)據(jù),可以減少一些沒有用的數(shù)據(jù),方便我們找到其他數(shù)據(jù)
        if total_train_step % 100 == 0:
            end_time = time.time()          # 訓(xùn)練結(jié)束時間
            print("訓(xùn)練時間: {}".format(end_time - start_time))
            print("訓(xùn)練次數(shù): {}, Loss: {}".format(total_train_step, loss))
            writer.add_scalar("train_loss", loss.item(), total_train_step)


    # 如何知道模型有沒有訓(xùn)練好,即有咩有達(dá)到自己想要的需求
    # 我們可以在每次訓(xùn)練完一輪后,進(jìn)行一次測試,在測試數(shù)據(jù)集上跑一遍,以測試數(shù)據(jù)集上的損失或正確率評估我們的模型有沒有訓(xùn)練好

    # 顧名思義,下面的代碼沒有梯度,即我們不會利用進(jìn)行調(diào)優(yōu)
    total_test_loss = 0
    total_accuracy = 0                                      # 準(zhǔn)確率
    with torch.no_grad():
        for data in test_dataloader:                        # 測試數(shù)據(jù)集中取數(shù)據(jù)
            imgs, targets = data
            if torch.cuda.is_available():
                imgs = imgs.cuda()                          # 在 GPU 上進(jìn)行訓(xùn)練
                targets = targets.cuda()
            outputs = model(imgs)
            loss = loss_fn(outputs, targets)                # 這里的 loss 只是一部分?jǐn)?shù)據(jù)(data) 在網(wǎng)絡(luò)模型上的損失
            total_test_loss = total_test_loss + loss        # 整個測試集的loss
            accuracy = (outputs.argmax(1) == targets).sum() # 分類正確個數(shù)
            total_accuracy += accuracy                      # 相加

    print("整體測試集上的loss: {}".format(total_test_loss))
    print("整體測試集上的正確率: {}".format(total_accuracy / test_data_size))
    writer.add_scalar("test_loss", total_test_loss)
    writer.add_scalar("test_accuracy", total_accuracy / test_data_size, total_test_step)
    total_test_loss += 1                                    # 測試完了之后要 +1

    torch.save(model, "model_{}.pth".format(i))
    print("模型已保存")

writer.close()

方法二 .to(device)

指定 訓(xùn)練的設(shè)備

device = torch.device("cpu")	# 使用cpu訓(xùn)練
device = torch.device("cuda")	# 使用gpu訓(xùn)練 
device = torch.device("cuda:0")	# 當(dāng)電腦中有多張顯卡時,使用第一張顯卡
device = torch.device("cuda:1")	# 當(dāng)電腦中有多張顯卡時,使用第二張顯卡

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

使用 GPU 訓(xùn)練

model = model.to(device)

loss_fn = loss_fn.to(device)

for data in train_dataloader:
    imgs, targets = data
    imgs = imgs.to(device)
    targets = targets.to(device)

代碼示例:

# 以 CIFAR10 數(shù)據(jù)集為例,展示一下完整的模型訓(xùn)練套路,完成對數(shù)據(jù)集的分類問題

import torch
import torchvision

from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import time

# 定義訓(xùn)練的設(shè)備
device = torch.device("cuda")

# 準(zhǔn)備數(shù)據(jù)集
train_data = torchvision.datasets.CIFAR10(root="dataset", train=True, transform=torchvision.transforms.ToTensor(), download=True)
test_data = torchvision.datasets.CIFAR10(root="dataset", train=False, transform=torchvision.transforms.ToTensor(), download=True)

# 獲得數(shù)據(jù)集的長度 len(), 即length
train_data_size = len(train_data)
test_data_size = len(test_data)

# 格式化字符串, format() 中的數(shù)據(jù)會替換 {}
print("訓(xùn)練數(shù)據(jù)集及的長度為: {}".format(train_data_size))
print("測試數(shù)據(jù)集及的長度為: {}".format(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ò)模型
class Model(nn.Module):
    def __init__(self) -> None:
        super().__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, input):
        input = self.model(input)
        return input

model = Model()
model = model.to(device)                    # 在 GPU 上進(jìn)行訓(xùn)練

# 創(chuàng)建損失函數(shù)
loss_fn = nn.CrossEntropyLoss()
loss_fn = loss_fn.to(device)                # 在 GPU 上進(jìn)行訓(xùn)練

# 優(yōu)化器
learning_rate = 1e-2        # 1e-2 = 1 * (10)^(-2) = 1 / 100 = 0.01
optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)

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

# 添加tensorboard
writer = SummaryWriter("logs_train")
start_time = time.time()                    # 開始訓(xùn)練的時間
for i in range(epoch):
    print("------第 {} 輪訓(xùn)練開始------".format(i+1))

    # 訓(xùn)練步驟開始
    for data in train_dataloader:
        imgs, targets = data
        imgs = imgs.to(device)
        targets = targets.to(device)
        outputs = model(imgs)               # 將訓(xùn)練的數(shù)據(jù)放入
        loss = loss_fn(outputs, targets)    # 得到損失值

        optimizer.zero_grad()               # 優(yōu)化過程中首先要使用優(yōu)化器進(jìn)行梯度清零
        loss.backward()                     # 調(diào)用得到的損失,利用反向傳播,得到每一個參數(shù)節(jié)點(diǎn)的梯度
        optimizer.step()                    # 對參數(shù)進(jìn)行優(yōu)化
        total_train_step += 1               # 上面就是進(jìn)行了一次訓(xùn)練,訓(xùn)練次數(shù) +1

        # 只有訓(xùn)練步驟是100 倍數(shù)的時候才打印數(shù)據(jù),可以減少一些沒有用的數(shù)據(jù),方便我們找到其他數(shù)據(jù)
        if total_train_step % 100 == 0:
            end_time = time.time()          # 訓(xùn)練結(jié)束時間
            print("訓(xùn)練時間: {}".format(end_time - start_time))
            print("訓(xùn)練次數(shù): {}, Loss: {}".format(total_train_step, loss))
            writer.add_scalar("train_loss", loss.item(), total_train_step)


    # 如何知道模型有沒有訓(xùn)練好,即有咩有達(dá)到自己想要的需求
    # 我們可以在每次訓(xùn)練完一輪后,進(jìn)行一次測試,在測試數(shù)據(jù)集上跑一遍,以測試數(shù)據(jù)集上的損失或正確率評估我們的模型有沒有訓(xùn)練好

    # 顧名思義,下面的代碼沒有梯度,即我們不會利用進(jìn)行調(diào)優(yōu)
    total_test_loss = 0
    total_accuracy = 0                                      # 準(zhǔn)確率
    with torch.no_grad():
        for data in test_dataloader:                        # 測試數(shù)據(jù)集中取數(shù)據(jù)
            imgs, targets = data
            imgs = imgs.to(device)
            targets = targets.to(device)
            outputs = model(imgs)
            loss = loss_fn(outputs, targets)                # 這里的 loss 只是一部分?jǐn)?shù)據(jù)(data) 在網(wǎng)絡(luò)模型上的損失
            total_test_loss = total_test_loss + loss        # 整個測試集的loss
            accuracy = (outputs.argmax(1) == targets).sum() # 分類正確個數(shù)
            total_accuracy += accuracy                      # 相加

    print("整體測試集上的loss: {}".format(total_test_loss))
    print("整體測試集上的正確率: {}".format(total_accuracy / test_data_size))
    writer.add_scalar("test_loss", total_test_loss)
    writer.add_scalar("test_accuracy", total_accuracy / test_data_size, total_test_step)
    total_test_loss += 1                                    # 測試完了之后要 +1

    torch.save(model, "model_{}.pth".format(i))
    print("模型已保存")

writer.close()

[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-Pw65Px5W-1645015877614)(C:\Users\14158\AppData\Roaming\Typora\typora-user-images\1644999041019.png)]

【注】對于網(wǎng)絡(luò)模型和損失函數(shù),直接調(diào)用 .cuda() 或者 .to() 即可。但是數(shù)據(jù)和標(biāo)注需要返回變量

為了方便記憶,最好都返回變量

使用Google colab進(jìn)行訓(xùn)練

附:一些和GPU有關(guān)的基本操作匯總

# 1,查看gpu信息
if_cuda = torch.cuda.is_available()
print("if_cuda=",if_cuda)

# GPU 的數(shù)量
gpu_count = torch.cuda.device_count()
print("gpu_count=",gpu_count)

# 2,將張量在gpu和cpu間移動
tensor = torch.rand((100,100))
tensor_gpu = tensor.to("cuda:0") # 或者 tensor_gpu = tensor.cuda()
print(tensor_gpu.device)
print(tensor_gpu.is_cuda)

tensor_cpu = tensor_gpu.to("cpu") # 或者 tensor_cpu = tensor_gpu.cpu()?
print(tensor_cpu.device)

# 3,將模型中的全部張量移動到gpu上
net = nn.Linear(2,1)
print(next(net.parameters()).is_cuda)
net.to("cuda:0") # 將模型中的全部參數(shù)張量依次到GPU上,注意,無需重新賦值為 net = net.to("cuda:0")
print(next(net.parameters()).is_cuda)
print(next(net.parameters()).device)

# 4,創(chuàng)建支持多個gpu數(shù)據(jù)并行的模型
linear = nn.Linear(2,1)
print(next(linear.parameters()).device)

model = nn.DataParallel(linear)
print(model.device_ids)
print(next(model.module.parameters()).device)?

#注意保存參數(shù)時要指定保存model.module的參數(shù)
torch.save(model.module.state_dict(), "./data/model_parameter.pkl")?

linear = nn.Linear(2,1)
linear.load_state_dict(torch.load("./data/model_parameter.pkl"))?

# 5,清空cuda緩存
# 該方在cuda超內(nèi)存時十分有用
torch.cuda.empty_cache()

總結(jié)

到此這篇關(guān)于PyTorch使用GPU訓(xùn)練的兩種方法的文章就介紹到這了,更多相關(guān)PyTorch使用GPU訓(xùn)練內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python命令行參數(shù)sys.argv使用示例

    python命令行參數(shù)sys.argv使用示例

    這篇文章主要介紹了python命令行參數(shù)sys.argv使用示例,大家參考使用吧
    2014-01-01
  • 如何利用python將Xmind用例轉(zhuǎn)為Excel用例

    如何利用python將Xmind用例轉(zhuǎn)為Excel用例

    這篇文章主要介紹了如何利用python將Xmind用例轉(zhuǎn)為Excel用例,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-06-06
  • Python Paramiko模塊的安裝與使用詳解

    Python Paramiko模塊的安裝與使用詳解

    最近閑著學(xué)習(xí)python,看到有個paramiko模塊,貌似很強(qiáng)大,所以從網(wǎng)上學(xué)習(xí)后總結(jié)了這篇文章,下面這篇文章就給大家介紹了Python中Paramiko模塊的安裝與使用,文中介紹的很詳細(xì),相信對大家的學(xué)習(xí)很有幫助,有需要的朋友們下面來一起看看吧。
    2016-11-11
  • python屬于解釋語言嗎

    python屬于解釋語言嗎

    在本篇文章里小編給大家分享了關(guān)于python關(guān)于是否為解釋語言的知識點(diǎn),有興趣的朋友們可以學(xué)習(xí)下。
    2020-06-06
  • Python中Numpy和Matplotlib的基本使用指南

    Python中Numpy和Matplotlib的基本使用指南

    numpy庫處理的最基礎(chǔ)數(shù)據(jù)類型是由同種元素構(gòu)成的多維數(shù)組(ndarray),而matplotlib 是提供數(shù)據(jù)繪圖功能的第三方庫,其pyplot子庫主要用于實(shí)現(xiàn)各種數(shù)據(jù)展示圖形的繪制,這篇文章主要給大家介紹了關(guān)于Python中Numpy和Matplotlib的基本使用指南,需要的朋友可以參考下
    2021-11-11
  • 使用Python高效獲取網(wǎng)絡(luò)數(shù)據(jù)的操作指南

    使用Python高效獲取網(wǎng)絡(luò)數(shù)據(jù)的操作指南

    網(wǎng)絡(luò)爬蟲是一種自動化程序,用于訪問和提取網(wǎng)站上的數(shù)據(jù),Python是進(jìn)行網(wǎng)絡(luò)爬蟲開發(fā)的理想語言,擁有豐富的庫和工具,使得編寫和維護(hù)爬蟲變得簡單高效,本文將詳細(xì)介紹如何使用Python進(jìn)行網(wǎng)絡(luò)爬蟲開發(fā),包括基本概念、常用庫、數(shù)據(jù)提取方法、反爬措施應(yīng)對以及實(shí)際案例
    2025-03-03
  • python提取字符串中的數(shù)字的實(shí)現(xiàn)

    python提取字符串中的數(shù)字的實(shí)現(xiàn)

    本文主要介紹了python提取字符串中的數(shù)字的實(shí)現(xiàn),主要介紹了幾種常見的方法,具有一定的參考價值,感興趣的可以了解一下
    2023-10-10
  • 用python實(shí)現(xiàn)的可以拷貝或剪切一個文件列表中的所有文件

    用python實(shí)現(xiàn)的可以拷貝或剪切一個文件列表中的所有文件

    python 實(shí)現(xiàn)剪切或是拷貝一個文件列表中的所有文件
    2009-04-04
  • Python編譯結(jié)果之code對象與pyc文件詳解

    Python編譯結(jié)果之code對象與pyc文件詳解

    今天小編就為大家分享一篇對Python編譯結(jié)果之code對象與pyc文件的詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-10-10
  • TensorFlow學(xué)習(xí)之分布式的TensorFlow運(yùn)行環(huán)境

    TensorFlow學(xué)習(xí)之分布式的TensorFlow運(yùn)行環(huán)境

    這篇文章主要了TensorFlow學(xué)習(xí)之分布式的TensorFlow運(yùn)行環(huán)境的相關(guān)知識,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-02-02

最新評論

汾西县| 晴隆县| 株洲市| 佛山市| 侯马市| 曲松县| 平度市| 石家庄市| 洪泽县| 淮南市| 溆浦县| 桐柏县| 兴化市| 崇左市| 汽车| 陵川县| 新营市| 南通市| 武宣县| 遵化市| 桂东县| 福州市| 隆昌县| 宿松县| 五大连池市| 台中市| 廊坊市| 双桥区| 确山县| 肥西县| 江西省| 阳高县| 广河县| 英吉沙县| 隆尧县| 册亨县| 松江区| 内丘县| 五寨县| 聊城市| 大余县|