ML Foundations
Count sparse and negative label IDs with NumPy
Keep the observed label IDs next to their counts when class IDs are negative or far apart.

Evidence and testing
Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.
The position in a bincount is the ID
NumPy bincount counts occurrences of nonnegative integer inputs. Its output uses the integer value itself as an index, and its length is at least one greater than the largest input. Missing IDs within that range have zero counts. Negative IDs are not accepted. [1]
This is convenient for a compact set of nonnegative class IDs. For sparse IDs with a very large maximum, however, the result still spans the range up to that maximum. A sentinel such as negative one also needs an explicit policy before calling bincount.
References: [1]
Count observed IDs and preserve the mapping
Run python examples/numpy_sparse_label_counts.py. The fixture contains a negative sentinel, a small ID and a much larger ID. It shows that bincount rejects the negative input. NumPy unique with return_counts then returns the sorted observed values and the count associated with each value. [1, 2]
The result pairs negative one with two occurrences, seven with one, and one million with two. Keep both returned arrays together: the count at position zero belongs to the first returned ID, not necessarily class zero. Assertions check the exact mapping for this finite integer fixture.
Whether the negative sentinel should be counted as a class or excluded depends on the application. If it means missing or ignored, filter it before counting and separately report how many records were excluded.
Executed with Python 3.12.14 and NumPy 2.3.5; stdout and checksum are in private evidence.
import numpy as np
labels = np.array([1000000, -1, 7, 1000000, -1])
try:
np.bincount(labels)
except ValueError:
print('bincount rejects negative IDs')
values, counts = np.unique(labels, return_counts=True)
print('label IDs:', values.tolist())
print('counts:', counts.tolist())
print('pairs:', list(zip(values.tolist(), counts.tolist())))
assert values.tolist() == [-1, 7, 1000000]
assert counts.tolist() == [2, 1, 2]
Recorded output
bincount rejects negative IDs label IDs: [-1, 7, 1000000] counts: [2, 1, 2] pairs: [(-1, 2), (7, 1), (1000000, 2)]
Choose the representation deliberately
Unique counts only values that occur in the data. If a reporting contract requires every possible class, including classes with zero observations, align the result to a separately defined class list. Do not silently treat a missing observed ID as an unknown class. [2]
The example is one-dimensional and unweighted. It does not benchmark performance or cover floating point NaNs, strings, multidimensional aggregation or distributed data. For a dense fixed range of nonnegative IDs, bincount remains a direct option.