如何在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.