Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
a6f071d
Add array API support for Ridge(solver='cholesky')
ogrisel Jun 20, 2024
01c2553
Merge branch 'main' into ridge-cholesky-array-api
ogrisel Jun 20, 2024
513a739
Update PR number in changelog
ogrisel Jun 20, 2024
2d4da37
Merge branch 'main' into ridge-cholesky-array-api
ogrisel Jun 21, 2024
99af487
Improve test coverage
ogrisel Jun 21, 2024
8b4e412
Simplify test
ogrisel Jun 21, 2024
0a17d7c
Fix auto-solver logic and tests
ogrisel Jun 21, 2024
6c90122
Fix handling of multiple target with different alpha values
ogrisel Jun 21, 2024
8e66855
Factorize some code to limit branching when calling linalg.solve
ogrisel Jun 21, 2024
720c7e3
Fix handling of sample weights (still lack dedicated tests)
ogrisel Jun 21, 2024
91090f8
cosmit
ogrisel Jun 21, 2024
1ba2750
Typo in comment
ogrisel Jun 21, 2024
74f35a5
More code simplification
ogrisel Jun 21, 2024
fa1347d
Make sure one_alpha is a Python bool instance to avoid raising deprec…
ogrisel Jun 21, 2024
b9591bf
Avoid raising a deprecation warning when passing dtype=None to _atol_…
ogrisel Jun 21, 2024
8a80994
Remove usless xp.asarray(coef)
ogrisel Jun 21, 2024
cc6321b
Fix zip iteration over nd-array-api-strict datastructures
ogrisel Jun 21, 2024
e930b68
Merge branch 'main' into ridge-cholesky-array-api
ogrisel Jun 28, 2024
614f0da
Add link to the spec.
ogrisel Jun 28, 2024
19a9dc1
Add test for sample_weight
ogrisel Jun 28, 2024
a823ad1
Add array API support for _check_sample_weight
ogrisel Jun 28, 2024
38d7287
Fix broken test for get_namespace_and_device
ogrisel Jun 28, 2024
5bb5ac7
Extend the tests to trigger rank deficiency problem for the linear sy…
ogrisel Jun 28, 2024
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
2 changes: 1 addition & 1 deletion doc/modules/array_api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ Estimators

- :class:`decomposition.PCA` (with `svd_solver="full"`,
`svd_solver="randomized"` and `power_iteration_normalizer="QR"`)
- :class:`linear_model.Ridge` (with `solver="svd"`)
- :class:`linear_model.Ridge` (with `solver="cholesky"` or `solver="svd"`)
- :class:`discriminant_analysis.LinearDiscriminantAnalysis` (with `solver="svd"`)
- :class:`preprocessing.KernelCenterer`
- :class:`preprocessing.MaxAbsScaler`
Expand Down
2 changes: 2 additions & 0 deletions doc/whats_new/v1.6.rst
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ See :ref:`array_api` for more details.
:class:`model_selection.HalvingRandomSearchCV` now support Array API
compatible inputs when their base estimators do. :pr:`27096` by :user:`Tim
Head <betatim>` and :user:`Olivier Grisel <ogrisel>`.
- :class:`linear_model.Ridge` with `solver="cholesky"` now supports Array API
compatible inputs. :pr:`29318` by :user:`Olivier Grisel <ogrisel>`.

