oneflow.clamp

oneflow.clamp()

Clamp all elements in input into the range [ min, max ] and return a resulting tensor:

\[\begin{split}y_i = \begin{cases} \text{min} & \text{if } x_i < \text{min} \\ x_i & \text{if } \text{min} \leq x_i \leq \text{max} \\ \text{max} & \text{if } x_i > \text{max} \end{cases}\end{split}\]

If input is of type FloatTensor or DoubleTensor, args min and max must be real numbers, otherwise they should be integers.

Parameters
  • input (Tensor) – the input tensor.

  • min (Number) – lower-bound of the range to be clamped to. Defaults to None.

  • max (Number) – upper-bound of the range to be clamped to. Defaults to None.

  • out (Tensor, optional) – the output tensor.

For example:

>>> import oneflow as flow
>>> import numpy as np
>>> arr = np.array([0.2, 0.6, -1.5, -0.3])
>>> input = flow.Tensor(arr)
>>> output = flow.clamp(input, min=-0.5, max=0.5)
>>> output
tensor([ 0.2000,  0.5000, -0.5000, -0.3000], dtype=oneflow.float32)

>>> arr = np.array([0.2, 0.6, -1.5, -0.3])
>>> input = flow.Tensor(arr)
>>> output = flow.clamp(input, min=None, max=0.5)
>>> output
tensor([ 0.2000,  0.5000, -1.5000, -0.3000], dtype=oneflow.float32)

>>> arr = np.array([0.2, 0.6, -1.5, -0.3])
>>> input = flow.Tensor(arr)
>>> output = flow.clamp(input, min=-0.5, max=None)
>>> output
tensor([ 0.2000,  0.6000, -0.5000, -0.3000], dtype=oneflow.float32)