megengine.functional.clip

clip(x, lower=None, upper=None)[源代码]

Clamps all elements in input tensor into the range [ lower, upper ] and returns a resulting tensor:

\[\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}\]
参数
  • x (Tensor) – (Tensor): The input tensor.

  • lower – (Numberic,optional): lower-bound of the range to be clamped to.

  • upper – (Numberic,optional): upper-bound of the range to be clamped to.

注解

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

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

返回类型

Tensor

返回

output clamped tensor. The result must have a data type determined by 类型提升规则.

实际案例

>>> import numpy as np
>>> x = Tensor([0,1,2,3,4])
>>> F.clip(x, 2, 4)
Tensor([2 2 2 3 4], dtype=int32, device=xpux:0)
>>> x = Tensor([0,1,2,3,4])
>>> F.clip(x, 4, 3)
Tensor([3 3 3 3 3], dtype=int32, device=xpux:0)
>>> x = F.arange(5)
>>> F.clip(x, lower=3)
Tensor([3. 3. 3. 3. 4.], device=xpux:0)
>>> x = F.arange(5, dtype=np.int32)
>>> F.clip(x, upper=2.1)
Tensor([0.  1.  2.  2.1 2.1], device=xpux:0)