-
-
Notifications
You must be signed in to change notification settings - Fork 25.8k
ENH Add zero division handling to cohen_kappa_score #31172
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
Open
StefanieSenger
wants to merge
15
commits into
scikit-learn:main
Choose a base branch
from
StefanieSenger:undefined_cohen_kappa_score
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
5a000a0
ENH Add zero division handling to cohen_kappa_score
StefanieSenger 02fd573
add changelog
StefanieSenger 2d84ded
add warnings raised in case of zero division
StefanieSenger 4b00d9f
refine test comments
StefanieSenger f58492a
correct version
StefanieSenger 245da3e
improve docstring of test
StefanieSenger ede386e
wording
StefanieSenger b93b445
add deprecation cycle for default behaviour if zero division
StefanieSenger 612b800
Merge branch 'main' into undefined_cohen_kappa_score
StefanieSenger a7f4ba6
fix linting
StefanieSenger 375d204
Merge branch 'main' into undefined_cohen_kappa_score
StefanieSenger 6d8e59b
Apply suggestions from code review
StefanieSenger 973b219
clean up test and correct warning message
StefanieSenger 3947409
Merge branch 'main' into undefined_cohen_kappa_score
StefanieSenger 2ee10a3
leaner test
StefanieSenger File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
3 changes: 3 additions & 0 deletions
3
doc/whats_new/upcoming_changes/sklearn.metrics/31172.enhancement.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
- :func:`~metrics.cohen_kappa_score` now has a `replace_undefined_by` param, that can be | ||
set to define the function's return value when there would be a division by zero. | ||
By :user:`Stefanie Senger <StefanieSenger>` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -799,10 +799,25 @@ def multilabel_confusion_matrix( | |
"labels": ["array-like", None], | ||
"weights": [StrOptions({"linear", "quadratic"}), None], | ||
"sample_weight": ["array-like", None], | ||
"replace_undefined_by": [ | ||
Interval(Real, -1.0, 1.0, closed="both"), | ||
np.nan, | ||
Hidden(StrOptions({"deprecated"})), | ||
], | ||
}, | ||
prefer_skip_nested_validation=True, | ||
) | ||
def cohen_kappa_score(y1, y2, *, labels=None, weights=None, sample_weight=None): | ||
# TODO(1.9): Change default value for `replace_undefined_by` param to 0.0 and remove | ||
# FutureWarnings; also the defaults in the warning messages need to be updated. | ||
def cohen_kappa_score( | ||
y1, | ||
y2, | ||
*, | ||
labels=None, | ||
weights=None, | ||
sample_weight=None, | ||
replace_undefined_by="deprecated", | ||
): | ||
r"""Compute Cohen's kappa: a statistic that measures inter-annotator agreement. | ||
|
||
This function computes Cohen's kappa [1]_, a score that expresses the level | ||
|
@@ -843,11 +858,25 @@ class labels [2]_. | |
sample_weight : array-like of shape (n_samples,), default=None | ||
Sample weights. | ||
|
||
replace_undefined_by : np.nan, float in [-1.0, 1.0], default=np.nan | ||
Sets the return value when a division by zero would occur. This can happen for | ||
instance on empty input arrays, or when no label of interest (as defined in the | ||
`labels` param) is assigned by the second annotator, or when both `y1` and `y2` | ||
only have one label in common that is also in `labels`. In these cases, an | ||
:class:`~sklearn.exceptions.UndefinedMetricWarning` is raised. Can take the | ||
following values: | ||
|
||
- `np.nan` to return `np.nan` | ||
- a floating point value in the range of [-1.0, 1.0] to return a specific value | ||
|
||
.. versionadded:: 1.7 | ||
|
||
Returns | ||
------- | ||
kappa : float | ||
The kappa statistic, which is a number between -1 and 1. The maximum | ||
value means complete agreement; zero or lower means chance agreement. | ||
The kappa statistic, which is a number between -1.0 and 1.0. The maximum value | ||
means complete agreement; the minimum value means complete disagreement; 0.0 | ||
indicates no agreement beyond what would be expected by chance. | ||
|
||
References | ||
---------- | ||
|
@@ -883,7 +912,28 @@ class labels [2]_. | |
n_classes = confusion.shape[0] | ||
sum0 = np.sum(confusion, axis=0) | ||
sum1 = np.sum(confusion, axis=1) | ||
expected = np.outer(sum0, sum1) / np.sum(sum0) | ||
|
||
mgs_changing_default = ( | ||
"The default return value of `cohen_kappa_score` in case of a division " | ||
"by zero has been deprecated in 1.7 and will be changed to 0.0 in version " | ||
"1.9. Set `replace_undefined_by=0.0` to use the new default and to silence " | ||
"this Warning." | ||
) | ||
|
||
numerator = np.outer(sum0, sum1) | ||
denominator = np.sum(sum0) | ||
if np.isclose(denominator, 0): | ||
if replace_undefined_by == "deprecated": | ||
replace_undefined_by = np.nan | ||
warnings.warn(mgs_changing_default, FutureWarning) | ||
msg = ( | ||
"`y2` contains no labels that are presented in both `y1` and `labels`." | ||
"cohen_kappa_score is undefined and set to the value defined in " | ||
"the `replace_undefined_by` param, which defaults to `np.nan`." | ||
) | ||
warnings.warn(msg, UndefinedMetricWarning, stacklevel=2) | ||
return replace_undefined_by | ||
expected = numerator / denominator | ||
|
||
if weights is None: | ||
w_mat = np.ones([n_classes, n_classes], dtype=int) | ||
|
@@ -896,7 +946,21 @@ class labels [2]_. | |
else: | ||
w_mat = (w_mat - w_mat.T) ** 2 | ||
|
||
k = np.sum(w_mat * confusion) / np.sum(w_mat * expected) | ||
numerator = np.sum(w_mat * confusion) | ||
denominator = np.sum(w_mat * expected) | ||
if np.isclose(denominator, 0): | ||
if replace_undefined_by == "deprecated": | ||
replace_undefined_by = np.nan | ||
warnings.warn(mgs_changing_default, FutureWarning) | ||
msg = ( | ||
"`y1`, `y2` and `labels` have only one label in common. " | ||
"cohen_kappa_score is undefined and set to the value defined in the " | ||
"`replace_undefined_by` param, which defaults to `np.nan`." | ||
) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In my thinking, this message also fits the cases when y1 and y2 only deal with one label (as in "test case: both inputs only have one label"). |
||
warnings.warn(msg, UndefinedMetricWarning, stacklevel=2) | ||
return replace_undefined_by | ||
k = numerator / denominator | ||
|
||
return float(1 - k) | ||
|
||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would pick 0.0 as a future default (instead of -1.0 which is the worst score), because it is the least expressive of the scores, representing matching labels by chance.
If users would use
cohen_kappa_score
as part of their custom metric, that calculates the mean over several cohen_kappa_scores, 0.0 would be a neutral element like the "ignore" option that we have talked about in this comment: #29048 (comment)