Skip to content

Commit

Permalink
bug (ssr): Be explicit when setting the shape.
Browse files Browse the repository at this point in the history
Previously, sklearn.linear_model.ridge_regression would always give a 2D array
when using 2D inputs.  A change to scikitlearn 1.6 now squeezes that extra
dimension when there's only one target for the regression.

Also, remove extra debug.py that snuck in previous commit.
  • Loading branch information
Jacob-Stevens-Haas committed Jan 12, 2025
1 parent f60cba9 commit 8b8f0a5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 21 deletions.
20 changes: 19 additions & 1 deletion pysindy/optimizers/ssr.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
from typing import cast
from typing import NewType
from typing import TypeVar

import numpy as np
from numpy.typing import NBitBase
from sklearn.linear_model import ridge_regression

from .base import BaseOptimizer

Rows = TypeVar("Rows", covariant=True, bound=int)
Cols = TypeVar("Cols", covariant=True, bound=int)
Float2D = np.ndarray[tuple[Rows, Cols], np.dtype[np.floating[NBitBase]]]
Features = NewType("Features", int)
Targets = NewType("Targets", int)
Samples = NewType("Samples", int)


class SSR(BaseOptimizer):
"""Stepwise sparse regression (SSR) greedy algorithm.
Expand Down Expand Up @@ -157,17 +169,23 @@ def _model_residual(self, x, y, coef, inds):
cc[total_ind] = 0.0
return cc, total_ind

def _regress(self, x, y):
def _regress(
self, x: Float2D[Samples, Features], y: Float2D[Samples, Targets]
) -> Float2D[Targets, Features]:
"""Perform the ridge regression"""
kw = self.ridge_kw or {}
coef = ridge_regression(x, y, self.alpha, **kw)
coef = np.atleast_2d(coef) # type: ignore
self.iters += 1
return coef

def _reduce(self, x, y):
"""Performs at most ``self.max_iter`` iterations of the
SSR greedy algorithm.
"""
# Until static typing grows, use cast
x = cast(Float2D[Samples, Features], x)
y = cast(Float2D[Samples, Targets], y)
n_samples, n_features = x.shape
n_targets = y.shape[1]
cond_num = np.linalg.cond(x)
Expand Down
20 changes: 0 additions & 20 deletions test/test_optimizers/debug.py

This file was deleted.

0 comments on commit 8b8f0a5

Please sign in to comment.