add median op (#2705)
This commit is contained in:
@@ -2484,6 +2484,35 @@ void init_ops(nb::module_& m) {
|
||||
Returns:
|
||||
array: The output array of means.
|
||||
)pbdoc");
|
||||
m.def(
|
||||
"median",
|
||||
[](const mx::array& a,
|
||||
const IntOrVec& axis,
|
||||
bool keepdims,
|
||||
mx::StreamOrDevice s) {
|
||||
return mx::median(a, get_reduce_axes(axis, a.ndim()), keepdims, s);
|
||||
},
|
||||
nb::arg(),
|
||||
"axis"_a = nb::none(),
|
||||
"keepdims"_a = false,
|
||||
nb::kw_only(),
|
||||
"stream"_a = nb::none(),
|
||||
nb::sig(
|
||||
"def median(a: array, /, axis: Union[None, int, Sequence[int]] = None, keepdims: bool = False, *, stream: Union[None, Stream, Device] = None) -> array"),
|
||||
R"pbdoc(
|
||||
Compute the median(s) over the given axes.
|
||||
|
||||
Args:
|
||||
a (array): Input array.
|
||||
axis (int or list(int), optional): Optional axis or
|
||||
axes to reduce over. If unspecified this defaults
|
||||
to reducing over the entire array.
|
||||
keepdims (bool, optional): Keep reduced axes as
|
||||
singleton dimensions, defaults to `False`.
|
||||
|
||||
Returns:
|
||||
array: The output array of medians.
|
||||
)pbdoc");
|
||||
m.def(
|
||||
"var",
|
||||
[](const mx::array& a,
|
||||
|
||||
@@ -775,6 +775,39 @@ class TestOps(mlx_tests.MLXTestCase):
|
||||
self.assertEqual(mx.mean(x, axis=0).tolist(), [2, 3])
|
||||
self.assertEqual(mx.mean(x, axis=1).tolist(), [1.5, 3.5])
|
||||
|
||||
def test_median(self):
|
||||
x = mx.array([])
|
||||
with self.assertRaises(ValueError):
|
||||
mx.median(x, axis=0)
|
||||
x = mx.array([0, 1, 2, 3, 4])
|
||||
with self.assertRaises(ValueError):
|
||||
mx.median(x, axis=(0, 1))
|
||||
with self.assertRaises(ValueError):
|
||||
mx.median(x, axis=(0, 0))
|
||||
|
||||
out = mx.median(x)
|
||||
self.assertEqual(out.shape, ())
|
||||
self.assertEqual(out.item(), 2)
|
||||
out = mx.median(x, keepdims=True)
|
||||
self.assertEqual(out.shape, (1,))
|
||||
|
||||
x = mx.array([0, 1, 2, 3, 4, 5])
|
||||
out = mx.median(x)
|
||||
self.assertEqual(out.item(), 2.5)
|
||||
|
||||
x = mx.random.normal((5, 5, 5, 5))
|
||||
out = mx.median(x, axis=(0, 2), keepdims=True)
|
||||
out_np = np.median(x, axis=(0, 2), keepdims=True)
|
||||
self.assertTrue(np.allclose(out, out_np))
|
||||
|
||||
out = mx.median(x, axis=(1, 3), keepdims=True)
|
||||
out_np = np.median(x, axis=(1, 3), keepdims=True)
|
||||
self.assertTrue(np.allclose(out, out_np))
|
||||
|
||||
out = mx.median(x, axis=(0, 1, 3), keepdims=True)
|
||||
out_np = np.median(x, axis=(0, 1, 3), keepdims=True)
|
||||
self.assertTrue(np.allclose(out, out_np))
|
||||
|
||||
def test_var(self):
|
||||
x = mx.array(
|
||||
[
|
||||
|
||||
Reference in New Issue
Block a user