PyTorch使用GPU訓(xùn)練的兩種方法實(shí)例
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 就會(huì)報(bào)錯(cuò),更好的寫法是先判斷 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ù)會(huì)替換 {}
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)練的時(shí)間
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)用得到的損失,利用反向傳播,得到每一個(gè)參數(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í)候才打印數(shù)據(jù),可以減少一些沒有用的數(shù)據(jù),方便我們找到其他數(shù)據(jù)
if total_train_step % 100 == 0:
end_time = time.time() # 訓(xùn)練結(jié)束時(shí)間
print("訓(xùn)練時(shí)間: {}".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)練好
# 顧名思義,下面的代碼沒有梯度,即我們不會(huì)利用進(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 # 整個(gè)測試集的loss
accuracy = (outputs.argmax(1) == targets).sum() # 分類正確個(gè)數(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)電腦中有多張顯卡時(shí),使用第一張顯卡
device = torch.device("cuda:1") # 當(dāng)電腦中有多張顯卡時(shí),使用第二張顯卡
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ù)會(huì)替換 {}
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)練的時(shí)間
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)用得到的損失,利用反向傳播,得到每一個(gè)參數(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í)候才打印數(shù)據(jù),可以減少一些沒有用的數(shù)據(jù),方便我們找到其他數(shù)據(jù)
if total_train_step % 100 == 0:
end_time = time.time() # 訓(xùn)練結(jié)束時(shí)間
print("訓(xùn)練時(shí)間: {}".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)練好
# 顧名思義,下面的代碼沒有梯度,即我們不會(huì)利用進(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 # 整個(gè)測試集的loss
accuracy = (outputs.argmax(1) == targets).sum() # 分類正確個(gè)數(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)]](http://img.jbzj.com/file_images/article/202205/2022051714314525.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間移動(dòng)
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,將模型中的全部張量移動(dòng)到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)建支持多個(gè)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ù)時(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)存時(shí)十分有用
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í)現(xiàn)的登陸Discuz!論壇通用代碼分享
這篇文章主要介紹了python實(shí)現(xiàn)的登陸Discuz!論壇通用代碼分享,需要的朋友可以參考下2014-07-07
Python讀取excel文件中的數(shù)據(jù),繪制折線圖及散點(diǎn)圖
這篇文章主要介紹了Python讀取excel文件中的數(shù)據(jù),繪制折線圖及散點(diǎn)圖,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09
在keras 中獲取張量 tensor 的維度大小實(shí)例
這篇文章主要介紹了在keras 中獲取張量 tensor 的維度大小實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
python正則表達(dá)式實(shí)現(xiàn)自動(dòng)化編程
這篇文章主要介紹了python正則表達(dá)式實(shí)現(xiàn)自動(dòng)化編程,re模塊的compile()方法是構(gòu)成正則表達(dá)式的方法,向compile()傳入一個(gè)字符串表示正則表達(dá)式,該方法返回一個(gè)Regex模式的對象,需要的朋友可以參考下2023-01-01
python刪除列表元素的三種方法(remove,pop,del)
這篇文章主要介紹了python刪除列表元素的三種方法(remove,pop,del),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
使用python的pyplot繪制函數(shù)實(shí)例
今天小編就為大家分享一篇使用python的pyplot繪制函數(shù)實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
Python中的優(yōu)先隊(duì)列(priority?queue)和堆(heap)
這篇文章主要介紹了Python中的優(yōu)先隊(duì)列(priority?queue)和堆(heap),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
Python實(shí)現(xiàn)K-近鄰算法的示例代碼
k-近鄰算法(K-Nearest Neighbour algorithm),又稱 KNN 算法,是數(shù)據(jù)挖掘技術(shù)中原理最簡單的算法。本文將介紹實(shí)現(xiàn)K-近鄰算法的示例代碼,需要的可以參考一下2022-09-09

