-
Notifications
You must be signed in to change notification settings - Fork 56
Add multi-output classifier support and refresh examples #207
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
Open
noahho
wants to merge
11
commits into
main
Choose a base branch
from
codex/create-example-for-multioutput-prediction-with-imputation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
c019ef6
Add multi-output classifier support and refresh examples
noahho 45c8c25
Fix multi-output wrappers cloning and tests
noahho 013dd39
Merge branch 'main' into codex/create-example-for-multioutput-predict…
noahho ba93368
- fix codex
3a203c8
- fix codex
c8496e5
- fix codex
be0c93b
- fix codex
aabe063
Update src/tabpfn_extensions/multioutput.py
noahho 9863448
Update src/tabpfn_extensions/multioutput.py
noahho cd3c249
Update src/tabpfn_extensions/multioutput.py
noahho 61e4b68
Merge branch 'main' into codex/create-example-for-multioutput-predict…
noahho 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
Some comments aren't visible on the classic Files Changed page.
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,74 @@ | ||
| """Multi-output prediction workflows for TabPFN.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import numpy as np | ||
| from sklearn.datasets import make_multilabel_classification, make_regression | ||
| from sklearn.metrics import r2_score, roc_auc_score | ||
| from sklearn.model_selection import train_test_split | ||
|
|
||
| from tabpfn_extensions.multioutput import ( | ||
| TabPFNMultiOutputClassifier, | ||
| TabPFNMultiOutputRegressor, | ||
| ) | ||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # 1. Multi-output regression with missing features | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
| X_reg, y_reg = make_regression( | ||
| n_samples=120, | ||
| n_features=6, | ||
| n_targets=2, | ||
| n_informative=6, | ||
| noise=0.05, | ||
| random_state=0, | ||
| ) | ||
|
noahho marked this conversation as resolved.
|
||
|
|
||
| X_reg_train, X_reg_test, y_reg_train, y_reg_test = train_test_split( | ||
| X_reg, y_reg, test_size=0.3, random_state=42 | ||
| ) | ||
|
|
||
| regressor = TabPFNMultiOutputRegressor(n_estimators=4) | ||
| regressor.fit(X_reg_train, y_reg_train) | ||
|
|
||
| reg_predictions = regressor.predict(X_reg_test) | ||
| print("Regression predictions shape:", reg_predictions.shape) | ||
|
|
||
| r2_per_target = [ | ||
| r2_score(y_reg_test[:, i], reg_predictions[:, i]) | ||
| for i in range(reg_predictions.shape[1]) | ||
| ] | ||
|
noahho marked this conversation as resolved.
|
||
| print("Regression R2 per target:", r2_per_target) | ||
| print( | ||
| "Regression average R2:", | ||
| r2_score(y_reg_test, reg_predictions, multioutput="uniform_average"), | ||
| ) | ||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # 2. Multi-output classification (multi-label) with the same wrapper pattern | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
| X_clf, y_clf = make_multilabel_classification( | ||
| n_samples=150, | ||
| n_features=6, | ||
| n_classes=3, | ||
| n_labels=2, | ||
| allow_unlabeled=False, | ||
| random_state=1, | ||
| ) | ||
|
|
||
| X_clf = X_clf.astype(np.float32) | ||
|
noahho marked this conversation as resolved.
|
||
|
|
||
| X_clf_train, X_clf_test, y_clf_train, y_clf_test = train_test_split( | ||
| X_clf, y_clf, test_size=0.3, random_state=42 | ||
| ) | ||
|
|
||
| classifier = TabPFNMultiOutputClassifier(n_estimators=4) | ||
| classifier.fit(X_clf_train, y_clf_train) | ||
|
|
||
| clf_predictions = classifier.predict_proba(X_clf_test) | ||
| print("Classification predictions shape:", clf_predictions.shape) | ||
|
|
||
| micro_roc_auc = roc_auc_score(y_clf_test, clf_predictions, average="micro") | ||
| print("Classification micro-ROC-AUC:", micro_roc_auc) | ||
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,75 @@ | ||
| """Wrapper for multi-output learning with TabPFN.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Any, TypeVar | ||
|
|
||
| from sklearn.multioutput import MultiOutputClassifier, MultiOutputRegressor | ||
|
|
||
| from .utils import TabPFNClassifier, TabPFNRegressor | ||
|
|
||
| _EstimatorT = TypeVar("_EstimatorT") | ||
|
|
||
|
|
||
| class _TabPFNMultiOutputMixin: | ||
| """Shared initialisation logic for TabPFN multi-output wrappers.""" | ||
|
|
||
| _tabpfn_estimator_cls: type[_EstimatorT] | ||
|
|
||
| def __init__( | ||
| self, | ||
| estimator: _EstimatorT | None = None, | ||
| *, | ||
| n_preprocessing_jobs: int | None = None, | ||
| **tabpfn_params: Any, | ||
| ) -> None: | ||
| if estimator is not None and tabpfn_params: | ||
| msg = "Provide either a custom estimator or tabpfn_params, not both." | ||
| raise ValueError(msg) | ||
|
|
||
| self._estimator_is_default = estimator is None | ||
| self.tabpfn_params = dict(tabpfn_params) if self._estimator_is_default else {} | ||
|
|
||
| if self._estimator_is_default: | ||
| estimator = self._tabpfn_estimator_cls(**tabpfn_params) | ||
|
|
||
| super().__init__(estimator=estimator, n_jobs=n_jobs) | ||
|
|
||
| def get_params( | ||
| self, deep: bool = True | ||
| ) -> dict[str, Any]: # pragma: no cover - delegating to sklearn | ||
| """Return parameters for this estimator with TabPFN kwargs included.""" | ||
| params = super().get_params(deep=deep) | ||
| if self._estimator_is_default: | ||
| params.pop("estimator", None) | ||
| params.update(self.tabpfn_params) | ||
| return params | ||
|
|
||
| def set_params( | ||
| self, **params: Any | ||
| ) -> _TabPFNMultiOutputMixin: # pragma: no cover - delegating to sklearn | ||
| """Update parameters while keeping TabPFN kwargs in sync.""" | ||
| if getattr(self, "_estimator_is_default", False): | ||
| tabpfn_updates: dict[str, Any] = {} | ||
| for key in list(params): | ||
| if key in {"estimator", "n_jobs"}: | ||
| continue | ||
| tabpfn_updates[key] = params.pop(key) | ||
|
|
||
| if tabpfn_updates: | ||
| self.tabpfn_params.update(tabpfn_updates) | ||
| self.estimator = self._tabpfn_estimator_cls(**self.tabpfn_params) | ||
|
|
||
| return super().set_params(**params) | ||
|
|
||
|
|
||
| class TabPFNMultiOutputRegressor(_TabPFNMultiOutputMixin, MultiOutputRegressor): | ||
| """A lightweight multi-output wrapper around :class:`TabPFNRegressor`.""" | ||
|
|
||
| _tabpfn_estimator_cls = TabPFNRegressor | ||
|
|
||
|
|
||
| class TabPFNMultiOutputClassifier(_TabPFNMultiOutputMixin, MultiOutputClassifier): | ||
| """A lightweight multi-output wrapper around :class:`TabPFNClassifier`.""" | ||
|
|
||
| _tabpfn_estimator_cls = TabPFNClassifier | ||
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,44 @@ | ||
| """Tests for the multi-output TabPFN wrappers.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import numpy as np | ||
| import pytest | ||
| from sklearn.base import clone | ||
| from sklearn.datasets import make_regression | ||
| from sklearn.metrics import r2_score | ||
|
|
||
| from tabpfn_extensions.multioutput import ( | ||
| TabPFNMultiOutputRegressor, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.client_compatible | ||
| @pytest.mark.local_compatible | ||
| def test_multioutput_regression(backend): | ||
| """TabPFN kwargs should be cloneable when estimator is created internally.""" | ||
| X, y = make_regression( | ||
| n_samples=30, | ||
| n_features=4, | ||
| n_targets=2, | ||
| n_informative=4, | ||
| noise=0.2, | ||
| random_state=1, | ||
| ) | ||
|
noahho marked this conversation as resolved.
|
||
| model = TabPFNMultiOutputRegressor() | ||
|
|
||
| model.fit(X, y) | ||
| predictions = model.predict(X) | ||
|
|
||
| assert predictions.shape == y.shape | ||
| assert np.isfinite(predictions).all() | ||
|
|
||
| cloned_model = clone(model) | ||
| cloned_model.fit(X, y) | ||
| cloned_predictions = cloned_model.predict(X) | ||
|
|
||
| assert cloned_predictions.shape == y.shape | ||
| assert np.isfinite(cloned_predictions).all() | ||
|
|
||
| cloned_score = r2_score(y, cloned_predictions, multioutput="uniform_average") | ||
| assert cloned_score > 0.2 | ||
|
noahho marked this conversation as resolved.
|
||
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.
Uh oh!
There was an error while loading. Please reload this page.