pytorch训练模型写法
时间: 2023-11-03 16:58:28 浏览: 106
在PyTorch中,训练模型的写法通常包括以下几个步骤:
1. 导入必要的库和模块:
```
import torch
import torchvision
import torch.nn as nn
import torch.optim as optim
```
2. 定义模型结构:
```
model = torchvision.models.resnet50(pretrained=True)
```
3. 定义损失函数和优化器:
```
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
```
4. 进行训练循环:
```
for epoch in range(num_epochs):
model.train() # 将模型切换至训练模式
running_loss = 0.0
for images, labels in train_loader:
# 前向传播
outputs = model(images)
loss = criterion(outputs, labels)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
running_loss += loss.item()
# 计算并打印每个epoch的平均损失
epoch_loss = running_loss / len(train_loader)
print(f"Epoch [{epoch+1}/{num_epochs}], Loss: {epoch_loss:.4f}")
```
5. 在验证集上评估模型性能:
```
model.eval() # 将模型切换至验证模式
with torch.no_grad():
correct = 0
total = 0
for images, labels in val_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
print(f"Validation Accuracy: {accuracy:.2f}%")
```
阅读全文