要在PyTorch中使用GPU進行數據集的加載、模型的訓練和最后模型的測試,需要將數據集和模型都移動到GPU上,并確保在訓練和測試過程中都在GPU上進行計算。以下是一個完整的示例代碼,展示了如何在PyTorch中使用GPU進行端到端的訓練和測試:
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset# 檢查GPU是否可用
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")# 準備訓練和測試數據,并將其移動到GPU
train_input = torch.randn(100, 10).to(device)
train_target = torch.randn(100, 1).to(device)
test_input = torch.randn(20, 10).to(device)
test_target = torch.randn(20, 1).to(device)# 創建數據集和數據加載器
train_dataset = TensorDataset(train_input, train_target)
train_loader = DataLoader(train_dataset, batch_size=10, shuffle=True)# 定義一個簡單的神經網絡模型,并將其移動到GPU
class SimpleModel(nn.Module):def __init__(self):super(SimpleModel, self).__init__()self.fc1 = nn.Linear(10, 5)self.relu = nn.ReLU()self.fc2 = nn.Linear(5, 1)def forward(self, x):x = self.fc1(x)x = self.relu(x)x = self.fc2(x)return xmodel = SimpleModel().to(device)# 定義損失函數和優化器
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.01)# 訓練模型
model.train()
for epoch in range(100):for input_data, target_data in train_loader:optimizer.zero_grad()output = model(input_data)loss = criterion(output, target_data)loss.backward()optimizer.step()# 測試模型
model.eval()
with torch.no_grad():test_output = model(test_input)test_loss = criterion(test_output, test_target)print(f'Test Loss: {test_loss.item()}')
在這個示例中,我們首先檢查GPU是否可用,并將訓練和測試數據移動到GPU上。然后,我們創建了數據集和數據加載器,定義了神經網絡模型,并將模型移動到GPU。在訓練過程中,我們使用數據加載器加載數據進行訓練;在測試過程中,我們使用model.eval()
將模型切換為評估模式,并使用torch.no_grad()
上下文管理器關閉梯度計算,以避免在測試過程中更新模型參數。最后,我們計算了模型在測試集上的損失。整個訓練和測試過程都在GPU上進行,以加速計算和提高效率。