mindspore.ops.clamp
- mindspore.ops.clamp(input, min=None, max=None)[source]
Clamps tensor values between the specified minimum value and maximum value.
Limits the value of \(input\) to a range, whose lower limit is min and upper limit is max .
\[\begin{split}out_i= \left\{ \begin{array}{align} max & \text{ if } x_i\ge max \\ x_i & \text{ if } min \lt x_i \lt max \\ min & \text{ if } x_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 input, min and max should support implicit type conversion and cannot be bool type.
- Parameters
input (Union(Tensor, list[Tensor], tuple[Tensor])) – Input data, which type is Tensor or a list or tuple of Tensor. Tensors of arbitrary dimensions are supported.
min (Union(Tensor, float, int), optional) – The minimum value. Default:
None
.max (Union(Tensor, float, int), optional) – The maximum value. Default:
None
.
- Returns
Union(Tensor, tuple[Tensor], list[Tensor]), a clipped Tensor or a tuple or a list of clipped Tensor. The data type and shape are the same as input.
- Raises
ValueError – If both min and max are None.
TypeError – If the type of input is not in Tensor or list[Tensor] or tuple[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, ops >>> 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 = ops.clamp(input, min_value, max_value) >>> print(output) [[ 5. 20. 5. 7.] [ 5. 11. 6. 20.]] >>> # case 2: the data type of input is list[Tensor] >>> min_value = 5 >>> max_value = 20 >>> input_x = Tensor(np.array([[1., 25., 5., 7.], [4., 11., 6., 21.]]), mindspore.float32) >>> input_y = Tensor(np.array([[1., 25., 5., 7.], [4., 11., 6., 21.]]), mindspore.float32) >>> output = ops.clamp([input_x,input_y], min_value, max_value) >>> for out in output: ... print(out) [[ 5. 20. 5. 7.] [ 5. 11. 6. 20.]] [[ 5. 20. 5. 7.] [ 5. 11. 6. 20.]]