Compute scikit-learn's balanced class weights by hand with NumPy
Quick Overview
Reproduce scikit-learn's balanced class weights in NumPy by counting labels and applying the n_samples / (n_classes * count) formula. It tests vectorized counting, label ordering assumptions and how class weighting rebalances a logistic regression loss.
Compute scikit-learn's balanced class weights by hand with NumPy
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `balanced_class_weights(y: np.ndarray) -> np.ndarray` reproducing scikit-learn's `class_weight='balanced'` by hand. `y` is a 1-D integer ndarray of labels from consecutive classes `0..n_classes-1`. Return a `float64` ndarray of shape `(n_classes,)` where entry `i` is the weight of class `i`, ordered ascending to match `np.unique(y)`.
Requirements:
- Formula: `n_samples / (n_classes * np.bincount(y))`.
- `n_samples = len(y)`, `n_classes = len(np.unique(y))`.
- Do not import or call `sklearn.utils.class_weight.compute_class_weight`.
- The result is graded with `assert_allclose(rtol=1e-5)` against `compute_class_weight('balanced', classes=np.unique(y), y=y)` on the 2-class example below and a 3-class case.
Example:
```python
y = np.array([0]*8 + [1]*2)
balanced_class_weights(y) # -> array([0.625, 2.5])
```
```hint Check against the example
Work the 8-versus-2 example by hand first. Multiply each class's count by its weight and compare the totals for the two classes.
```
### Constraints & Assumptions
- `y` is a 1-D array of non-negative integers.
- Labels are consecutive from 0, and every class in `0..n_classes-1` appears at least once.
### What a Strong Answer Covers
- Computes the sample count, class count and per-class counts with vectorized NumPy, without calling scikit-learn's helper.
- Returns `float64` weights of shape `(n_classes,)` in ascending label order.
- Explains why the order of `np.bincount` matches `np.unique(y)` under the consecutive-label assumption.
- Notes that every class ends up with the same total weight, `n_samples / n_classes`.
- States the time and space cost and what goes wrong when a label in the range is missing.
### Follow-up Questions
- How would you change the function if the labels were arbitrary values, such as strings or non-consecutive integers?
- How do these weights change the logistic regression loss, and how does weighting compare with resampling the data?
- After training with balanced weights, are the predicted probabilities still calibrated? What would you do about it?
Overview: Reproduce scikit-learn's balanced class weights in NumPy by counting labels and applying the n_samples / (n_classes * count) formula. It tests vectorized counting, label ordering assumptions and how class weighting rebalances a logistic regression loss.
Compute scikit-learn's balanced class weights by hand with NumPy
General
Nov 25, 2026
easyData ScientistOtherMachine Learning
0
0
Implement balanced_class_weights(y: np.ndarray) -> np.ndarray reproducing scikit-learn's class_weight='balanced' by hand. y is a 1-D integer ndarray of labels from consecutive classes 0..n_classes-1. Return a float64 ndarray of shape (n_classes,) where entry i is the weight of class i, ordered ascending to match np.unique(y).
Do not import or call
sklearn.utils.class_weight.compute_class_weight
.
The result is graded with
assert_allclose(rtol=1e-5)
against
compute_class_weight('balanced', classes=np.unique(y), y=y)
on the 2-class example below and a 3-class case.
Example:
y = np.array([0]*8 + [1]*2)
balanced_class_weights(y) # -> array([0.625, 2.5])
Constraints & Assumptions
y
is a 1-D array of non-negative integers.
Labels are consecutive from 0, and every class in
0..n_classes-1
appears at least once.
What a Strong Answer Covers Guidance
Computes the sample count, class count and per-class counts with vectorized NumPy, without calling scikit-learn's helper.
Returns
float64
weights of shape
(n_classes,)
in ascending label order.
Explains why the order of
np.bincount
matches
np.unique(y)
under the consecutive-label assumption.
Notes that every class ends up with the same total weight,
n_samples / n_classes
.
States the time and space cost and what goes wrong when a label in the range is missing.
Follow-up Questions Guidance
How would you change the function if the labels were arbitrary values, such as strings or non-consecutive integers?
How do these weights change the logistic regression loss, and how does weighting compare with resampling the data?
After training with balanced weights, are the predicted probabilities still calibrated? What would you do about it?