mindspore.ops.diff

View Source On Gitee
mindspore.ops.diff(x, n=1, axis=- 1, prepend=None, append=None)[source]

Computes the n-th forward difference along the given axis.

The first-order differences is calculated as \(out[i] = x[i+1] - x[i]\) . Higher-order differences are calculated by using mindspore.ops.diff() recursively.

Note

Zero-shaped Tensor is not supported, a value error is raised if an empty Tensor is encountered. Any dimension of a Tensor is 0, which is considered an empty Tensor. Tensor with shape of \((0,)\), \((1, 2, 0, 4)\) are all empty Tensor.

Parameters
  • x (Tensor) – The input tensor.

  • n (int, optional) – The number of times to compute the difference. Currently only 1 is supported. Default 1 .

  • axis (int, optional) – The axis to compute the difference along. Default -1 .

  • prepend (Tensor, optional) – Values to prepend to x along axis before performing the difference. Their dimensions must be equivalent to that of x, and their shapes must match input's shape except on dim. Default None .

  • append (Tensor, optional) – Values to append to x along axis before performing the difference. Their dimensions must be equivalent to that of x, and their shapes must match input's shape except on dim. Default None .

Returns

Tensor, the n-th differences of input. The shape of the output is the same as x except along axis where the size is reduced by n. The type of the output is the same as x.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore
>>> x = mindspore.tensor([1, 3, 2])
>>> # case 1: By default, compute the first-order differences along axis -1.
>>> mindspore.ops.diff(x)
Tensor(shape=[2], dtype=Int64, value= [ 2, -1])
>>>
>>> # case 2: When argument prepend is setting:
>>> n = mindspore.tensor([4, 5])
>>> mindspore.ops.diff(x, prepend=n)
Tensor(shape=[4], dtype=Int64, value= [ 1, -4,  2, -1])
>>>
>>> # case 3: When argument append is setting:
>>> mindspore.ops.diff(x, append=n)
Tensor(shape=[4], dtype=Int64, value= [ 2, -1,  2,  1])
>>>
>>> # case 4: When input is 2-D dimensional tensor, compute forward difference along different axis.
>>> x = mindspore.tensor([[1, 2, 3], [3, 4, 5]])
>>> mindspore.ops.diff(x, axis=0)
Tensor(shape=[1, 3], dtype=Int64, value=
[[2, 2, 2]])
>>> mindspore.ops.diff(x, axis=1)
Tensor(shape=[2, 2], dtype=Int64, value=
[[1, 1],
 [1, 1]])