mindspore.ops.count_nonzero
- mindspore.ops.count_nonzero(x, axis=(), keep_dims=False, dtype=mstype.int32)[源代码]
计算输入Tensor指定轴上的非零元素的数量。
- 参数:
x (Tensor) - 输入数据用于统计非零元素。 \((N,*)\) ,其中 \(*\) 表示任意数量的附加维度。
axis (Union[int, tuple(int), list(int)]) - 指定计算的维度。只允许为常量。默认值:(),在所有维度进行计算。
keep_dims (bool) - 如果为True,则保留计算的维度,且长度为1。如果为False,则不要保留这些维度。默认值:False。
dtype (Union[Number, mindspore.bool_]) - 输出Tensor的数据类型。只允许为常量。默认值:mindspore.int32。
- 返回:
Tensor,非零元素的数量。数据类型由 dtype 所指定。
- 异常:
TypeError - axis 不是int、tuple或者list。
ValueError - axis 不在[-x.ndim, x.ndim)范围内。
- 支持平台:
Ascend
GPU
CPU
样例:
>>> from mindspore import Tensor, ops >>> import numpy as np >>> # 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]]