Repository navigation
Description
Warning
This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.
Describe the bug
When compute_class_weight or compute_sample_weight is called with class_weight="balanced" and an empty input (classes=np.array([]), y=np.array([])), it crashes with an unexpected low-level IndexError:
IndexError: arrays used as indices must be of integer (or boolean) type
In contrast, calling compute_class_weight with class_weight=None or class_weight={} returns an empty array array([], dtype=float64), and compute_sample_weight(class_weight=None, y=[]) returns an empty array.
Steps/Code to Reproduce
import numpy as np
from sklearn.utils.class_weight import compute_class_weight, compute_sample_weight
# Reproduce via compute_class_weight:
compute_class_weight("balanced", classes=np.array([]), y=np.array([]))
# Or via compute_sample_weight:
compute_sample_weight("balanced", y=np.array([]))Expected Results
Either:
- Return an empty array of class / sample weights of shape
(0,)consistent withclass_weight=Noneandclass_weight={}, or - Raise a clear, descriptive
ValueErrorduring input validation if 0-length inputs are disallowed.
Actual Results
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../sklearn/utils/_param_validation.py", line 218, in wrapper
return func(*args, **kwargs)
File ".../sklearn/utils/class_weight.py", line 84, in compute_class_weight
weight = recip_freq[le.transform(classes)]
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
IndexError: arrays used as indices must be of integer (or boolean) typeRoot Cause Analysis
In sklearn/utils/class_weight.py:
elif class_weight == "balanced":
# Find the weight of each class as present in y.
le = LabelEncoder()
y_ind = le.fit_transform(y)
if not all(np.isin(classes, le.classes_)):
raise ValueError("classes should have valid labels that are in y")
sample_weight = _check_sample_weight(sample_weight, y)
weighted_class_counts = np.bincount(y_ind, weights=sample_weight)
recip_freq = weighted_class_counts.sum() / (
len(le.classes_) * weighted_class_counts
)
weight = recip_freq[le.transform(classes)]When classes has length 0, le.transform(classes) produces an empty array with default float dtype (array([], dtype=float64)). In NumPy, attempting to index recip_freq using a floating-point array triggers IndexError: arrays used as indices must be of integer (or boolean) type.
If classes.shape[0] == 0, returning np.empty(0, dtype=np.float64) (matching class_weight=None) avoids the invalid indexing.
Versions / Environment
- OS: Linux
- scikit-learn: 1.6 / 1.7 / 1.8.dev / main
- Python: 3.11 / 3.12 / 3.13
- NumPy: 2.x
Activity