mindspore.ops.Median

class mindspore.ops.Median(global_median=False, axis=0, keep_dims=False)[source]

Computes the median and its corresponding indices of input tensor in the axis dimension. If global_median is True, computes the median of all elements of tensor.

Warning

  • indices does not necessarily contain the first occurrence of each median value found in the input, unless it is unique. The specific implementation of this API is device-specific. The results may be different on CPU and GPU.

  • When attr global_median is True, the value of the second output tensor indices is meaningless.

Parameters
  • global_median (bool, optional) – Whether the output tensor is the median of all input tensor elements or not. Default: Fasle.

  • axis (int, optional) – The specified dimension to compute median. Default: 0.

  • keep_dims (bool, optional) – Whether the output tensor need to retain axis dimension or not. Default: False.

Inputs:
  • x (Tensor) - A Tensor to calculate median with. Supported dtype:int16, int32, int64, float32 or float64.

Outputs:
  • y (Tensor) - Median, has the same dtype as the x.

    • If global_median is True, the y has only one element.

    • If keep_dims is True, the y has the same shape as the x except the size of y in dimension axis is 1.

    • Otherwise, the y lacks axis dimension than input.

  • indices (Tensor) - Indices, Has the same shape as the y, with dtype int64.

Raises
  • TypeError – If dtype of x is not one of the following: int16, int32, int64, float32, float64.

  • TypeError – If input x is not a Tensor.

  • TypeError – If global_median or keep_dims is assigned a nonboolean value.

  • TypeError – If axis is not int.

  • ValueError – If axis is not in range of [-x.dim, x.dim-1].

Supported Platforms:

GPU CPU

Examples

>>> # case 1 : common median compute
>>> from mindspore import Tensor, ops
>>> import numpy as np
>>> x = Tensor(np.array([[5, 1, 2],[3, 5, 7], [1, 6, 4]]).astype(np.int64))
>>> median = ops.Median(global_median=False, axis=0, keep_dims=False)
>>> y = median(x)
>>> print(y)
(Tensor(shape=[3], dtype=Int64, value= [3, 5, 4]), Tensor(shape=[3], dtype=Int64, value= [1, 1, 2]))
>>> # case 2 : global median compute
>>> from mindspore import Tensor, ops
>>> import numpy as np
>>> x = Tensor(np.array([[1, 7, 6],[5, 1, 3],[9, 17, 1]]).astype(np.int32))
>>> median = ops.Median(global_median=True)
>>> y = median(x)
>>> print(y)
(Tensor(shape=[], dtype=Int32, value= 5), Tensor(shape=[], dtype=Int64, value= 0))