当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python PyTorch cumulative_trapezoid用法及代码示例


本文简要介绍python语言中 torch.cumulative_trapezoid 的用法。

用法:

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

参数

  • y(Tensor) -计算梯形规则时使用的值。

  • x(Tensor) -如果指定,则定义上面指定的值之间的间距。

关键字参数

  • dx(float) -值之间的恒定间距。如果 xdx 均未指定,则默认为 1。有效地将结果乘以其值。

  • dim(int) -计算梯形规则的维度。默认情况下最后一个(最里面的)维度。

沿着 dim 累积计算 trapezoidal rule 。默认情况下,元素之间的间距假定为 1,但 dx 可用于指定不同的常量间距,并且 x 可用于指定沿 dim 的任意间距。

更多详情,请阅读 torch.trapezoid() torch.trapezoid() 与此函数之间的区别在于, torch.trapezoid() 为每个积分返回一个值,而此函数为积分中的每个间距返回一个累积值。这类似于.sum 如何返回一个值,而.cumsum 返回一个累积和。

例子:

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

>>> # Computes the same trapezoidal rule directly up to each element to verify
>>> (1 + 5) / 2
3.0
>>> (1 + 10 + 10) / 2
10.5

>>> # Cumulatively computes the trapezoidal rule in 1D with constant spacing of 2
>>> # NOTE: the result is the same as before, but multiplied by 2
>>> torch.cumulative_trapezoid(y, dx=2)
tensor([6., 21.])

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

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

>>> # Cumulatively 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.cumulative_trapezoid(y)
tensor([[ 0.5,  2.],
        [ 3.5,  8.],
        [ 6.5, 14.]])

>>> # Cumulatively computes the trapezoidal rule for each column of the matrix
>>> torch.cumulative_trapezoid(y, dim=0)
tensor([[ 1.5,  2.5,  3.5],
        [ 6.0,  8.0, 10.0]])

>>> # Cumulatively 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.cumulative_trapezoid(y, x)
tensor([[2., 5.],
        [2., 5.],
        [2., 5.]])

>>> # Cumulatively 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.cumulative_trapezoid(y, x)
tensor([[1., 2.],
        [2., 4.],
        [3., 6.]])

相关用法


注:本文由纯净天空筛选整理自pytorch.org大神的英文原创作品 torch.cumulative_trapezoid。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。