PyTorch how to compute second order Jacobian?

2024/9/21 5:47:38

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.

Would anybody know how to do that in PyTorch? Below, the code snippet from my project:

import torch
import torch.nn as nnclass PINN(torch.nn.Module):def __init__(self, layers:list):super(PINN, self).__init__()self.linears = nn.ModuleList([])for i, dim in enumerate(layers[:-2]):self.linears.append(nn.Linear(dim, layers[i+1]))self.linears.append(nn.ReLU())self.linears.append(nn.Linear(layers[-2], layers[-1]))def forward(self, x):for layer in self.linears:x = layer(x)return x

I then instantiate my network:

n_in = 1
units = 50
q = 500pinn = PINN([n_in, units, units, units, q+1])
pinn

Which returns

PINN((linears): ModuleList((0): Linear(in_features=1, out_features=50, bias=True)(1): ReLU()(2): Linear(in_features=50, out_features=50, bias=True)(3): ReLU()(4): Linear(in_features=50, out_features=50, bias=True)(5): ReLU()(6): Linear(in_features=50, out_features=501, bias=True))
)

Then I compute both FO and SO jacobians

x = torch.randn(1, requires_grad=False)u_x = torch.autograd.functional.jacobian(pinn, x, create_graph=True)
print("First Order Jacobian du/dx of shape {}, and features\n{}".format(u_x.shape, u_x)u_xx = torch.autograd.functional.jacobian(lambda _: u_x, x)
print("Second Order Jacobian du_x/dx of shape {}, and features\n{}".format(u_xx.shape, u_xx)

Returns

First Order Jacobian du/dx of shape torch.Size([501, 1]), and features
tensor([[-0.0310],[ 0.0139],[-0.0081],[-0.0248],[-0.0033],[ 0.0013],[ 0.0040],[ 0.0273],...[-0.0197]], grad_fn=<ViewBackward>)
Second Order Jacobian du/dx of shape torch.Size([501, 1, 1]), and features
tensor([[[0.]],[[0.]],[[0.]],[[0.]],...[[0.]]])

Should not u_xx be a None vector if it didn't depend on x?

Thanks in advance

Answer

The second order Jacobian is known as the Hessian and can be computed easily using PyTorch's builtin functions:

torch.autograd.functional.hessian(func, inputs)
https://en.xdnf.cn/q/72084.html

Related Q&A

Tensorflow setup on RStudio/ R | CentOS

For the last 5 days, I am trying to make Keras/Tensorflow packages work in R. I am using RStudio for installation and have used conda, miniconda, virtualenv but it crashes each time in the end. Install…

Cant import soundfile

Im using Anaconda and Im trying to import soundfile/pysoundfile. I installed the package by running conda install -c conda-forge pysoundfile and I think it succeeded because when I run conda list it sh…

Most efficient way to multiply a small matrix with a scalar in numpy

I have a program whose main performance bottleneck involves multiplying matrices which have one dimension of size 1 and another large dimension, e.g. 1000: large_dimension = 1000a = np.random.random((1…

MultiValueDictKeyError / request.POST

I think I hav a problem at request.POST[title]MultiValueDictKeyError at /blog/add/post/"title"Request Method: GETRequest URL: http://119.81.247.69:8000/blog/add/post/Django Version: 1.8.…

How can I auto run py.test once a relative command has been change?

Via autonose or nosy, it will automatically run the nosetests once the some tests file or the relative files have been changes. I would like to ask that whether py.test provides the similar function fo…

Publish a post using XML-RPC WordPress API and Python with category

Im doing a migration from a website to another one which use Wordpress. I created new custom types for my needs (with the plugin Custom Post Types), and I created categories for each custom type.I then…

Django registration email not sending

Ive been trying to get the django-registration-redux account activation email to send to newly registered users.Ive gotten all non-email related parts to work, such as loggin in/out and actually regist…

NumPy data type comparison

I was playing with comparing data types of two different arrays to pick one that is suitable for combining the two. I was happy to discover that I could perform comparison operations, but in the proces…

A simple method for rotating images in reportlab

How can we easily rotate an image using reportlab? I have not found an easy method. The only way found comes from http://dods.ipsl.jussieu.fr/orchidee/SANORCHIDEE/TEMP/TEMP_LOCAL/cdat_portable/lib_new…

XML header getting removed after processing with elementtree

i have an xml file and i used Elementtree to add a new tag to the xml file.My xml file before processing is as follows <?xml version="1.0" encoding="utf-8"?><PackageInfo …