PyTorch torch.bincount function
PyTorch torch reference manual
torch.bincount is a function in PyTorch used to count the occurrences of each nonnegative integer value. It returns a new 1D tensor in which the i-th element gives the number of times value i appears in the input. It is commonly used for histograms and grouped statistics.
Function definition
torch.bincount(input, weights=None, minlength=0)
Usage examples
Example
import
torch
Basic usage: Count the occurrences of each value
x
=
torch.
tensor
(
[
0
,
1
,
1
,
2
,
2
,
2
,
3
,
3
,
4
]
)
counts
=
torch.
bincount
(
x
)
(
"Input:"
,
x
)
(
"Count result:"
,
counts
)
Output: tensor([1, 2, 3, 2, 1])
Use the weights parameter
x
=
torch.
tensor
(
[
0
,
1
,
1
,
2
,
2
,
2
]
)
weights
=
torch.
tensor
(
[
1.0
,
2.0
,
3.0
,
1.0
,
2.0
,
3.0
]
)
weighted_counts
=
torch.
bincount
(
x
,
weights
=
weights
)
(
"Weighted count:"
,
weighted_counts
)
Output: tensor([1., 5., 6.])
Set the minimum length
x
=
torch.
tensor
(
[
0
]
)
counts
=
torch.
bincount
(
x
,
minlength
=
5
)
(
"Minimum length 5:"
,
counts
)