-
Notifications
You must be signed in to change notification settings - Fork 121
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
GroupedPredictor
patch
#619
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
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
There are no files selected for viewing
This file contains 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 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 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 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 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 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 was deleted.
Oops, something went wrong.
This file contains 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 |
---|---|---|
@@ -1,7 +1,7 @@ | ||
import numpy as np | ||
import pandas as pd | ||
from sklearn import clone | ||
from sklearn.base import BaseEstimator, is_classifier | ||
from sklearn.base import BaseEstimator, ClassifierMixin, MetaEstimatorMixin, RegressorMixin, is_classifier, is_regressor | ||
from sklearn.utils.metaestimators import available_if | ||
from sklearn.utils.validation import check_array, check_is_fitted | ||
|
||
|
@@ -14,9 +14,21 @@ | |
) | ||
|
||
|
||
class GroupedPredictor(BaseEstimator): | ||
"""Construct an estimator per data group. Splits data by values of a single column and fits one estimator per such | ||
column. | ||
class GroupedPredictor(MetaEstimatorMixin, BaseEstimator): | ||
"""`GroupedPredictor` is a meta-estimator that fits a separate estimator for each group in the input data. | ||
|
||
The input data is split into a group and a value part: for each unique combination of the group columns, a separate | ||
estimator is fitted to the corresponding value rows. The group columns are specified by the `groups` parameter. | ||
|
||
If `use_global_model=True` a fallback estimator will be fitted on the entire dataset in case a group is not found | ||
during `.predict()`. | ||
|
||
If `shrinkage` is not `None`, the predictions of the group-level models are combined using a shrinkage method. The | ||
shrinkage method can be one of the predefined methods `"constant"`, `"min_n_obs"`, `"relative"` or a custom | ||
shrinkage function. The shrinkage method is specified by the `shrinkage` parameter. | ||
|
||
!!! warning "Shrinkage" | ||
Shrinkage is only available for regression models. | ||
|
||
Parameters | ||
---------- | ||
|
@@ -43,6 +55,19 @@ class GroupedPredictor(BaseEstimator): | |
If disabled, the model/pipeline is expected to handle e.g. missing, non-numeric, or non-finite values. | ||
**shrinkage_kwargs : dict | ||
Keyword arguments to the shrinkage function | ||
|
||
Attributes | ||
---------- | ||
estimators_ : dict | ||
A dictionary with the fitted estimators per group | ||
groups_ : list | ||
A list of all the groups that were found during fitting | ||
fallback_ : estimator | ||
A fallback estimator that is used when `use_global_model=True` and a group is not found during `.predict()` | ||
shrinkage_function_ : callable | ||
The shrinkage function that is used to calculate the shrinkage factors | ||
shrinkage_factors_ : dict | ||
A dictionary with the shrinkage factors per group | ||
""" | ||
|
||
# Number of features in value df can be 0, e.g. for dummy models | ||
|
@@ -212,6 +237,9 @@ def fit(self, X, y=None): | |
self : GroupedPredictor | ||
The fitted estimator. | ||
""" | ||
if self.shrinkage is not None and not is_regressor(self.estimator): | ||
raise ValueError("Shrinkage is only available for regression models") | ||
|
||
X_group, X_value = _split_groups_and_values( | ||
X, self.groups, min_value_cols=0, check_X=self.check_X, **self._check_kwargs | ||
) | ||
|
@@ -409,3 +437,99 @@ def decision_function(self, X): | |
return self.__predict_groups(X_group, X_value, method="decision_function") | ||
else: | ||
return self.__predict_shrinkage_groups(X_group, X_value, method="decision_function") | ||
|
||
@property | ||
def _estimator_type(self): | ||
"""Computes `_estimator_type` dynamically from the wrapped model.""" | ||
return self.estimator._estimator_type | ||
|
||
|
||
class GroupedRegressor(GroupedPredictor, RegressorMixin): | ||
FBruzzesi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""`GroupedRegressor` is a meta-estimator that fits a separate regressor for each group in the input data. | ||
|
||
Its spec is the same as [`GroupedPredictor`][sklego.meta.grouped_predictor.GroupedPredictor] but it is available | ||
only for regression models. | ||
|
||
!!! info "New in version 0.7.5" | ||
""" | ||
|
||
def fit(self, X, y): | ||
"""Fit one regressor for each group of training data `X` and `y`. | ||
|
||
Will also learn the groups that exist within the training dataset. | ||
|
||
Parameters | ||
---------- | ||
X : array-like of shape (n_samples, n_features) | ||
Training data. | ||
y : array-like of shape (n_samples,) | ||
Target values. | ||
|
||
Returns | ||
------- | ||
self : GroupedRegressor | ||
The fitted regressor. | ||
|
||
Raises | ||
------- | ||
ValueError | ||
If the supplied estimator is not a regressor. | ||
""" | ||
if not is_regressor(self.estimator): | ||
raise ValueError("GroupedRegressor is only available for regression models") | ||
|
||
return super().fit(X, y) | ||
|
||
|
||
class GroupedClassifier(GroupedPredictor, ClassifierMixin): | ||
FBruzzesi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""`GroupedClassifier` is a meta-estimator that fits a separate classifier for each group in the input data. | ||
|
||
Its equivalent to [`GroupedPredictor`][sklego.meta.grouped_predictor.GroupedPredictor] with `shrinkage=None` | ||
but it is available only for classification models. | ||
|
||
!!! info "New in version 0.7.5" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
""" | ||
|
||
def __init__( | ||
self, | ||
estimator, | ||
groups, | ||
use_global_model=True, | ||
check_X=True, | ||
**shrinkage_kwargs, | ||
): | ||
super().__init__( | ||
estimator=estimator, | ||
groups=groups, | ||
shrinkage=None, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Forcing shrinkage to be None |
||
use_global_model=use_global_model, | ||
check_X=check_X, | ||
) | ||
|
||
def fit(self, X, y): | ||
"""Fit one classifier for each group of training data `X` and `y`. | ||
|
||
Will also learn the groups that exist within the training dataset. | ||
|
||
Parameters | ||
---------- | ||
X : array-like of shape (n_samples, n_features) | ||
Training data. | ||
y : array-like of shape (n_samples,) | ||
Target values. | ||
|
||
Returns | ||
------- | ||
self : GroupedClassifier | ||
The fitted regressor. | ||
|
||
Raises | ||
------- | ||
ValueError | ||
If the supplied estimator is not a classifier. | ||
""" | ||
|
||
if not is_classifier(self.estimator): | ||
raise ValueError("GroupedClassifier is only available for classification models") | ||
self.classes_ = np.unique(y) | ||
return super().fit(X, y) |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we want to mention the classifier/regressor objects in the docs here maybe?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sounds reasonable