PyTorch how to compute second order Jacobian?(PyTorch 如何计算二阶雅可比行列式?)
问题描述
我有一个计算向量的神经网络u
.我想计算关于输入 x
(单个元素)的一阶和二阶雅可比.
I have a neural network that's computing a vector quantity u
. I'd like to compute first and second-order jacobians with respect to the input x
, a single element.
有人知道如何在 PyTorch 中做到这一点吗?下面是我项目中的代码片段:
Would anybody know how to do that in PyTorch? Below, the code snippet from my project:
然后我实例化我的网络:
I then instantiate my network:
哪个返回
然后我计算 FO 和 SO jacobians
Then I compute both FO and SO jacobians
退货
如果u_xx
不依赖于x
,它不应该是一个None
向量吗?
Should not u_xx
be a None
vector if it didn't depend on x
?
提前致谢
推荐答案
所以正如@jodag 在他的评论中提到的,ReLU
为空或线性,它的梯度是恒定的(除了在 0
,这是一个罕见的事件),所以它的二阶导数为零.我将激活函数更改为 Tanh
,这最终允许我计算两次雅可比.
So as @jodag mentioned in his comment, ReLU
being null or linear, its gradient is constant (except on 0
, which is a rare event), so its second-order derivative is zero. I changed the activation function to Tanh
, which finally allows me to compute the jacobian twice.
最终代码是
然后在 PINN
的实例上调用 compute_u_xx(x)
并将 x.require_grad
设置为 True
得到我在那里.如何摆脱 torch.autograd.functional.jacobian
引入的无用维度仍有待理解...
Then calling compute_u_xx(x)
on an instance of PINN
with x.require_grad
set to True
gets me there. How to get rid of useless dimensions introduced by torch.autograd.functional.jacobian
remains to be understood though...
这篇关于PyTorch 如何计算二阶雅可比行列式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!