Skip to content

MNT Raise erorr when normalize is invalid in confusion_matrix #15888

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions doc/whats_new/v0.22.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ This is a bug-fix release to primarily resolve some packaging issues in version
Changelog
---------

:mod:`sklearn.metrics`
......................

- |Fix| :func:`metrics.plot_confusion_matrix` now raises error when `normalize`
is invalid. Previously, it runs fine with no normalization.
:pr:`15888` by `Hanmin Qin`_.

:mod:`sklearn.utils`
....................

Expand Down
4 changes: 4 additions & 0 deletions sklearn/metrics/_classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,10 @@ def confusion_matrix(y_true, y_pred, labels=None, sample_weight=None,

check_consistent_length(y_true, y_pred, sample_weight)

if normalize not in ['true', 'pred', 'all', None]:
raise ValueError("normalize must be one of {'true', 'pred', "
"'all', None}")

n_labels = labels.size
label_to_ind = {y: x for x, y in enumerate(labels)}
# convert yt, yp into index
Expand Down
4 changes: 0 additions & 4 deletions sklearn/metrics/_plot/confusion_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,6 @@ def plot_confusion_matrix(estimator, X, y_true, labels=None,
if not is_classifier(estimator):
raise ValueError("plot_confusion_matrix only supports classifiers")

if normalize not in {'true', 'pred', 'all', None}:
raise ValueError("normalize must be one of {'true', 'pred', "
"'all', None}")

y_pred = estimator.predict(X)
cm = confusion_matrix(y_true, y_pred, sample_weight=sample_weight,
labels=labels, normalize=normalize)
Expand Down
7 changes: 7 additions & 0 deletions sklearn/metrics/tests/test_classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,13 @@ def test_confusion_matrix_normalize(normalize, cm_dtype, expected_results):
assert cm.dtype.kind == cm_dtype


def test_confusion_matrix_normalize_wrong_option():
y_test = [0, 0, 0, 0, 1, 1, 1, 1]
y_pred = [0, 0, 0, 0, 0, 0, 0, 0]
with pytest.raises(ValueError, match='normalize must be one of'):
confusion_matrix(y_test, y_pred, normalize=True)


def test_confusion_matrix_normalize_single_class():
y_test = [0, 0, 0, 0, 1, 1, 1, 1]
y_pred = [0, 0, 0, 0, 0, 0, 0, 0]
Expand Down