PyTorch反向传播中学习率的设置方法及相关疑问解答
关于PyTorch中学习率的设置与权重更新
首先要明确:loss.backward()只是计算梯度,并不负责更新权重,权重更新是由优化器(Optimizer)完成的,学习率也是在初始化优化器时指定的,不是在反向传播步骤中设置。
步骤1:初始化优化器并指定学习率
PyTorch提供了多种优化器(比如SGD、Adam等),你需要将模型的参数传入优化器,并通过lr参数指定学习率。以常用的SGD为例:
# 在定义损失函数后添加这行代码 optimizer = optim.SGD(model.parameters(), lr=0.1) # 这里lr=0.1就是你指定的学习率
不同优化器的默认学习率不同:
SGD默认学习率是0.01Adam默认学习率是0.001
步骤2:执行权重更新
在调用loss.backward()计算完梯度后,需要调用优化器的step()方法来完成权重更新:
loss.backward() optimizer.step() # 这一步才会用学习率×梯度来更新模型权重
修改后的完整代码
把优化器的初始化和权重更新步骤加入你的代码:
import torch import torch.nn as nn import torch.optim as optim class MyNeuralNetwork(nn.Module): def __init__(self): super(MyNeuralNetwork, self).__init__() layer_1=nn.Linear(in_features=2, out_features=2, bias=False) weight_1 = torch.tensor([[.3,.25],[.4, .35]]) layer_1.weight = nn.Parameter(weight_1) self.layer1 = nn.Sequential( layer_1, nn.Sigmoid() ) layer_2 = nn.Linear(in_features=2, out_features=2, bias=False) weight_2 = torch.tensor([[.45, .4],[.7, .6]]) layer_2.weight = nn.Parameter(weight_2) self.layer2 = nn.Sequential( layer_2, nn.Sigmoid() ) def forward(self, input): output = self.layer1(input) output = self.layer2(output) return output model = MyNeuralNetwork().to("cpu") print(model) input = torch.tensor([0.1,0.2]).reshape(1,-1) target = torch.tensor([0.4,0.6]).reshape(1,-1) # 初始化优化器,指定学习率为0.1 optimizer = optim.SGD(model.parameters(), lr=0.1) out = model(input) print(f"output value : {out}") criterion = nn.MSELoss() loss = criterion(out, target) print(f"loss value : {loss}") model.zero_grad() print('↓ layer1.weight before backward propagation ↓') print(model._modules['layer1']._modules['0'].weight) print(model._modules['layer2']._modules['0'].weight) print() loss.backward() optimizer.step() # 执行权重更新 print('↓ layer1.weight after backward propagation and optimizer step ↓') print(model._modules['layer1']._modules['0'].weight) print(model._modules['layer2']._modules['0'].weight)
关键说明
- 每次训练循环(如果是多轮训练)都需要先调用
model.zero_grad()清空之前的梯度,避免梯度累积。 - 学习率的大小会直接影响模型的训练效果:过大可能导致模型震荡不收敛,过小则训练速度太慢。
内容的提问来源于stack exchange,提问作者Umgee
相关产品推荐
相关产品推荐

