使用pytorch定义卷积神经网络如何设置学习率衰减
时间: 2023-12-16 22:03:49 浏览: 83
在PyTorch中,可以使用torch.optim.lr_scheduler模块来设置学习率衰减。以下是使用StepLR调度器来设置每过一定的epoch就将学习率衰减一定的倍数的示例代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
# 定义卷积神经网络模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(nn.functional.relu(self.conv1(x)))
x = self.pool(nn.functional.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = nn.functional.relu(self.fc1(x))
x = nn.functional.relu(self.fc2(x))
x = self.fc3(x)
return x
# 定义数据集和优化器
train_loader = torch.utils.data.DataLoader(...)
model = Net()
optimizer = optim.SGD(model.parameters(), lr=0.1)
# 定义学习率衰减策略
scheduler = StepLR(optimizer, step_size=10, gamma=0.1)
# 训练模型
for epoch in range(num_epochs):
for i, (inputs, labels) in enumerate(train_loader):
optimizer.zero_grad()
outputs = model(inputs)
loss = nn.CrossEntropyLoss()(outputs, labels)
loss.backward()
optimizer.step()
scheduler.step()
# 在每个step_size(这里为10)个epoch后,学习率会乘以gamma(这里为0.1),从而实现学习率衰减。
```
如果想使用其他的学习率衰减策略,只需要更改scheduler的类型和对应的参数即可。
阅读全文