【发布时间】:2019-07-01 02:42:58
【问题描述】:
使用 PyTorch,我想计算 Hessian 向量积,其中 Hessian 是某个神经网络损失函数的二阶导数矩阵,该向量将是该损失函数的梯度向量。
感谢this post,我知道如何计算常规函数的 Hessian 矢量积。但是,当函数是神经网络的损失函数时,我遇到了麻烦。这是因为参数被打包到一个模块中,可以通过 nn.parameters() 访问,而不是 Torch 张量。
我想做这样的事情(不起作用):
### a simple neural network
linear = nn.Linear(10, 20)
x = torch.randn(1, 10)
y = linear(x).sum()
### compute the gradient and make a copy that is detached from the graph
grad = torch.autograd.grad(y, linear.parameters(),create_graph=True)
v = grad.clone().detach()
### compute the Hessian vector product
z = grad @ v
z.backward()
类比这个(确实有效):
x = Variable(torch.Tensor([1, 1]), requires_grad=True)
f = 3*x[0]**2 + 4*x[0]*x[1] + x[1]**2
grad, = torch.autograd.grad(f, x, create_graph=True)
v = grad.clone().detach()
z = grad @ v
z.backward()
This post 解决了类似(可能相同?)的问题,但我不明白解决方案。
【问题讨论】:
-
澄清一下,你想计算网络中每组权重的粗麻布吗?在这种情况下,您的模型有两组权重:权重矩阵
w和偏置向量b。 -
正确 - 我希望能够将导数 wtf 导出到 w 和 b 中参数的展开向量(称为 Theta)。
标签: pytorch