mygrad.clip#

mygrad.clip(a: ArrayLike, a_min: Optional[ArrayLike], a_max: Optional[ArrayLike], out: Optional[Union[Tensor, ndarray]] = None, *, constant: Optional[bool] = None) Tensor[source]#

Clip (limit) the values in an array.

Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.

Equivalent to mg.minimum(a_max, mg.maximum(a, a_min))`.

No check is performed to ensure a_min < a_max.

This docstring was adapted from that of numpy.clip

Parameters
aArrayLike

Array containing elements to clip.

a_minOptional[float, ArrayLike]

Minimum value. If None, clipping is not performed on lower interval edge. Not more than one of a_min and a_max may be None.

a_maxOptional[float, ArrayLike]

Maximum value. If None, clipping is not performed on upper interval edge. Not more than one of a_min and a_max may be None. If a_min or a_max are ArrayLike, then the three arrays will be broadcasted to match their shapes.

outOptional[Union[ndarray, Tensor]]

A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated tensor is returned.

constantbool, optional(default=False)

If True, the returned tensor is a constant (it does not backpropagate a gradient)

Returns
Tensor

A tensor with the elements of a, but where values < a_min are replaced with a_min, and those > a_max with a_max.

Examples

>>> import mygrad as mg
>>> a = mg.arange(10)
>>> mg.clip(a, 1, 8)
Tensor([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
>>> a
Tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> mg.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
Tensor([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])