Skip to content

ENH Add Array API compatibility for additive_chi2_kernel #29144

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 8 commits into from
Jun 13, 2024
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
1 change: 1 addition & 0 deletions doc/modules/array_api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ Metrics
- :func:`sklearn.metrics.mean_gamma_deviance`
- :func:`sklearn.metrics.mean_squared_error`
- :func:`sklearn.metrics.mean_tweedie_deviance`
- :func:`sklearn.metrics.pairwise.additive_chi2_kernel`
- :func:`sklearn.metrics.pairwise.cosine_similarity`
- :func:`sklearn.metrics.pairwise.paired_cosine_distances`
- :func:`sklearn.metrics.r2_score`
Expand Down
3 changes: 2 additions & 1 deletion doc/whats_new/v1.6.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ See :ref:`array_api` for more details.
- :func:`sklearn.metrics.mean_gamma_deviance` :pr:`29239` by :usser:`Emily Chen <EmilyXinyi>`;
- :func:`sklearn.metrics.mean_squared_error` :pr:`29142` by :user:`Yaroslav Korobko <Tialo>`;
- :func:`sklearn.metrics.mean_tweedie_deviance` :pr:`28106` by :user:`Thomas Li <lithomas1>`;
- :func:`sklearn.metrics.pairwise.cosine_similarity` :pr:`29014` by :user:`Edoardo Abati <EdAbati>`.
- :func:`sklearn.metrics.pairwise.additive_chi2_kernel` :pr:`29144` by :user:`Yaroslav Korobko <Tialo>`;
- :func:`sklearn.metrics.pairwise.cosine_similarity` :pr:`29014` by :user:`Edoardo Abati <EdAbati>`;
- :func:`sklearn.metrics.pairwise.paired_cosine_distances` :pr:`29112` by :user:`Edoardo Abati <EdAbati>`.

**Classes:**
Expand Down
23 changes: 17 additions & 6 deletions sklearn/metrics/pairwise.py
Original file line number Diff line number Diff line change
Expand Up @@ -1718,7 +1718,7 @@ def additive_chi2_kernel(X, Y=None):

Returns
-------
kernel : ndarray of shape (n_samples_X, n_samples_Y)
kernel : array-like of shape (n_samples_X, n_samples_Y)
The kernel matrix.

See Also
Expand Down Expand Up @@ -1750,15 +1750,26 @@ def additive_chi2_kernel(X, Y=None):
array([[-1., -2.],
[-2., -1.]])
"""
xp, _ = get_namespace(X, Y)
X, Y = check_pairwise_arrays(X, Y, accept_sparse=False)
if (X < 0).any():
if xp.any(X < 0):
raise ValueError("X contains negative values.")
if Y is not X and (Y < 0).any():
if Y is not X and xp.any(Y < 0):
raise ValueError("Y contains negative values.")

result = np.zeros((X.shape[0], Y.shape[0]), dtype=X.dtype)
_chi2_kernel_fast(X, Y, result)
return result
if _is_numpy_namespace(xp):
result = np.zeros((X.shape[0], Y.shape[0]), dtype=X.dtype)
_chi2_kernel_fast(X, Y, result)
return result
else:
dtype = _find_matching_floating_dtype(X, Y, xp=xp)
xb = X[:, None, :]
yb = Y[None, :, :]
nom = -((xb - yb) ** 2)
denom = xb + yb
nom = xp.where(denom == 0, xp.asarray(0, dtype=dtype), nom)
denom = xp.where(denom == 0, xp.asarray(1, dtype=dtype), denom)
return xp.sum(nom / denom, axis=2)


@validate_params(
Expand Down
7 changes: 6 additions & 1 deletion sklearn/metrics/tests/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,11 @@
zero_one_loss,
)
from sklearn.metrics._base import _average_binary_score
from sklearn.metrics.pairwise import cosine_similarity, paired_cosine_distances
from sklearn.metrics.pairwise import (
additive_chi2_kernel,
cosine_similarity,
paired_cosine_distances,
)
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils import shuffle
from sklearn.utils._array_api import (
Expand Down Expand Up @@ -1955,6 +1959,7 @@ def check_array_api_metric_pairwise(metric, array_namespace, device, dtype_name)
check_array_api_regression_metric,
],
paired_cosine_distances: [check_array_api_metric_pairwise],
additive_chi2_kernel: [check_array_api_metric_pairwise],
mean_gamma_deviance: [check_array_api_regression_metric],
max_error: [check_array_api_regression_metric],
}
Expand Down