mindspore.ops.count_nonzero
- mindspore.ops.count_nonzero(x, axis=(), keep_dims=False, dtype=mstype.int32)[source]
Counts the number of non-zero values in the input tensor along the given axis. If no axis is specified then all non-zeros in the tensor are counted.
- Parameters
x (Tensor) – The input tensor.
axis (Union[int, tuple(int), list(int)], optional) – Specify the axis for computation. Default
()
, which counts all non-zero elements.keep_dims (bool, optional) – Whether to maintain dimensions specified by axis. Default
False
, don't keep these dimensions.dtype (Union[Number, mindspore.bool], optional) – The data type returned. Default
mstype.int32
.
- Returns
Tensor
- Supported Platforms:
Ascend
GPU
CPU
Examples
>>> import mindspore >>> # case 1: each value specified. >>> x = mindspore.tensor([[0, 1, 0], [1, 1, 0]], mindspore.float32) >>> nonzero_num = mindspore.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 = mindspore.ops.count_nonzero(x=x) >>> print(nonzero_num) 3 >>> # case 3: axis value was specified 0. >>> nonzero_num = mindspore.ops.count_nonzero(x=x, axis=[0,]) >>> print(nonzero_num) [1 2 0] >>> # case 4: axis value was specified 1. >>> nonzero_num = mindspore.ops.count_nonzero(x=x, axis=[1,]) >>> print(nonzero_num) [1 2] >>> # case 5: keep_dims value was specified. >>> nonzero_num = mindspore.ops.count_nonzero(x=x, keep_dims=True) >>> print(nonzero_num) [[3]] >>> # case 6: keep_dims and axis value was specified. >>> nonzero_num = mindspore.ops.count_nonzero(x=x, axis=[0,], keep_dims=True) >>> print(nonzero_num) [[1 2 0]]