torch.bincount
function bincount(input: Tensor, options?: BincountOptions): Tensorfunction bincount(input: Tensor, minlength: number, weights: Tensor, options?: BincountOptions): TensorCount the frequency of each value in an array of non-negative integers.
Computes a histogram for integer values in range [0, max(input)]. Each position in the output contains the number of times that index value appears in the input (optionally weighted). Efficient for small integer datasets and frequency counting.
Commonly used for:
- Histogram computation for integer data
- Frequency tables and value counting
- Building weighted histograms
- Label distribution analysis
- Data validation and sanity checks
- Input tensor must have non-negative integer values only
- Output length = max(max(input) + 1, minlength)
- If all inputs are 0, output is [n] where n = number of zeros
- Weights must have the same shape as input
- Efficient O(n + max(input)) algorithm
- Input values must be in range [0, 2^31-1] for practical use
Parameters
inputTensor- 1D tensor of non-negative integer values (dtype must support integers)
optionsBincountOptionsoptional
Returns
Tensor– 1D tensor of counts/weights, where output[i] = number of times i appears in input (or sum of weights where input == i if weights provided)Examples
// Basic frequency counting
const x = torch.tensor([1, 2, 1, 0, 3, 1]);
torch.bincount(x); // [1, 3, 1, 1] - count of 0, 1, 2, 3
// With minimum length (padding)
const x = torch.tensor([0, 1, 2]);
torch.bincount(x, 5); // [1, 1, 1, 0, 0] - padded to length 5
// Weighted histogram (soft assignments)
const x = torch.tensor([0, 1, 1, 2]);
const w = torch.tensor([0.5, 1.0, 2.0, 1.5]);
torch.bincount(x, 0, w); // [0.5, 3.0, 1.5] - weighted counts
// Label distribution in classification
const labels = torch.tensor([0, 1, 1, 2, 0, 1, 0]); // Class labels
const distribution = torch.bincount(labels); // [3, 3, 1] - count per class
const weights = distribution / labels.shape[0]; // [3/7, 3/7, 1/7] - class weightsSee Also
- PyTorch torch.bincount()
- histogram - Continuous histogram with float bin edges
- histc - Histogram with specified bin range and count
- unique - Get unique elements and their counts
- searchsorted - Binary search for binning continuous values