首页 > 解决方案 > 了解 PyTorch 中的反向传播

问题描述

我正在探索 PyTorch,但我不理解以下示例的输出:

# Initialize x, y and z to values 4, -3 and 5
x = torch.tensor(4., requires_grad = True)
y = torch.tensor(-3., requires_grad = True)
z = torch.tensor(5., requires_grad = True)

# Set q to sum of x and y, set f to product of q with z
q = x + y
f = q * z

# Compute the derivatives
f.backward()

# Print the gradients
print("Gradient of x is: " + str(x.grad))
print("Gradient of y is: " + str(y.grad))
print("Gradient of z is: " + str(z.grad))

输出

Gradient of x is: tensor(5.)
Gradient of y is: tensor(5.)
Gradient of z is: tensor(1.)

我毫不怀疑我的困惑源于一个小小的误解。有人可以逐步解释吗?

标签: pythondeep-learningneural-networkpytorchbackpropagation

解决方案


我希望你明白,当你这样做f.backward()时,你得到的x.graddfdx

在你的情况下 。所以,简单地说(使用初步微积分)

如果您输入 x、y 和 z 的值,就可以解释输出。

但是,这并不是真正的“反向传播”算法。这只是偏导数(这是您在问题中提出的所有问题)。

编辑:如果您想了解其背后的反向传播机制,请参阅@Ivan 的回答。


推荐阅读