Skip to content

Make skorch work with sklearn 1.6.0, attempt 2 #1078

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 2 commits into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 3 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added
### Changed

- All neural net classes now inherit from sklearn's [`BaseEstimator`](https://scikit-learn.org/stable/modules/generated/sklearn.base.BaseEstimator.html). This is to support compatibility with sklearn 1.6.0 and above. Classification models additionally inherit from [`ClassifierMixin`](https://scikit-learn.org/stable/modules/generated/sklearn.base.ClassifierMixin.html) and regressors from [`RegressorMixin`](https://scikit-learn.org/stable/modules/generated/sklearn.base.RegressorMixin.html).

### Fixed

- Fix an issue with using `NeuralNetBinaryClassifier` with `torch.compile` (#1058)
Expand Down
3 changes: 0 additions & 3 deletions skorch/callbacks/base.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
""" Basic callback definition. """

import warnings

from sklearn.base import BaseEstimator
from skorch.exceptions import SkorchWarning


__all__ = ['Callback']
Expand Down
4 changes: 2 additions & 2 deletions skorch/classifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def get_neural_net_clf_doc(doc):


# pylint: disable=missing-docstring
class NeuralNetClassifier(NeuralNet, ClassifierMixin):
class NeuralNetClassifier(ClassifierMixin, NeuralNet):
__doc__ = get_neural_net_clf_doc(NeuralNet.__doc__)

def __init__(
Expand Down Expand Up @@ -258,7 +258,7 @@ def get_neural_net_binary_clf_doc(doc):
return doc


class NeuralNetBinaryClassifier(NeuralNet, ClassifierMixin):
class NeuralNetBinaryClassifier(ClassifierMixin, NeuralNet):
# pylint: disable=missing-docstring
__doc__ = get_neural_net_binary_clf_doc(NeuralNet.__doc__)

Expand Down
2 changes: 1 addition & 1 deletion skorch/hf.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from skorch.utils import check_is_fitted, params_for


class _HuggingfaceTokenizerBase(BaseEstimator, TransformerMixin):
class _HuggingfaceTokenizerBase(TransformerMixin, BaseEstimator):
"""Base class for yet to train and pretrained tokenizers

Implements the ``vocabulary_`` attribute and the methods
Expand Down
2 changes: 1 addition & 1 deletion skorch/llm/classifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ def generate_logits(self, *, label_id, **kwargs):
return recorded_logits + recorder.recorded_scores[:]


class _LlmBase(BaseEstimator, ClassifierMixin):
class _LlmBase(ClassifierMixin, BaseEstimator):
"""Base class for LLM models

This class handles a few of the checks, as well as the whole prediction
Expand Down
6 changes: 3 additions & 3 deletions skorch/net.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@


# pylint: disable=too-many-instance-attributes
class NeuralNet:
class NeuralNet(BaseEstimator):
# pylint: disable=anomalous-backslash-in-string
"""NeuralNet base class.

Expand Down Expand Up @@ -1992,7 +1992,7 @@ def _get_params_callbacks(self, deep=True):
return params

def get_params(self, deep=True, **kwargs):
params = BaseEstimator.get_params(self, deep=deep, **kwargs)
params = super().get_params(deep=deep, **kwargs)
# Callback parameters are not returned by .get_params, needs
# special treatment.
params_cb = self._get_params_callbacks(deep=deep)
Expand Down Expand Up @@ -2111,7 +2111,7 @@ def set_params(self, **kwargs):
normal_params[key] = val

self._apply_virtual_params(virtual_params)
BaseEstimator.set_params(self, **normal_params)
super().set_params(**normal_params)

for key, val in special_params.items():
if key.endswith('_'):
Expand Down
5 changes: 3 additions & 2 deletions skorch/probabilistic.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import gpytorch
import numpy as np
import torch
from sklearn.base import ClassifierMixin, RegressorMixin

from skorch.net import NeuralNet
from skorch.dataset import ValidSplit
Expand Down Expand Up @@ -391,7 +392,7 @@ def __getstate__(self):
raise pickle.PicklingError(msg) from exc


class _GPRegressorPredictMixin:
class _GPRegressorPredictMixin(RegressorMixin):
"""Mixin class that provides a predict method for GP regressors."""
def predict(self, X, return_std=False, return_cov=False):
"""Returns the predicted mean and optionally standard deviation.
Expand Down Expand Up @@ -778,7 +779,7 @@ def get_gp_binary_clf_doc(doc):
return doc


class GPBinaryClassifier(GPBase):
class GPBinaryClassifier(ClassifierMixin, GPBase):
__doc__ = get_gp_binary_clf_doc(NeuralNet.__doc__)

def __init__(
Expand Down
2 changes: 1 addition & 1 deletion skorch/regressor.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def get_neural_net_reg_doc(doc):


# pylint: disable=missing-docstring
class NeuralNetRegressor(NeuralNet, RegressorMixin):
class NeuralNetRegressor(RegressorMixin, NeuralNet):
__doc__ = get_neural_net_reg_doc(NeuralNet.__doc__)

def __init__(
Expand Down
6 changes: 4 additions & 2 deletions skorch/tests/test_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,7 @@ def test_grid_search_with_slds_works(
self, slds, y, classifier_module):
from sklearn.model_selection import GridSearchCV
from skorch import NeuralNetClassifier
from skorch.utils import to_numpy

net = NeuralNetClassifier(
classifier_module,
Expand All @@ -450,12 +451,13 @@ def test_grid_search_with_slds_works(
gs = GridSearchCV(
net, params, refit=False, cv=3, scoring='accuracy', error_score='raise'
)
gs.fit(slds, y) # does not raise
gs.fit(slds, to_numpy(y)) # does not raise
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not supporting a mixture of NumPy arrays and CPU pytorch arrays, feels like a regression from scikit-learn's side.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For me, the question is: is it an intended change or was it introduced accidentally?

If it's unintended, one way to resolve this would be here:

https://github.com/scikit-learn/scikit-learn/blob/1922303a79aa776768e2ee89bbda5b6eb4dd5d8b/sklearn/utils/_array_api.py#L177

There would need to be another check

  1. if one of the devices is an instance of torch.device
  2. and for this device, device.type == "cpu"
  3. and the other device is "cpu"

it should be allowed.

Copy link
Member

@thomasjpfan thomasjpfan Dec 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like there is already a bug report and a PR to fix it in scikit-learn:

scikit-learn/scikit-learn#29107 (comment)
scikit-learn/scikit-learn#30454


def test_grid_search_with_slds_and_internal_split_works(
self, slds, y, classifier_module):
from sklearn.model_selection import GridSearchCV
from skorch import NeuralNetClassifier
from skorch.utils import to_numpy

net = NeuralNetClassifier(classifier_module)
params = {
Expand All @@ -465,7 +467,7 @@ def test_grid_search_with_slds_and_internal_split_works(
gs = GridSearchCV(
net, params, refit=True, cv=3, scoring='accuracy', error_score='raise'
)
gs.fit(slds, y) # does not raise
gs.fit(slds, to_numpy(y)) # does not raise

def test_grid_search_with_slds_X_and_slds_y(
self, slds, slds_y, classifier_module):
Expand Down
Loading