快捷方式

torch.trapezoid

torch.trapezoid(y, x=None, *, dx=None, dim=-1) Tensor

沿 dim 計算梯形法則。預設情況下,元素之間的間距假定為 1,但可以使用 dx 指定不同的常數間距,並可以使用 x 指定沿 dim 的任意間距。

假設 y 是一個一維張量,其元素為 y0,y1,...,yn{y_0, y_1, ..., y_n},則預設計算方式為

i=1n12(yi+yi1)\begin{aligned} \sum_{i = 1}^{n} \frac{1}{2} (y_i + y_{i-1}) \end{aligned}

當指定 dx 時,計算方式變為

i=1nΔx2(yi+yi1)\begin{aligned} \sum_{i = 1}^{n} \frac{\Delta x}{2} (y_i + y_{i-1}) \end{aligned}

有效地將結果乘以 dx。當指定 x 時,假設 x 也是一個一維張量,其元素為 x0,x1,...,xn{x_0, x_1, ..., x_n},則計算方式變為

i=1n(xixi1)2(yi+yi1)\begin{aligned} \sum_{i = 1}^{n} \frac{(x_i - x_{i-1})}{2} (y_i + y_{i-1}) \end{aligned}

xy 具有相同尺寸時,計算方式如上所述,並且不需要廣播。當它們的尺寸不同時,此函式的廣播行為如下所示。對於 xy,該函式都會計算沿維度 dim 的相鄰元素之間的差值。這有效地建立了兩個張量 x_diffy_diff,它們的形狀與原始張量相同,只是沿維度 dim 的長度減少了 1。之後,這兩個張量會被廣播在一起,作為梯形法則計算的一部分,以計算最終輸出。詳情請參閱下面的示例。

注意

梯形法則是透過平均函式的左右黎曼和來近似計算函式定積分的一種技術。隨著分割槽的解析度增加,近似結果會變得更準確。

引數
  • y (Tensor) – 計算梯形法則時使用的值。

  • x (Tensor) – 如果指定,則定義如上所述的值之間的間距。

關鍵字引數
  • dx (float) – 值之間的常數間距。如果既未指定 x 也未指定 dx,則預設值為 1。有效地將結果乘以其值。

  • dim (int) – 沿其計算梯形法則的維度。預設情況下是最後一個(最內層)維度。

示例

>>> # Computes the trapezoidal rule in 1D, spacing is implicitly 1
>>> y = torch.tensor([1, 5, 10])
>>> torch.trapezoid(y)
tensor(10.5)

>>> # Computes the same trapezoidal rule directly to verify
>>> (1 + 10 + 10) / 2
10.5

>>> # Computes the trapezoidal rule in 1D with constant spacing of 2
>>> # NOTE: the result is the same as before, but multiplied by 2
>>> torch.trapezoid(y, dx=2)
21.0

>>> # Computes the trapezoidal rule in 1D with arbitrary spacing
>>> x = torch.tensor([1, 3, 6])
>>> torch.trapezoid(y, x)
28.5

>>> # Computes the same trapezoidal rule directly to verify
>>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2
28.5

>>> # Computes the trapezoidal rule for each row of a 3x3 matrix
>>> y = torch.arange(9).reshape(3, 3)
tensor([[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]])
>>> torch.trapezoid(y)
tensor([ 2., 8., 14.])

>>> # Computes the trapezoidal rule for each column of the matrix
>>> torch.trapezoid(y, dim=0)
tensor([ 6., 8., 10.])

>>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix
>>> #   with the same arbitrary spacing
>>> y = torch.ones(3, 3)
>>> x = torch.tensor([1, 3, 6])
>>> torch.trapezoid(y, x)
array([5., 5., 5.])

>>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix
>>> #   with different arbitrary spacing per row
>>> y = torch.ones(3, 3)
>>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]])
>>> torch.trapezoid(y, x)
array([2., 4., 6.])

文件

訪問 PyTorch 的全面開發者文件

檢視文件

教程

獲取面向初學者和高階開發者的深度教程

檢視教程

資源

查詢開發資源並解答問題

檢視資源