megengine.functional.clip

clip(x, lower=None, upper=None)[source]

Element-wise clipping function.

Clamps(limits) all elements \(x_i\) of the input tensor \(x\) into the range [ lower, upper ]. For example, if a range of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.

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

Equivalent to F.minimum(upper, np.maximum(x, upper)) right now.

Parameters
  • x (Tensor) – The input tensor.

  • lower – lower-bound of the range to be clamped to. Should have a numeric data type.

  • upper – upper-bound of the range to be clamped to. Should have a numeric data type.

Note

  • If both lower and upper are None, raises an AssertionError.

  • If lower is None, equivalent to F.minimum(x, upper).

  • If upper is None, equivalent to F.maximum(x, lower).

  • If lower is bigger than `upper, the result is same as clip(Tensor(), upper, upper).

Return type

Tensor

Returns

output clamped tensor. The result must have a data type determined by Type promotion rules.