mindspore.Tensor.clamp

Tensor.clamp(min=None, max=None) Tensor

Clamps tensor values between the specified minimum value and maximum value.

Limits the value of \(self\) to a range, whose lower limit is min and upper limit is max .

\[\begin{split}out_i= \left\{ \begin{array}{align} max & \text{ if } self_i\ge max \\ self_i & \text{ if } min \lt self_i \lt max \\ min & \text{ if } self_i \le min \\ \end{array}\right.\end{split}\]

Note

  • min and max cannot be None at the same time;

  • When min is None and max is not None, the elements in Tensor larger than max will become max;

  • When min is not None and max is None, the elements in Tensor smaller than min will become min;

  • If min is greater than max, the value of all elements in Tensor will be set to max;

  • The data type of self, min and max should support implicit type conversion and cannot be bool type.

Parameters
  • min (Union(Tensor, float, int), optional) – The minimum value. Default: None .

  • max (Union(Tensor, float, int), optional) – The maximum value. Default: None .

Returns

Tensor, a clipped Tensor. The data type and shape are the same as self.

Raises
  • ValueError – If both min and max are None.

  • TypeError – If the type of self is not Tensor.

  • TypeError – If the type of min is not in None, Tensor, float or int.

  • TypeError – If the type of max is not in None, Tensor, float or int.

Supported Platforms:

Ascend GPU CPU

Examples

>>> # case 1: the data type of input is Tensor
>>> import mindspore
>>> from mindspore import Tensor
>>> import numpy as np
>>> min_value = Tensor(5, mindspore.float32)
>>> max_value = Tensor(20, mindspore.float32)
>>> input = Tensor(np.array([[1., 25., 5., 7.], [4., 11., 6., 21.]]), mindspore.float32)
>>> output = input.clamp(min_value, max_value)
>>> print(output)
[[ 5. 20.  5.  7.]
 [ 5. 11.  6. 20.]]
>>> # case 2: the data type of input is number
>>> import mindspore
>>> from mindspore import Tensor
>>> import numpy as np
>>> min_value = 5
>>> max_value = 20
>>> input = Tensor(np.array([[1., 25., 5., 7.], [4., 11., 6., 21.]]), mindspore.float32)
>>> output = input.clamp(min_value, max_value)
>>> print(output)
[[ 5. 20.  5.  7.]
 [ 5. 11.  6. 20.]]