python - 了解 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.)
我毫不怀疑我的困惑源于一个小小的误解。有人可以逐步解释吗?
解决方案
我希望你明白,当你这样做f.backward()
时,你得到的x.grad
是。
在你的情况下 。所以,简单地说(使用初步微积分)
如果您输入 x、y 和 z 的值,就可以解释输出。
但是,这并不是真正的“反向传播”算法。这只是偏导数(这是您在问题中提出的所有问题)。
编辑:如果您想了解其背后的反向传播机制,请参阅@Ivan 的回答。
推荐阅读
- python - 从图像中提取和保存字符
- python - 如何从这个“元音食者”中删除字母?
- microsoft-graph-api - 使用 Graph API 向 Teams 中的特定用户发送消息
- python - 使用 Jetson.utils.cudaFont.OverlayText() 函数时,如何处理非典型英语的字母?
- azure-ad-b2c - 如果以前的配置文件抛出错误,验证配置文件仍会执行
- xml - 获取 XML 子节点并设置新的 ID 值
- authentication - 在 ASP.NET Core 中,是否可以在授权中使用枚举作为策略 RequireRole?
- sql - 将多条记录合并为一个人拥有的一条记录?
- webpack - WebPack 加载器 addDependency 是否将文件添加到包中?
- linux - Docker Swarm覆盖网络 - 容器无法通信