Skip to content

confusion_matrix crashes when sample_weight is an empty array #33040

@Nitin-Prata

Description

@Nitin-Prata

Describe the bug

When calling confusion_matrix with non-empty y_true and y_pred but an empty
sample_weight array, the function crashes during internal processing.

This appears to be caused by inconsistent handling of empty sample_weight
compared to all-zero sample_weight, which currently raises a ValueError.

Steps/Code to Reproduce

from sklearn.metrics import confusion_matrix

y_true = [0, 1]
y_pred = [0, 1]

confusion_matrix(y_true, y_pred, sample_weight=[])

Expected Results

Either
A clear ValueError indicating invalid sample_weight, OR
A documented and consistent behavior matching all-zero sample_weight.

In any case, the function should not crash internally.

Actual Results

The function crashes with an internal error related to array length mismatch
during confusion matrix construction.

Versions

System:
python: 3.12.10 (tags/v3.12.10:0cc8128, Apr 8 2025, 12:21:36) [MSC v.1943 64 bit (AMD64)]
executable: C:\Users\HP\venv-sklearn\Scripts\python.exe
machine: Windows-11-10.0.26200-SP0

Python dependencies:
sklearn: 1.9.dev0
pip: 25.3
setuptools: 80.9.0
numpy: 2.4.0
scipy: 1.16.3
Cython: 3.2.4
pandas: None
matplotlib: None
joblib: 1.5.3
threadpoolctl: 3.6.0

Built with OpenMP: True

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions