Class-Balanced Weights via Effective Number
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement three functions for class-balanced loss weights.
- `effective_number(counts, beta)` returns the effective number of samples for each class, $E_n = \frac{1 - \beta^n}{1 - \beta}$, where $n$ is the class count.
- `class_balanced_weights(counts, beta)` returns weights proportional to ${1 / E_n}$, rescaled so they sum to the number of classes.
- `class_balanced_sample_weights(y, beta)` returns, for each label in `y`, the class-balanced weight of its class. The classes are the sorted unique labels of `y`, and the counts come from `y`.
Example:
```python
effective_number([1, 2, 3], 0.5) # [1.0, 1.5, 1.75]
class_balanced_weights([1, 2, 3], 0.5) # [63/47, 42/47, 36/47], sums to 3
class_balanced_sample_weights([5, 2, 5, 5, 2, 9], 0.5)
# classes 2, 5, 9 have counts 2, 3, 1
# -> [36/47, 42/47, 36/47, 36/47, 42/47, 63/47]
```
```hint One call for the labels
A single NumPy call can return the sorted labels, their counts and each sample's position among those labels. That gives you the counts for the class weights and the lookup for the sample weights.
```
### Constraints & Assumptions
- `counts` is a non-empty 1-D array-like of positive values; otherwise raise `ValueError`.
- `beta` must lie in $[0, 1)$; otherwise raise `ValueError`. With `beta = 0` every class gets the same weight.
- All three functions return 1-D NumPy float arrays, and the sample weights have shape `(len(y),)`.
### What a Strong Answer Covers
- A vectorized effective-number computation that matches the closed form on small counts.
- Normalization of the inverse effective numbers so the weights sum to the number of classes.
- Mapping each sample to its class weight using the sorted unique labels and their counts from `y`.
- Validation of empty or non-1-D counts, non-positive counts, and `beta` outside $[0, 1)$.
- How the weights behave at `beta = 0` and as `beta` approaches 1.
### Follow-up Questions
- How should β be chosen, and how does it relate to inverse frequency?
- How would you plug these weights into a loss such as focal loss or cross-entropy?
- What happens with classes that are absent from a batch or from `y`?
Overview: Implement class-balanced weights based on the effective number of samples, map them to per-sample weights, and validate the inputs. It tests vectorized NumPy, normalization of loss weights, and how the beta parameter moves the weighting between uniform and inverse frequency.