torch.trapezoid#
- torch.trapezoid(y, x=None, *, dx=None, dim=-1) Tensor#
沿
dim計算梯形法則。預設情況下,元素之間的間隔假定為 1,但可以使用dx指定不同的恆定間隔,也可以使用x指定沿dim的任意間隔。應只指定x或dx中的一個。假設
y是一個一維張量,其元素為 , 預設計算為當指定
dx時,計算變為有效地將結果乘以
dx。當指定x時,假設x也是一個一維張量,其元素為 , 計算變為當
x和y的大小相同時,計算如上所述,無需廣播。當它們的大小不同時,此函式的廣播行為如下。對於x和y,函式會計算沿dim維度的連續元素之間的差值。這會有效地建立兩個張量 x_diff 和 y_diff,它們的形狀與原始張量相同,只是沿dim維度的長度減少了 1。之後,將這兩個張量一起廣播,以計算梯形法則的最終輸出。有關詳細資訊,請參閱下面的示例。注意
梯形法則是透過平均黎曼和的左側和右側來近似函式定積分的技術。隨著劃分解析度的增加,近似值會變得更準確。
- 引數
- 關鍵字引數
示例
>>> # 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.])