捷徑

torch.autograd.functional.jacobian

torch.autograd.functional.jacobian(func, inputs, create_graph=False, strict=False, vectorize=False, strategy='reverse-mode')[來源][來源]

計算給定函式的 Jacobian 矩陣。

參數
  • func (function) – 一個 Python 函式,它接受 Tensor 輸入並傳回 Tensor 的 tuple 或 Tensor。

  • inputs (Tensorstuple Tensor) – 傳遞給函式 func 的輸入。

  • create_graph (bool, optional) – 如果為 True,則 Jacobian 將以可微分的方式計算。 請注意,當 strictFalse 時,結果可能不需要梯度或與輸入斷開連接。 預設值為 False

  • strict (bool, optional) – 如果為 True,當我們檢測到存在一個輸入,使得所有輸出都獨立於它時,將會引發錯誤。 如果為 False,我們會回傳一個零 Tensor 作為該輸入的 Jacobian,這是預期的數學值。 預設值為 False

  • vectorize (bool, optional) – 此功能為實驗性質。 如果您正在尋找較不具實驗性且效能更高的東西,請考慮使用 torch.func.jacrev()torch.func.jacfwd()。 在計算 Jacobian 時,通常我們會對 Jacobian 的每一列調用一次 autograd.grad。 如果此標誌為 True,我們只執行一次帶有 batched_grad=Trueautograd.grad 調用,它使用 vmap 原型功能。 雖然這在許多情況下應該可以提高效能,但由於此功能仍處於實驗階段,因此可能存在效能瓶頸。 有關更多資訊,請參閱 torch.autograd.grad()batched_grad 參數。

  • strategy (str, optional) – 設定為 "forward-mode""reverse-mode" 以確定 Jacobian 將使用前向或反向模式 AD 計算。 目前,"forward-mode" 需要 vectorized=True。 預設值為 "reverse-mode"。 如果 func 的輸出多於輸入,則 "forward-mode" 往往具有更高的效能。 否則,建議使用 "reverse-mode"

回傳

如果只有單個輸入和輸出,這將是一個包含線性化輸入和輸出的 Jacobian 的單個 Tensor。 如果其中一個是 tuple,則 Jacobian 將是一個 Tensors 的 tuple。 如果兩者都是 tuple,則 Jacobian 將是一個 Tensors 的 tuple 的 tuple,其中 Jacobian[i][j] 將包含第 i 個輸出和第 j 個輸入的 Jacobian,並且其大小將為相應輸出和相應輸入的大小的串聯,並且將具有與相應輸入相同的 dtype 和裝置。 如果策略是 forward-mode,則 dtype 將是輸出的 dtype;否則,為輸入的 dtype。

回傳型別

Jacobian (Tensor 或巢狀 Tensors tuple)

範例

>>> def exp_reducer(x):
...     return x.exp().sum(dim=1)
>>> inputs = torch.rand(2, 2)
>>> jacobian(exp_reducer, inputs)
tensor([[[1.4917, 2.4352],
         [0.0000, 0.0000]],
        [[0.0000, 0.0000],
         [2.4369, 2.3799]]])
>>> jacobian(exp_reducer, inputs, create_graph=True)
tensor([[[1.4917, 2.4352],
         [0.0000, 0.0000]],
        [[0.0000, 0.0000],
         [2.4369, 2.3799]]], grad_fn=<ViewBackward>)
>>> def exp_adder(x, y):
...     return 2 * x.exp() + 3 * y
>>> inputs = (torch.rand(2), torch.rand(2))
>>> jacobian(exp_adder, inputs)
(tensor([[2.8052, 0.0000],
        [0.0000, 3.3963]]),
 tensor([[3., 0.],
         [0., 3.]]))

文件

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources