如何在 PyTorch 中計算給定標量函式的海森矩陣?


hessian() 函式計算給定函式的海森矩陣。hessian() 函式可以從 torch.autograd.functional 模組訪問。正在計算海森矩陣的函式以張量作為輸入,並返回一個張量元組或一個張量。hessian() 函式返回一個張量,其中包含為具有給定輸入的函式計算的海森矩陣值。

語法

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

引數

  • func − 它是計算海森矩陣的 Python 函式。

  • input − 它是函式 func 的輸入。

步驟

我們可以使用以下步驟來計算給定函式的海森矩陣:

  • 匯入所需的庫。在以下所有示例中,所需的 Python 庫是 torch。確保您已安裝它。

import torch
from torch.autograd.functional import hessian
  • 定義一個函式 func,需要為其計算海森矩陣。此函式的輸入為 input

def func(x):
   return x**3 + 4*x -10
  • 定義函式 func 的張量 input

input = torch.tensor([2.,3.,4.])
  • 計算上面為給定輸入 input 定義的函式的海森矩陣。

output = hessian(func, input)
  • 列印包含計算出的海森矩陣的張量。

print("Hessian Tensor:
", output)

示例 1

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

# define a function
def func(x):
   return x**3 + 4*x -10
input = torch.tensor([2.])
output = hessian(func, input)
print("Hessian Tensor:
",output)

輸出

Hessian Tensor:
   tensor([[12.]])

在上面的示例中,我們計算了給定輸入的函式的海森矩陣。這裡我們使用的函式是單變數函式。

示例 2

# Import the required libraries
import torch
from torch.autograd.functional import hessian
def func(x):
   return (x**3 + 4*x -10).sum()

# apply an input having more than one elements
input = torch.randn(2,2)
output = hessian(func, input)
print(output)

輸出

tensor([[[[-1.4218, -0.0000],
   [ 0.0000, -0.0000]],

   [[-0.0000, -2.7878],
   [ 0.0000, -0.0000]]],

   [[[-0.0000, -0.0000],
   [ 1.9817, -0.0000]],

   [[-0.0000, -0.0000],
   [ 0.0000, -2.8517]]]])

在上面的示例中,我們計算了給定 2×2 輸入張量的函式的海森矩陣。這裡我們使用的函式是單變數函式。

示例 3

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

# define a function
def func(x, y):
   return x**3 + x*y
input = (torch.tensor([2.]),torch.tensor([4.]))
output = hessian(func, input)
print(output)

# to apply multi element tensor as input
def func(x, y):
   return (x**3 + x*y).sum()
input = (torch.tensor([2.,3.]),torch.tensor([4., 5.]))
output = hessian(func, input)
print(output)

輸出

((tensor([[12.]]), tensor([[1.]])), (tensor([[1.]]),
   tensor([[0.]])))
((tensor([[12., 0.],
   [ 0., 18.]]), tensor([[1., 0.],
   [0., 1.]])), (tensor([[1., 0.],
   [0., 1.]]), tensor([[0., 0.],
   [0., 0.]])))

在上面的示例中,我們計算了給定輸入張量的函式的海森矩陣。這裡我們使用的函式是雙變數函式。因此,我們已將輸入定義為兩個張量的元組。

更新於: 2022-01-27

1K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.