count_nonzero

paddle. count_nonzero ( x, axis=None, keepdim=False, name=None ) [source]

Counts the number of non-zero values in the tensor x along the specified axis.

Parameters
  • x (Tensor) – An N-D Tensor, the data type is bool, float16, float32, float64, int32 or int64.

  • axis (int|list|tuple, optional) – The dimensions along which the sum is performed. If None, sum all elements of x and return a Tensor with a single element, otherwise must be in the range \([-rank(x), rank(x))\). If \(axis[i] < 0\), the dimension to reduce is \(rank + axis[i]\).

  • keepdim (bool, optional) – Whether to reserve the reduced dimension in the output Tensor. The result Tensor will have one fewer dimension than the x unless keepdim is true, default value is False.

  • name (str, optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Returns

Results of count operation on the specified axis of input Tensor x, it’s data type is ‘int64’.

Return type

Tensor

Examples

>>> import paddle
>>> # x is a 2-D Tensor:
>>> x = paddle.to_tensor([[0., 1.1, 1.2], [0., 0., 1.3], [0., 0., 0.]])
>>> out1 = paddle.count_nonzero(x)
>>> out1
Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
3)
>>> out2 = paddle.count_nonzero(x, axis=0)
>>> out2
Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
[0, 1, 2])
>>> out3 = paddle.count_nonzero(x, axis=0, keepdim=True)
>>> out3
Tensor(shape=[1, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[0, 1, 2]])
>>> out4 = paddle.count_nonzero(x, axis=1)
>>> out4
Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
[2, 1, 0])
>>> out5 = paddle.count_nonzero(x, axis=1, keepdim=True)
>>> out5
Tensor(shape=[3, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
[[2],
 [1],
 [0]])

>>> # y is a 3-D Tensor:
>>> y = paddle.to_tensor([[[0., 1.1, 1.2], [0., 0., 1.3], [0., 0., 0.]],
...                         [[0., 2.5, 2.6], [0., 0., 2.4], [2.1, 2.2, 2.3]]])
>>> out6 = paddle.count_nonzero(y, axis=[1, 2])
>>> out6
Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True,
[3, 6])
>>> out7 = paddle.count_nonzero(y, axis=[0, 1])
>>> out7
Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
[1, 3, 5])