Skip to content

FIX mcc zero divsion #19977

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 7 commits into from
Jun 3, 2021
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
5 changes: 2 additions & 3 deletions sklearn/metrics/_classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -878,12 +878,11 @@ def matthews_corrcoef(y_true, y_pred, *, sample_weight=None):
cov_ytyp = n_correct * n_samples - np.dot(t_sum, p_sum)
cov_ypyp = n_samples ** 2 - np.dot(p_sum, p_sum)
cov_ytyt = n_samples ** 2 - np.dot(t_sum, t_sum)
mcc = cov_ytyp / np.sqrt(cov_ytyt * cov_ypyp)

if np.isnan(mcc):
if cov_ypyp * cov_ytyt == 0:
return 0.
else:
return mcc
return cov_ytyp / np.sqrt(cov_ytyt * cov_ypyp)


@_deprecate_positional_args
Expand Down
35 changes: 13 additions & 22 deletions sklearn/metrics/tests/test_classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
from sklearn.utils._testing import assert_array_equal
from sklearn.utils._testing import assert_array_almost_equal
from sklearn.utils._testing import assert_allclose
from sklearn.utils._testing import assert_warns_div0
from sklearn.utils._testing import assert_no_warnings
from sklearn.utils._testing import assert_warns_message
from sklearn.utils._testing import ignore_warnings
Expand Down Expand Up @@ -622,7 +621,6 @@ def test_cohen_kappa():
weights="quadratic"), 0.9541, decimal=4)


@ignore_warnings
def test_matthews_corrcoef_nan():
assert matthews_corrcoef([0], [1]) == 0.0
assert matthews_corrcoef([0, 0], [0, 1]) == 0.0
Expand Down Expand Up @@ -684,17 +682,11 @@ def test_matthews_corrcoef():
assert_almost_equal(matthews_corrcoef(y_true, y_true_inv2), -1)

# For the zero vector case, the corrcoef cannot be calculated and should
# result in a RuntimeWarning
mcc = assert_warns_div0(matthews_corrcoef, [0, 0, 0, 0], [0, 0, 0, 0])

# But will output 0
assert_almost_equal(mcc, 0.)
# output 0
assert_almost_equal(matthews_corrcoef([0, 0, 0, 0], [0, 0, 0, 0]), 0.)

# And also for any other vector with 0 variance
mcc = assert_warns_div0(matthews_corrcoef, y_true, ['a'] * len(y_true))

# But will output 0
assert_almost_equal(mcc, 0.)
assert_almost_equal(matthews_corrcoef(y_true, ['a'] * len(y_true)), 0.)

# These two vectors have 0 correlation and hence mcc should be 0
y_1 = [1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1]
Expand Down Expand Up @@ -731,12 +723,15 @@ def test_matthews_corrcoef_multiclass():
assert_almost_equal(matthews_corrcoef(y_true, y_pred_min),
-12 / np.sqrt(24 * 16))

# Zero variance will result in an mcc of zero and a Runtime Warning
# Zero variance will result in an mcc of zero
y_true = [0, 1, 2]
y_pred = [3, 3, 3]
mcc = assert_warns_message(RuntimeWarning, 'invalid value encountered',
matthews_corrcoef, y_true, y_pred)
assert_almost_equal(mcc, 0.0)
assert_almost_equal(matthews_corrcoef(y_true, y_pred), 0.0)

# Also for ground truth with zero variance
y_true = [3, 3, 3]
y_pred = [0, 1, 2]
assert_almost_equal(matthews_corrcoef(y_true, y_pred), 0.0)

# These two vectors have 0 correlation and hence mcc should be 0
y_1 = [0, 1, 2, 0, 1, 2, 0, 1, 2]
Expand All @@ -754,16 +749,12 @@ def test_matthews_corrcoef_multiclass():
sample_weight=sample_weight), -1)

# For the zero vector case, the corrcoef cannot be calculated and should
# result in a RuntimeWarning
# output 0
y_true = [0, 0, 1, 2]
y_pred = [0, 0, 1, 2]
sample_weight = [1, 1, 0, 0]
mcc = assert_warns_message(RuntimeWarning, 'invalid value encountered',
matthews_corrcoef, y_true, y_pred,
sample_weight=sample_weight)

# But will output 0
assert_almost_equal(mcc, 0.)
assert_almost_equal(matthews_corrcoef(y_true, y_pred,
sample_weight=sample_weight), 0.)


@pytest.mark.parametrize('n_points', [100, 10000])
Expand Down
24 changes: 0 additions & 24 deletions sklearn/utils/_testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,30 +187,6 @@ def check_in_message(msg): return message in msg
return result


def assert_warns_div0(func, *args, **kw):
"""Assume that numpy's warning for divide by zero is raised.

Handles the case of platforms that do not support warning on divide by
zero.

Parameters
----------
func
*args
**kw
"""

with np.errstate(divide='warn', invalid='warn'):
try:
assert_warns(RuntimeWarning, np.divide, 1, np.zeros(1))
except AssertionError:
# This platform does not report numpy divide by zeros
return func(*args, **kw)
return assert_warns_message(RuntimeWarning,
'invalid value encountered',
func, *args, **kw)


# To remove when we support numpy 1.7
def assert_no_warnings(func, *args, **kw):
"""
Expand Down