Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.count_nonzero function

PyTorch torch.count_nonzero function


PyTorch torch reference manual PyTorch torch reference manual

torch.count_nonzero is a PyTorch function for returning the number of non-zero elements in a tensor.

Function definition

torch.count_nonzero(input, dim)


Usage examples

Example

import

torch

x

=

torch.

tensor

(

[

1

,

0

,

2

,

0

,

3

,

0

,

0

,

4

]

)

Return the number of non-zero elements

print

(

"Number of non-zero elements:"

,

torch.

count_nonzero

(

x

)

)

Number of non-zero elements along dim=0

y

=

torch.

tensor

(

[

[

1

,

0

,

2

]

,

[

0

,

3

,

0

]

,

[

4

,

0

,

5

]

]

)

print

(

"Number of non-zero elements:"

,

torch.

count_nonzero

(

y

)

)

print

(

"Number of non-zero elements along dim=0:"

,

torch.

count_nonzero

(

y

,

dim

=

0

)

)

print

(

"Number of non-zero elements along dim=1:"

,

torch.

count_nonzero

(

y

,

dim

=

1

)

)

The output is:

非零元素数量: tensor(4)

非零元素数量: tensor(5)

dim=0 非零元素数量: tensor([2, 1, 2])

dim=1 非零元素数量: tensor([2, 1, 2])


PyTorch torch reference manual PyTorch torch reference manual