【发布时间】:2020-07-19 17:17:33
【问题描述】:
以下代码旨在解释 PyTorch 梯度计算的工作原理,IMO 应该返回权重矩阵,但它没有:
# the code calculates T x W + B ---> K1
# compute the mean of K1 --> km
# compute the gradient of km relative to T
#
import torch
torch.manual_seed(0)
t = torch.rand(2,3)
w = torch.rand(3,4)
b = torch.rand(1,4)
#
k1 = torch.mm(t, w) + b
#
#torch.set_grad_enabled(True)
print('k1_grad_fn ',k1.grad_fn)
#
print('t grad ',t.grad)
#
#
km = k1.mean()
km.requires_grad_(True)
print('k1 mean=',km)
km.backward()
print('t grad ',t.grad)
print('k1 grad ',k1.grad_fn)
结果是:
t grad None
k1 mean= tensor(1.0396, requires_grad=True)
t grad None
k1 grad None```
【问题讨论】:
标签: python pytorch gradient matrix-multiplication autograd