PyTorch使用GPU訓練的兩種方法實例
Pytorch 使用GPU訓練
使用 GPU 訓練只需要在原來的代碼中修改幾處就可以了。
我們有兩種方式實現(xiàn)代碼在 GPU 上進行訓練
方法一 .cuda()
我們可以通過對網(wǎng)絡模型,數(shù)據(jù),損失函數(shù)這三種變量調(diào)用 .cuda() 來在GPU上進行訓練

# 將網(wǎng)絡模型在gpu上訓練 model = Model() model = model.cuda() # 損失函數(shù)在gpu上訓練 loss_fn = nn.CrossEntropyLoss() loss_fn = loss_fn.cuda() # 數(shù)據(jù)在gpu上訓練 for data in dataloader: imgs, targets = data imgs = imgs.cuda() targets = targets.cuda()
但是如果電腦沒有 GPU 就會報錯,更好的寫法是先判斷 cuda 是否可用:
# 將網(wǎng)絡模型在gpu上訓練
model = Model()
if torch.cuda.is_available():
model = model.cuda()
# 損失函數(shù)在gpu上訓練
loss_fn = nn.CrossEntropyLoss()
if torch.cuda.is_available():
loss_fn = loss_fn.cuda()
# 數(shù)據(jù)在gpu上訓練
for data in dataloader:
imgs, targets = data
if torch.cuda.is_available():
imgs = imgs.cuda()
targets = targets.cuda()
代碼案例:
# 以 CIFAR10 數(shù)據(jù)集為例,展示一下完整的模型訓練套路,完成對數(shù)據(jù)集的分類問題
import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import time
# 準備數(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("訓練數(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)絡模型
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 上進行訓練
# 創(chuàng)建損失函數(shù)
loss_fn = nn.CrossEntropyLoss()
if torch.cuda.is_available():
loss_fn = loss_fn.cuda() # 在 GPU 上進行訓練
# 優(yōu)化器
learning_rate = 1e-2 # 1e-2 = 1 * (10)^(-2) = 1 / 100 = 0.01
optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)
# 設置訓練網(wǎng)絡的一些參數(shù)
total_train_step = 0 # 記錄訓練的次數(shù)
total_test_step = 0 # 記錄測試的次數(shù)
epoch = 10 # 訓練的輪數(shù)
# 添加tensorboard
writer = SummaryWriter("logs_train")
start_time = time.time() # 開始訓練的時間
for i in range(epoch):
print("------第 {} 輪訓練開始------".format(i+1))
# 訓練步驟開始
for data in train_dataloader:
imgs, targets = data
if torch.cuda.is_available():
imgs = imgs.cuda()
targets = targets.cuda() # 在gpu上訓練
outputs = model(imgs) # 將訓練的數(shù)據(jù)放入
loss = loss_fn(outputs, targets) # 得到損失值
optimizer.zero_grad() # 優(yōu)化過程中首先要使用優(yōu)化器進行梯度清零
loss.backward() # 調(diào)用得到的損失,利用反向傳播,得到每一個參數(shù)節(jié)點的梯度
optimizer.step() # 對參數(shù)進行優(yōu)化
total_train_step += 1 # 上面就是進行了一次訓練,訓練次數(shù) +1
# 只有訓練步驟是100 倍數(shù)的時候才打印數(shù)據(jù),可以減少一些沒有用的數(shù)據(jù),方便我們找到其他數(shù)據(jù)
if total_train_step % 100 == 0:
end_time = time.time() # 訓練結束時間
print("訓練時間: {}".format(end_time - start_time))
print("訓練次數(shù): {}, Loss: {}".format(total_train_step, loss))
writer.add_scalar("train_loss", loss.item(), total_train_step)
# 如何知道模型有沒有訓練好,即有咩有達到自己想要的需求
# 我們可以在每次訓練完一輪后,進行一次測試,在測試數(shù)據(jù)集上跑一遍,以測試數(shù)據(jù)集上的損失或正確率評估我們的模型有沒有訓練好
# 顧名思義,下面的代碼沒有梯度,即我們不會利用進行調(diào)優(yōu)
total_test_loss = 0
total_accuracy = 0 # 準確率
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 上進行訓練
targets = targets.cuda()
outputs = model(imgs)
loss = loss_fn(outputs, targets) # 這里的 loss 只是一部分數(shù)據(jù)(data) 在網(wǎng)絡模型上的損失
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)
指定 訓練的設備
device = torch.device("cpu") # 使用cpu訓練
device = torch.device("cuda") # 使用gpu訓練
device = torch.device("cuda:0") # 當電腦中有多張顯卡時,使用第一張顯卡
device = torch.device("cuda:1") # 當電腦中有多張顯卡時,使用第二張顯卡
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
使用 GPU 訓練
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ù)集為例,展示一下完整的模型訓練套路,完成對數(shù)據(jù)集的分類問題
import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import time
# 定義訓練的設備
device = torch.device("cuda")
# 準備數(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("訓練數(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)絡模型
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 上進行訓練
# 創(chuàng)建損失函數(shù)
loss_fn = nn.CrossEntropyLoss()
loss_fn = loss_fn.to(device) # 在 GPU 上進行訓練
# 優(yōu)化器
learning_rate = 1e-2 # 1e-2 = 1 * (10)^(-2) = 1 / 100 = 0.01
optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)
# 設置訓練網(wǎng)絡的一些參數(shù)
total_train_step = 0 # 記錄訓練的次數(shù)
total_test_step = 0 # 記錄測試的次數(shù)
epoch = 10 # 訓練的輪數(shù)
# 添加tensorboard
writer = SummaryWriter("logs_train")
start_time = time.time() # 開始訓練的時間
for i in range(epoch):
print("------第 {} 輪訓練開始------".format(i+1))
# 訓練步驟開始
for data in train_dataloader:
imgs, targets = data
imgs = imgs.to(device)
targets = targets.to(device)
outputs = model(imgs) # 將訓練的數(shù)據(jù)放入
loss = loss_fn(outputs, targets) # 得到損失值
optimizer.zero_grad() # 優(yōu)化過程中首先要使用優(yōu)化器進行梯度清零
loss.backward() # 調(diào)用得到的損失,利用反向傳播,得到每一個參數(shù)節(jié)點的梯度
optimizer.step() # 對參數(shù)進行優(yōu)化
total_train_step += 1 # 上面就是進行了一次訓練,訓練次數(shù) +1
# 只有訓練步驟是100 倍數(shù)的時候才打印數(shù)據(jù),可以減少一些沒有用的數(shù)據(jù),方便我們找到其他數(shù)據(jù)
if total_train_step % 100 == 0:
end_time = time.time() # 訓練結束時間
print("訓練時間: {}".format(end_time - start_time))
print("訓練次數(shù): {}, Loss: {}".format(total_train_step, loss))
writer.add_scalar("train_loss", loss.item(), total_train_step)
# 如何知道模型有沒有訓練好,即有咩有達到自己想要的需求
# 我們可以在每次訓練完一輪后,進行一次測試,在測試數(shù)據(jù)集上跑一遍,以測試數(shù)據(jù)集上的損失或正確率評估我們的模型有沒有訓練好
# 顧名思義,下面的代碼沒有梯度,即我們不會利用進行調(diào)優(yōu)
total_test_loss = 0
total_accuracy = 0 # 準確率
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 只是一部分數(shù)據(jù)(data) 在網(wǎng)絡模型上的損失
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()
![[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(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)絡模型和損失函數(shù),直接調(diào)用 .cuda() 或者 .to() 即可。但是數(shù)據(jù)和標注需要返回變量
為了方便記憶,最好都返回變量
使用Google colab進行訓練
附:一些和GPU有關的基本操作匯總
# 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()總結
到此這篇關于PyTorch使用GPU訓練的兩種方法的文章就介紹到這了,更多相關PyTorch使用GPU訓練內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python中Numpy和Matplotlib的基本使用指南
numpy庫處理的最基礎數(shù)據(jù)類型是由同種元素構成的多維數(shù)組(ndarray),而matplotlib 是提供數(shù)據(jù)繪圖功能的第三方庫,其pyplot子庫主要用于實現(xiàn)各種數(shù)據(jù)展示圖形的繪制,這篇文章主要給大家介紹了關于Python中Numpy和Matplotlib的基本使用指南,需要的朋友可以參考下2021-11-11
使用Python高效獲取網(wǎng)絡數(shù)據(jù)的操作指南
網(wǎng)絡爬蟲是一種自動化程序,用于訪問和提取網(wǎng)站上的數(shù)據(jù),Python是進行網(wǎng)絡爬蟲開發(fā)的理想語言,擁有豐富的庫和工具,使得編寫和維護爬蟲變得簡單高效,本文將詳細介紹如何使用Python進行網(wǎng)絡爬蟲開發(fā),包括基本概念、常用庫、數(shù)據(jù)提取方法、反爬措施應對以及實際案例2025-03-03
用python實現(xiàn)的可以拷貝或剪切一個文件列表中的所有文件
python 實現(xiàn)剪切或是拷貝一個文件列表中的所有文件2009-04-04
TensorFlow學習之分布式的TensorFlow運行環(huán)境
這篇文章主要了TensorFlow學習之分布式的TensorFlow運行環(huán)境的相關知識,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02

