torch gpu 使用样例
时间: 2023-09-11 14:04:55 浏览: 76
pytorch使用指定GPU训练的实例
以下是使用 PyTorch 在 GPU 上训练深度学习模型的示例代码:
```python
import torch
# 检查 GPU 是否可用
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
# 定义模型
class MyModel(torch.nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = torch.nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1)
self.conv2 = torch.nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
self.fc1 = torch.nn.Linear(64 * 16 * 16, 256)
self.fc2 = torch.nn.Linear(256, 10)
def forward(self, x):
x = torch.nn.functional.relu(self.conv1(x))
x = torch.nn.functional.relu(self.conv2(x))
x = x.view(-1, 64 * 16 * 16)
x = torch.nn.functional.relu(self.fc1(x))
x = self.fc2(x)
return x
# 加载数据
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True)
# 初始化模型和优化器
model = MyModel().to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 训练模型
for epoch in range(10):
for i, (inputs, labels) in enumerate(train_loader):
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = torch.nn.functional.cross_entropy(outputs, labels)
loss.backward()
optimizer.step()
if i % 100 == 0:
print("Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}".format(epoch+1, 10, i+1, len(train_loader), loss.item()))
# 保存模型
torch.save(model.state_dict(), "my_model.pt")
```
其中,`device` 变量检查 GPU 是否可用,`model.to(device)` 将模型移动到 GPU 上,`inputs.to(device)` 和 `labels.to(device)` 将数据移动到 GPU 上,从而实现在 GPU 上训练模型。
阅读全文