torch.trapezoid¶
- torch.trapezoid(y, x=None, *, dx=None, dim=- 1) Tensor ¶
计算沿
dim
的梯形规则。默认情况下,元素之间的间距假设为 1,但可以使用dx
指定不同的常数间距,并且可以使用x
在dim
上指定任意间距。假设
y
是一个一维张量,其元素为 ,默认计算方式为当指定
dx
时,计算方式变为实际上是将结果乘以
dx
。当指定x
时,假设x
也是一个一维张量,其元素为 ,计算方式变为当
x
和y
具有相同大小时,计算方式如上所述,无需广播。当它们的尺寸不同时,此函数的广播行为如下。对于x
和y
,该函数计算沿维度dim
的相邻元素之间的差值。这实际上创建了两个与原始张量形状相同的张量,x_diff 和 y_diff,除了它们沿维度dim
的长度减少了 1。之后,这两个张量一起广播以计算最终输出,作为梯形法则的一部分。以下示例中提供了详细信息。注意
梯形法则是一种通过平均函数的左端和右端黎曼和来近似定积分的技术。随着分割分辨率的提高,近似值变得越来越准确。
- 参数:
y(张量)- 计算梯形法则时使用的值。
x(张量)- 如果指定,则定义上述值之间的间距。
- 关键字参数:
dx(浮点数)- 值之间的常数间距。如果没有指定
x
或dx
,则默认为 1。实际上将结果乘以其值。dim(整数)- 计算梯形法则的维度。默认为最内层维度。
示例:
>>> # 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.])