Skip to content
This repository has been archived by the owner on Nov 17, 2023. It is now read-only.

[Numpy] Fix np.clip in scalar case #17788

Merged
merged 1 commit into from
Mar 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions python/mxnet/numpy/multiarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -6200,6 +6200,11 @@ def clip(a, a_min, a_max, out=None):
>>> np.clip(a, 3, 6, out=a)
array([3., 3., 3., 3., 4., 5., 6., 6., 6., 6.], dtype=float32)
"""
from numbers import Number
if isinstance(a, Number):
# In case input is a scalar, the computation would fall back to native numpy.
# The value returned would be a python scalar.
return _np.clip(a, a_min, a_max, out=None)
return _mx_nd_np.clip(a, a_min, a_max, out=out)


Expand Down
10 changes: 10 additions & 0 deletions tests/python/unittest/test_numpy_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -3487,6 +3487,16 @@ def __init__(self, a_min=None, a_max=None):

def hybrid_forward(self, F, x):
return x.clip(self._a_min, self._a_max)

# Test scalar case
for _, a_min, a_max, throw_exception in workloads:
a = _np.random.uniform() # A scalar
if throw_exception:
# No need to test the exception case here.
continue
mx_ret = np.clip(a, a_min, a_max)
np_ret = _np.clip(a, a_min, a_max)
assert_almost_equal(mx_ret, np_ret, atol=1e-4, rtol=1e-3, use_broadcast=False)

for shape, a_min, a_max, throw_exception in workloads:
for dtype in dtypes:
Expand Down