mindspore.ops.count_nonzero

mindspore.ops.count_nonzero(x, axis=(), keep_dims=False, dtype=mstype.int32)[source]

Count number of nonzero elements across axis of input tensor.

Parameters
  • x (Tensor) – Input data is used to count non-zero numbers. With shape \((*)\) where \(*\) means, any number of additional dimensions.

  • axis (Union[int, tuple(int), list(int)], optional) – The dimensions to reduce. Default: () , reduce all dimensions.

  • keep_dims (bool, optional) – Whether to maintain dimensions specified by axis. If true, keep these reduced dimensions and the length is 1. If false, don’t keep these dimensions. Default: False .

  • dtype (Union[Number, mindspore.bool_], optional) – The data type of the output tensor. Default: mstype.int32 .

Returns

Tensor, number of nonzero element across axis specified by axis. The data type is specified by dtype.

Raises
  • TypeError – If axis is not int, tuple or list.

  • ValueError – If any value in axis is not in range [-x.ndim, x.ndim).

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor, ops
>>> import numpy as np
>>> import mindspore
>>> # case 1: each value specified.
>>> x = Tensor(np.array([[0, 1, 0], [1, 1, 0]]).astype(np.float32))
>>> nonzero_num = ops.count_nonzero(x=x, axis=[0, 1], keep_dims=True, dtype=mindspore.int32)
>>> print(nonzero_num)
[[3]]
>>> # case 2: all value is default.
>>> nonzero_num = ops.count_nonzero(x=x)
>>> print(nonzero_num)
3
>>> # case 3: axis value was specified 0.
>>> nonzero_num = ops.count_nonzero(x=x, axis=[0,])
>>> print(nonzero_num)
[1 2 0]
>>> # case 4: axis value was specified 1.
>>> nonzero_num = ops.count_nonzero(x=x, axis=[1,])
>>> print(nonzero_num)
[1 2]
>>> # case 5: keep_dims value was specified.
>>> nonzero_num = ops.count_nonzero(x=x,  keep_dims=True)
>>> print(nonzero_num)
[[3]]
>>> # case 6: keep_dims and axis value was specified.
>>> nonzero_num = ops.count_nonzero(x=x, axis=[0,], keep_dims=True)
>>> print(nonzero_num)
[[1 2 0]]