PyTorch 中的神经网络、损失和优化器如何连接?

How are neural networks, loss and optimizer connected in PyTorch?

的答案我都看过了,但还是完全没看懂。据我所知,这是最基本的设置:

net = CustomClassInheritingFromModuleWithDefinedInitAndForward()
criterion = nn.SomeLossClass()
optimizer = optim.SomeOptimizer(net.parameters(), ...)
for _, data in enumerate(trainloader, 0):
    inputs, labels = data
    optimizer.zero_grad()
    outputs = net(inputs)
    loss = criterion(outputs, labels)
    loss.backward()
    optimizer.step()

我不明白的是:

优化器使用 net.parameters() 初始化,我认为这是网络的内部权重。

Loss 不会访问这些参数,也不会访问网络本身。它只能访问网络的输出和输入标签。

优化器也不访问损失。

所以如果 loss 只作用于输出而优化器只作用于 net.parameters,它们如何连接?

Optimizer is initialized with net.parameters(), which I thought are internal weights of the net.

这是因为优化器会在训练过程中修改你的网络参数。

Loss does not access these parameters nor the net itself. It only has access to net's outputs and input labels.

损失仅计算预测与事实之间的误差。

Optimizer does not access loss either.

它访问在 loss.backward

期间计算的张量