torch.trapezoid

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

计算梯形规则沿dim维度。默认情况下,假设元素之间的间距为1,但可以通过dx指定不同的常量间距,或者通过x指定沿dim的任意间距。

假设y是一个一维张量,其元素为${y_0, y_1, ..., y_n}$,则默认的计算是

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

当指定 dx 时,计算会变成

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

有效地将结果乘以dx。当指定x时,假设x也是一维张量,其元素为${x_0, x_1, ..., x_n}$,计算变为

$\begin{aligned} \sum_{i = 1}^{n-1} \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) – 如果指定了 x,则定义了值之间的间隔。

关键字参数
  • dx (float) – 值之间的常量间隔。如果未指定 xdx,则默认为 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.])
本页目录