megengine.functional.clip¶
- clip(x, lower=None, upper=None)[源代码]¶
将输入张量的所有元素限制在
[ lower, upper ]
区间并返回相应的结果:\[\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): 输入张量。lower – (Numberic,optional): 限制区间的下界。
upper – (Numberic,optional): 限制区间的上界。
注解
如果 lower 和 upper 都是 None, 触发 AssertionError.
如果 lower 大于 upper, 结果和 clip(Tensor(), upper, upper) 相同。
实际案例
>>> 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)