MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / clip

Function clip

imperative/python/megengine/functional/elemwise.py:1041–1082  ·  view source on GitHub ↗

r"""Element-wise clipping function. Clamps(limits) all elements :math:`x_i` of the input tensor :math:`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``.

(x: Tensor, lower=None, upper=None)

Source from the content-addressed store, hash-verified

1039
1040
1041def clip(x: Tensor, lower=None, upper=None) -> Tensor:
1042 r"""Element-wise clipping function.
1043
1044 Clamps(limits) all elements :math:`x_i` of the input tensor :math:`x` into the range ``[ lower, upper ]``.
1045 For example, if a range of ``[0, 1]`` is specified,
1046 values smaller than ``0`` become ``0``, and values larger than ``1`` become ``1``.
1047
1048 .. math::
1049
1050 y_i = \begin{cases}
1051 \text{lower} & \text{if } x_i < \text{lower} \\
1052 x_i & \text{if } \text{lower} \leq x_i \leq \text{upper} \\
1053 \text{upper} & \text{if } x_i > \text{upper}
1054 \end{cases}
1055
1056 Equivalent to ``F.minimum(upper, np.maximum(x, upper))`` right now.
1057
1058 Args:
1059 x: The input tensor.
1060 lower: lower-bound of the range to be clamped to. Should have a numeric data type.
1061 upper: upper-bound of the range to be clamped to. Should have a numeric data type.
1062
1063 Note:
1064 * If both ``lower`` and ``upper`` are None, raises an ``AssertionError``.
1065 * If ``lower`` is None, equivalent to ``F.minimum(x, upper)``.
1066 * If ``upper`` is None, equivalent to ``F.maximum(x, lower)``.
1067 * If ``lower`` is bigger than ```upper``, the result is same as ``clip(Tensor(), upper, upper)``.
1068
1069 Returns:
1070 output clamped tensor. The result must have a data type determined by :ref:`dtype-promotion`.
1071
1072 """
1073 assert (
1074 lower is not None or upper is not None
1075 ), "At least one of 'lower' or 'upper' must not be None"
1076 if lower is not None:
1077 if upper is not None:
1078 return _elwise(x, lower, upper, mode=Elemwise.Mode.CLIP)
1079 else:
1080 return maximum(x, lower)
1081 else:
1082 return minimum(x, upper)
1083
1084
1085# trigonometric functions

Callers 5

normalizeFunction · 0.70
_check_out_dtypeFunction · 0.50
_get_tableMethod · 0.50
relu6Function · 0.50
clip_grad_valueFunction · 0.50

Calls 3

maximumFunction · 0.85
minimumFunction · 0.85
_elwiseFunction · 0.50

Tested by

no test coverage detected