mindspore.Tensor.clip

Tensor.clip(xmin, xmax, dtype=None)[source]

Clips (limits) the values in a Tensor.

Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of \([0, 1]\) is specified, values smaller than 0 become 0, and values larger than 1 become 1.

Note

Currently, clip with xmin=nan or xmax=nan is not supported.

Parameters
  • xmin (Tensor, scalar, None) – Minimum value. If None, clipping is not performed on the lower interval edge. Not more than one of xmin and xmax may be None.

  • xmax (Tensor, scalar, None) – Maximum value. If None, clipping is not performed on the upper interval edge. Not more than one of xmin and xmax may be None. If xmin or xmax are tensors, then xmin, xmax and the given tensor will be broadcasted to match their shapes.

  • dtype (mindspore.dtype, optional) – Overrides the dtype of the output Tensor. Default is None.

Returns

Tensor, a tensor with the elements of the input tensor, but where values < xmin are replaced with xmin, and those > xmax with xmax.

Raises
  • TypeError – If inputs have types not specified above.

  • ValueError – If the shapes of x1 and x2 cannot broadcast, or both xmin and xmax are None.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> x = Tensor([1, 2, 3, -4, 0, 3, 2, 0]).astype("float32")
>>> y = x.clip(0, 2)
>>> print(y)
[1. 2. 2. 0. 0. 2. 2. 0.]
>>> t = Tensor([1, 1, 1, 1, 1, 1, 1, 1])
>>> y = x.clip(t, 2)
>>> print(y)
[1. 2. 2. 1. 1. 2. 2. 1.]