Metadata Routing
----------------
Expand Down
152 changes: 88 additions & 64 deletions sklearn/linear_model/_ridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,57 +198,93 @@ def _solve_lsqr(
return coefs, n_iter


def _solve_cholesky(X, y, alpha):
def _solve_cholesky(X, y, alpha, xp=None):
# w = inv(X^t X + alpha*Id) * X.T y
if xp is None:
xp, _ = get_namespace(X, y)
n_features = X.shape[1]
n_targets = y.shape[1]

A = safe_sparse_dot(X.T, X, dense_output=True)
Xy = safe_sparse_dot(X.T, y, dense_output=True)

one_alpha = np.array_equal(alpha, len(alpha) * [alpha[0]])
one_alpha = bool(xp.all(alpha == alpha[0]))
if _is_numpy_namespace(xp):
# A.flat is guaranteed to be a view even when A is Fortran-ordered
# which typically happens when X is a CSR datastructure.
A_flat = A.flat
linalg_solve = partial(linalg.solve, assume_a="pos", overwrite_a=one_alpha)
else:
# XXX: ideally one would like to pass copy=False explicitly to
# xp.reshape, but this is not supported by PyTorch at the time of
# writing.
A_flat = xp.reshape(A, (-1,))
linalg_solve = xp.linalg.solve

if one_alpha:
A.flat[:: n_features + 1] += alpha[0]
return linalg.solve(A, Xy, assume_a="pos", overwrite_a=True).T
A_flat[:: n_features + 1] += alpha[0]
return linalg_solve(A, Xy).T
else:
coefs = np.empty([n_targets, n_features], dtype=X.dtype)
for coef, target, current_alpha in zip(coefs, Xy.T, alpha):
A.flat[:: n_features + 1] += current_alpha
coef[:] = linalg.solve(A, target, assume_a="pos", overwrite_a=False).ravel()
A.flat[:: n_features + 1] -= current_alpha
coefs = xp.empty([n_targets, n_features], dtype=X.dtype, device=device(X))
for target_idx, current_alpha in enumerate(alpha):
coef = coefs[target_idx, :]
target = Xy[:, target_idx]
A_flat[:: n_features + 1] += current_alpha
coef[:] = _ravel(linalg_solve(A, target))
A_flat[:: n_features + 1] -= current_alpha
return coefs


def _solve_cholesky_kernel(K, y, alpha, sample_weight=None, copy=False):
def _solve_cholesky_kernel(K, y, alpha, sample_weight=None, copy=False, xp=None):
# dual_coef = inv(X X^t + alpha*Id) y
if xp is None:
xp, _ = get_namespace(K, y, sample_weight)
n_samples = K.shape[0]
n_targets = y.shape[1]

if copy:
K = K.copy()

alpha = np.atleast_1d(alpha)
one_alpha = (alpha == alpha[0]).all()
has_sw = isinstance(sample_weight, np.ndarray) or sample_weight not in [1.0, None]
one_alpha = bool(xp.all(alpha == alpha[0]))
has_sw = sample_weight is not None

if has_sw:
# Unlike other solvers, we need to support sample_weight directly
# because K might be a pre-computed kernel.
sw = np.sqrt(np.atleast_1d(sample_weight))
y = y * sw[:, np.newaxis]
K *= np.outer(sw, sw)
sw = xp.sqrt(sample_weight)
y = y * sw[:, None]
K *= sw[:, None] @ sw[None, :] # outer product

if _is_numpy_namespace(xp):
# K.flat is guaranteed to be a view even when K is Fortran-ordered
# which typically happens for the linear kernel X @ X.T with X being a
# CSR datastructure.
K_flat = K.flat

# Note: we must use overwrite_a=False in order to be able to use the
# fall-back solution below in case a LinAlgError is raised.
linalg_solve = partial(linalg.solve, assume_a="pos", overwrite_a=False)
else:
# XXX: ideally one would like to pass copy=False explicitly to
# xp.reshape, but this is not supported by PyTorch at the time of
# writing.
K_flat = xp.reshape(K, (-1,))
linalg_solve = xp.linalg.solve

if one_alpha:
# Only one penalty, we can solve multi-target problems in one time.
K.flat[:: n_samples + 1] += alpha[0]
K_flat[:: n_samples + 1] += alpha[0]

try:
# Note: we must use overwrite_a=False in order to be able to
# use the fall-back solution below in case a LinAlgError
# is raised
dual_coef = linalg.solve(K, y, assume_a="pos", overwrite_a=False)
dual_coef = linalg_solve(K, y)
except np.linalg.LinAlgError:
# XXX: this exception is numpy specific. If another
# xp.linalg.LinAlgError is raised instead and if the caller is
# _ridge_regression, the caller should catch it and fall back to
# the SVD solution instead.
#
# TODO: find out which call-back we want in case the caller is a
# non-linear kernel ridge instead.
warnings.warn(
"Singular matrix in solving dual problem. Using "
"least-squares solution instead."
Expand All @@ -257,27 +293,24 @@ def _solve_cholesky_kernel(K, y, alpha, sample_weight=None, copy=False):

# K is expensive to compute and store in memory so change it back in
# case it was user-given.
K.flat[:: n_samples + 1] -= alpha[0]
K_flat[:: n_samples + 1] -= alpha[0]

if has_sw:
dual_coef *= sw[:, np.newaxis]
dual_coef *= sw[:, None]

return dual_coef
else:
# One penalty per target. We need to solve each target separately.
dual_coefs = np.empty([n_targets, n_samples], K.dtype)

for dual_coef, target, current_alpha in zip(dual_coefs, y.T, alpha):
K.flat[:: n_samples + 1] += current_alpha

dual_coef[:] = linalg.solve(
K, target, assume_a="pos", overwrite_a=False
).ravel()

K.flat[:: n_samples + 1] -= current_alpha
dual_coefs = xp.empty([n_targets, n_samples], dtype=K.dtype, device=device(K))
for target_idx, current_alpha in enumerate(alpha):
dual_coef = dual_coefs[target_idx, :]
target = y[:, target_idx]
K_flat[:: n_samples + 1] += current_alpha
dual_coef[:] = _ravel(linalg_solve(K, target))
K_flat[:: n_samples + 1] -= current_alpha

if has_sw:
dual_coefs *= sw[np.newaxis, :]
dual_coefs *= sw[None, :]

return dual_coefs.T

Expand Down Expand Up @@ -625,10 +658,10 @@ def _ridge_regression(
if is_numpy_namespace and not X_is_sparse:
X = np.asarray(X)

if not is_numpy_namespace and solver != "svd":
if not is_numpy_namespace and solver not in ("svd", "cholesky"):
raise ValueError(
f"Array API dispatch to namespace {xp.__name__} only supports "
f"solver 'svd'. Got '{solver}'."
f"solver 'svd' and 'cholesky'. Got '{solver}'."
)

if positive and solver != "lbfgs":
Expand Down Expand Up @@ -684,16 +717,8 @@ def _ridge_regression(
# we implement sample_weight via a simple rescaling.
X, y, sample_weight_sqrt = _rescale_data(X, y, sample_weight)

# Some callers of this method might pass alpha as single
# element array which already has been validated.
if alpha is not None and not isinstance(alpha, type(xp.asarray([0.0]))):
alpha = check_scalar(
alpha,
"alpha",
target_type=numbers.Real,
min_val=0.0,
include_boundaries="left",
)
if alpha is not None:
alpha = xp.asarray(alpha, dtype=X.dtype, device=device_)

# There should be either 1 or n_targets penalties
alpha = _ravel(xp.asarray(alpha, device=device_, dtype=X.dtype), xp=xp)
Expand Down Expand Up @@ -739,15 +764,14 @@ def _ridge_regression(
if n_features > n_samples:
K = safe_sparse_dot(X, X.T, dense_output=True)
try:
dual_coef = _solve_cholesky_kernel(K, y, alpha)

dual_coef = _solve_cholesky_kernel(K, y, alpha, xp=xp)
coef = safe_sparse_dot(X.T, dual_coef, dense_output=True).T
except linalg.LinAlgError:
# use SVD solver if matrix is singular
solver = "svd"
else:
try:
coef = _solve_cholesky(X, y, alpha)
coef = _solve_cholesky(X, y, alpha, xp=xp)
except linalg.LinAlgError:
# use SVD solver if matrix is singular
solver = "svd"
Expand Down Expand Up @@ -810,8 +834,6 @@ def _ridge_regression(
if ravel:
coef = _ravel(coef)

coef = xp.asarray(coef)

if return_n_iter and return_intercept:
res = coef, n_iter, intercept
elif return_intercept:
Expand All @@ -837,23 +859,25 @@ def resolve_solver(solver, positive, return_intercept, is_sparse, xp):
if positive:
raise ValueError(
"The solvers that support positive fitting do not support "
f"Array API dispatch to namespace {xp.__name__}. Please "
"either disable Array API dispatch, or use a numpy-like "
f"array API dispatch to namespace {xp.__name__}. Please "
"either disable array API dispatch, or use a numpy-like "
"namespace, or set `positive=False`."
)

# At the moment, Array API dispatch only supports the "svd" solver.
solver = "svd"
if solver != auto_solver_np:
warnings.warn(
f"Using Array API dispatch to namespace {xp.__name__} with "
f"`solver='auto'` will result in using the solver '{solver}'. "
"The results may differ from those when using a Numpy array, "
f"because in that case the preferred solver would be {auto_solver_np}. "
f"Set `solver='{solver}'` to suppress this warning."
resolved_solver = auto_solver_np
if auto_solver_np != "cholesky":
# The only way to end-up here is if the solver is 'auto' and the
# namespace is not numpy, and ridge_regression was called with
# return_intercept=True.
assert return_intercept
raise ValueError(
"The solvers that support fitting fit intercept without preprocessing "
f"do not support array API dispatch to namespace {xp.__name__}. Please "
"either disable array API dispatch, or use Ridge().fit_transform(X, y) "
"instead of ridge_regression(X, y)."
)

return solver
return resolved_solver


def resolve_solver_for_numpy(positive, return_intercept, is_sparse):
Expand All @@ -872,7 +896,7 @@ def resolve_solver_for_numpy(positive, return_intercept, is_sparse):

class _BaseRidge(LinearModel, metaclass=ABCMeta):
_parameter_constraints: dict = {
"alpha": [Interval(Real, 0, None, closed="left"), np.ndarray],
"alpha": [Interval(Real, 0, None, closed="left"), "array-like"],
"fit_intercept": ["boolean"],
"copy_X": ["boolean"],
"max_iter": [Interval(Integral, 1, None, closed="left"), None],
Expand Down
Loading