-
-
Notifications
You must be signed in to change notification settings - Fork 26.2k
ENH Add array api for log_loss #30439
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
Closed
Closed
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
0d8a25d
ENH Add array api for log_loss
OmarManzoor ca15245
Merge branch 'main' into array_api_log_loss
OmarManzoor 57398c4
Add changelog
OmarManzoor 3339cac
Revert unintended change
OmarManzoor 8df9a45
Merge branch 'main' into array_api_log_loss
OmarManzoor 6c9b0b4
Improve var naming
OmarManzoor 6476b98
Improve the _allclose helper
OmarManzoor 9e7d91e
Add missing xp
OmarManzoor cfabbd0
Add doc and improve variable names in _allclose
OmarManzoor 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
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
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,2 @@ | ||
- :func:`sklearn.metrics.log_loss` now supports Array API compatible inputs. | ||
by :user:`Omar Salman <OmarManzoor>` |
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 |
---|---|---|
|
@@ -27,8 +27,10 @@ | |
column_or_1d, | ||
) | ||
from ..utils._array_api import ( | ||
_allclose, | ||
_average, | ||
_bincount, | ||
_convert_to_numpy, | ||
_count_nonzero, | ||
_find_matching_floating_dtype, | ||
_is_numpy_namespace, | ||
|
@@ -39,6 +41,7 @@ | |
device, | ||
get_namespace, | ||
get_namespace_and_device, | ||
supported_float_dtypes, | ||
) | ||
from ..utils._param_validation import ( | ||
Hidden, | ||
|
@@ -2953,17 +2956,16 @@ def log_loss(y_true, y_pred, *, normalize=True, sample_weight=None, labels=None) | |
... [[.1, .9], [.9, .1], [.8, .2], [.35, .65]]) | ||
0.21616... | ||
""" | ||
y_pred = check_array( | ||
y_pred, ensure_2d=False, dtype=[np.float64, np.float32, np.float16] | ||
) | ||
xp, _, device_ = get_namespace_and_device(y_true, y_pred, sample_weight, labels) | ||
y_pred = check_array(y_pred, ensure_2d=False, dtype=supported_float_dtypes(xp=xp)) | ||
|
||
check_consistent_length(y_pred, y_true, sample_weight) | ||
lb = LabelBinarizer() | ||
|
||
if labels is not None: | ||
lb.fit(labels) | ||
lb.fit(_convert_to_numpy(labels, xp=xp)) | ||
else: | ||
lb.fit(y_true) | ||
lb.fit(_convert_to_numpy(y_true, xp=xp)) | ||
|
||
if len(lb.classes_) == 1: | ||
if labels is None: | ||
|
@@ -2979,32 +2981,37 @@ def log_loss(y_true, y_pred, *, normalize=True, sample_weight=None, labels=None) | |
"got {0}.".format(lb.classes_) | ||
) | ||
|
||
transformed_labels = lb.transform(y_true) | ||
float_dtype = _find_matching_floating_dtype(y_true, y_pred, xp=xp) | ||
transformed_labels = xp.asarray( | ||
lb.transform(_convert_to_numpy(y_true, xp=xp)), | ||
dtype=float_dtype, | ||
device=device_, | ||
) | ||
|
||
if transformed_labels.shape[1] == 1: | ||
transformed_labels = np.append( | ||
1 - transformed_labels, transformed_labels, axis=1 | ||
transformed_labels = xp.concat( | ||
(1 - transformed_labels, transformed_labels), axis=1 | ||
) | ||
|
||
# If y_pred is of single dimension, assume y_true to be binary | ||
# and then check. | ||
if y_pred.ndim == 1: | ||
y_pred = y_pred[:, np.newaxis] | ||
y_pred = y_pred[:, xp.newaxis] | ||
if y_pred.shape[1] == 1: | ||
y_pred = np.append(1 - y_pred, y_pred, axis=1) | ||
y_pred = xp.concat((1 - y_pred, y_pred), axis=1) | ||
|
||
eps = np.finfo(y_pred.dtype).eps | ||
eps = xp.finfo(y_pred.dtype).eps | ||
|
||
# Make sure y_pred is normalized | ||
y_pred_sum = y_pred.sum(axis=1) | ||
if not np.allclose(y_pred_sum, 1, rtol=np.sqrt(eps)): | ||
y_pred_sum = xp.sum(y_pred, axis=1) | ||
if not _allclose(y_pred_sum, 1, rtol=np.sqrt(eps), xp=xp): | ||
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. Note: Since we are internally converting to numpy in all cases in the |
||
warnings.warn( | ||
"The y_pred values do not sum to one. Make sure to pass probabilities.", | ||
UserWarning, | ||
) | ||
|
||
# Clipping | ||
y_pred = np.clip(y_pred, eps, 1 - eps) | ||
y_pred = xp.clip(y_pred, eps, 1 - eps) | ||
|
||
# Check if dimensions are consistent. | ||
transformed_labels = check_array(transformed_labels) | ||
|
@@ -3026,7 +3033,7 @@ def log_loss(y_true, y_pred, *, normalize=True, sample_weight=None, labels=None) | |
"labels: {0}".format(lb.classes_) | ||
) | ||
|
||
loss = -xlogy(transformed_labels, y_pred).sum(axis=1) | ||
loss = xp.sum(-xlogy(transformed_labels, y_pred), axis=1) | ||
|
||
return float(_average(loss, weights=sample_weight, normalize=normalize)) | ||
|
||
|
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
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
Oops, something went wrong.
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.
This is somewhat then missing the point of "supporting array API" here. I'd say we support array API if we don't convert to Numpy, and here we do. So in effect, there's not much of an improvement with this PR.
I think in order to get this merged,
LabelBinarizer
should support array API.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 agree that would be better, but I think we still perform computations after the LabelBinarizer part. Particularly the sums, clipping and xlogy, that might still bring some improvements as scipy's xlogy supports the array api.
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.
It might not be worth moving the data back and forth between devices
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.
Yes I think you are right.
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 updated the description to reflect this.
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 think that means we need to shelf this PR until we fix label binarizer.