如何在PyTorch中计算给定函数的雅可比矩阵?


 `jacobian()` 函数计算给定函数的雅可比矩阵。`jacobian()` 函数可以从 `torch.autograd.functional` 模块访问。其雅可比矩阵被计算的函数以张量作为输入,并返回一个张量元组或一个张量。`jacobian()` 函数返回一个包含针对具有给定输入的函数计算出的雅可比矩阵值的张量。

语法

torch.autograd.functional.jacobian(func, input)

参数

  • func − 这是计算雅可比矩阵的Python函数。

  • input − 它是函数func的输入。

步骤

我们可以使用以下步骤来计算给定函数的雅可比矩阵:

  • 导入所需的库。在以下所有示例中,所需的Python库是**torch**。请确保您已安装它。

import torch
from torch.autograd.functional import jacobian
  • 定义一个函数**func**,为此函数计算雅可比矩阵。此函数的输入是**input**。

def func(x):
   return x**3 + 4*x -10
  • 为函数**func**定义张量**input**。

input = torch.tensor([2.,3.,4.])
  • 为给定的输入**input**计算上面定义的函数的雅可比矩阵。

output = jacobian(func, input)
  • 打印包含已计算的雅可比矩阵的张量。

print("Jacobians Tensor:
", output)

示例1

# Import the required libraries
import torch
from torch.autograd.functional import jacobian

# define a function
def func(x):
   return x**3 + 4*x -10

# define the inputs
input1 = torch.tensor([2.])
input2 = torch.tensor([2.,3.])
input3 = torch.tensor([2.,3.,4.])

# compute the jacobians
output1 = jacobian(func, input1)
output2 = jacobian(func, input2)
output3 = jacobian(func, input3)

# print the Jacobians calculated above
print("Jacobian Tensor:
", output1) print("Jacobian Tensor:
", output2) print("Jacobian Tensor:
", output3)

输出

Jacobian Tensor:
   tensor([[16.]])
Jacobian Tensor:
   tensor([[16., 0.],
      [ 0., 31.]])
Jacobian Tensor:
   tensor([[16., 0., 0.],
      [ 0., 31., 0.],
      [ 0., 0., 52.]])

在上面的示例中,我们为不同输入的函数计算了雅可比矩阵。

示例2

import torch
from torch.autograd.functional import jacobian

# define a function
def func(x,y):
   return x.pow(3) + y

# here input is tuple of two tensors, one for x and other for y
input1 = (torch.tensor([2.]), torch.tensor([5.]))
input2 = (torch.tensor([2., 3., 4.]), torch.tensor([5., 6., 7.]))

output1 = jacobian(func, input1)
output2 = jacobian(func, input2)

print(output1)
print(output2)

输出

(tensor([[12.]]), tensor([[1.]]))
(tensor([[12., 0., 0.],
   [ 0., 27., 0.],
   [ 0., 0., 48.]]), tensor([[1., 0., 0.],
   [0., 1., 0.],
   [0., 0., 1.]]))

更新于:2022年1月27日

3K+ 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.