我试图理解PyTorch
. 我的问题与这两个有些相关:
为什么我们需要在 PyTorch 中调用 zero_grad()?
对第二个问题的已接受答案的评论表明,如果小批量太大而无法在单个前向传递中执行梯度更新,因此必须将其拆分为多个子批次,则可以使用累积梯度。
考虑以下玩具示例:
import numpy as np
import torch
class ExampleLinear(torch.nn.Module):
def __init__(self):
super().__init__()
# Initialize the weight at 1
self.weight = torch.nn.Parameter(torch.Tensor([1]).float(),
requires_grad=True)
def forward(self, x):
return self.weight * x
if __name__ == "__main__":
# Example 1
model = ExampleLinear()
# Generate some data
x = torch.from_numpy(np.array([4, 2])).float()
y = 2 * x
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
y_hat = model(x) # forward pass
loss = (y - y_hat) ** 2 …
Run Code Online (Sandbox Code Playgroud)