快捷方式

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 的全面开发者文档

查看文档

教程

获取面向初学者和高级开发者的深度教程

查看教程

资源

查找开发资源并解答问题

查看资源