我有一个计算向量的神经网络u。我想计算关于 input 的x一阶和二阶雅可比,单个元素。
有人知道如何在 PyTorch 中做到这一点吗?下面是我项目中的代码片段:
import torch
import torch.nn as nn
class 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
Run Code Online (Sandbox Code Playgroud)
然后我实例化我的网络:
n_in = 1
units = 50
q = 500
pinn = PINN([n_in, units, units, units, q+1])
pinn
Run Code Online (Sandbox Code Playgroud)
哪个返回
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) …Run Code Online (Sandbox Code Playgroud)