Meta Models¶
sklego.meta.confusion_balancer.ConfusionBalancer
¶
Bases: BaseEstimator
, MetaEstimatorMixin
, ClassifierMixin
The ConfusionBalancer
estimator attempts to give it's child estimator a more balanced output by learning from
the confusion matrix during training.
The idea is that the confusion matrix calculates \(P(C_i | M_i)\) where \(C_i\) is the actual class and \(M_i\) is the class that the underlying model gives. We use these probabilities to attempt a more balanced prediction by averaging the correction from the confusion matrix with the original probabilities.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
estimator
|
scikit-learn compatible classifier
|
The estimator to be wrapped, it must implement a |
required |
alpha
|
float
|
Hyperparameter which determines how much smoothing to apply. Must be between 0 and 1. |
0.5
|
cfm_smooth
|
float
|
Smoothing parameter for the confusion matrices to ensure zeros don't exist. |
0
|
Attributes:
Name | Type | Description |
---|---|---|
classes_ |
array-like of shape (n_classes,)
|
The target class labels. |
cfm_ |
array-like of shape (n_classes, n_classes)
|
The confusion matrix used for the correction. |
Source code in sklego/meta/confusion_balancer.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
|
fit(X, y)
¶
Fit the underlying estimator on the training data X
and y
, it calculates the confusion matrix,
normalizes it and stores it for later use.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training data. |
required |
y
|
array-like of shape (n_samples,)
|
Target values. |
required |
Returns:
Name | Type | Description |
---|---|---|
self |
ConfusionBalancer
|
The fitted estimator. |
Raises:
Type | Description |
---|---|
ValueError
|
If the underlying estimator does not have a |
Source code in sklego/meta/confusion_balancer.py
predict(X)
¶
Predict most likely class for new data X
using the underlying estimator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples,)
|
The predicted values. |
Source code in sklego/meta/confusion_balancer.py
predict_proba(X)
¶
Predict probabilities for new data X
using the underlying estimator and then applying the confusion matrix
correction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples, n_classes)
|
The predicted values. |
Source code in sklego/meta/confusion_balancer.py
sklego.meta.decay_estimator.DecayEstimator
¶
Bases: BaseEstimator
, MetaEstimatorMixin
Morphs an estimator such that the training weights can be adapted to ensure that points that are far away have less weight.
This meta estimator will only work for estimators that allow a sample_weights
argument in their .fit()
method.
The meta estimator .fit()
method computes the weights to pass to the estimator's .fit()
method.
Warning
It is up to the user to sort the dataset appropriately.
Warning
By default all the checks on the inputs X
and y
are delegated to the wrapped estimator.
To change such behaviour, set check_input
to True
.
Remark that if the check is skipped, then y
should have a shape
attribute, which is
used to extract the number of samples in training data, and compute the weights.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
scikit-learn compatible estimator
|
The estimator to be wrapped. |
required |
decay_func
|
Literal[linear, exponential, stepwise, sigmoid] | Callable[[ndarray, ndarray, ...], ndarray]
|
The decay function to use. Available built-in decay functions are:
Otherwise a callable can be passed and it should accept |
"exponential"
|
check_input
|
bool
|
Whether or not to check the input data. If False, the checks are delegated to the wrapped estimator. |
False
|
decay_kwargs
|
dict | None
|
Keyword arguments to the decay function. |
None
|
Attributes:
Name | Type | Description |
---|---|---|
estimator_ |
scikit-learn compatible estimator
|
The fitted estimator. |
weights_ |
array-like of shape (n_samples,)
|
The weights used to train the estimator. |
classes_ |
array-like of shape (n_classes,)
|
The classes labels. Only present if the wrapped estimator is a classifier. |
Examples:
from sklearn.linear_model import LinearRegression
from sklego.meta import DecayEstimator
decay_estimator = DecayEstimator(
model=LinearRegression(),
decay_func="linear",
min_value=0.1,
max_value=0.9
)
X, y = ...
# Fit the DecayEstimator on the data, this will compute the weights
# and pass them to the wrapped estimator
_ = decay_estimator.fit(X, y)
# At prediction time, the weights are not used
predictions = decay_estimator.predict(X)
# The weights are stored in the `weights_` attribute
weights = decay_estimator.weights_
Source code in sklego/meta/decay_estimator.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
|
fit(X, y)
¶
Fit the underlying estimator on the training data X
and y
using the calculated sample weights.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training data. |
required |
y
|
array-like of shape (n_samples,)
|
Target values. |
required |
Returns:
Name | Type | Description |
---|---|---|
self |
DecayEstimator
|
The fitted estimator. |
Source code in sklego/meta/decay_estimator.py
predict(X)
¶
Predict target values for X
using trained underlying estimator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples,)
|
The predicted values. |
Source code in sklego/meta/decay_estimator.py
sklego.meta.estimator_transformer.EstimatorTransformer
¶
Bases: TransformerMixin
, MetaEstimatorMixin
, BaseEstimator
Allow using an estimator as a transformer in an earlier step of a pipeline.
Warning
By default all the checks on the inputs X
and y
are delegated to the wrapped estimator.
To change such behaviour, set check_input
to True
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
estimator
|
scikit-learn compatible estimator
|
The estimator to be applied to the data, used as transformer. |
required |
predict_func
|
str
|
The method called on the estimator when transforming e.g. ( |
"predict"
|
check_input
|
bool
|
Whether or not to check the input data. If False, the checks are delegated to the wrapped estimator. |
False
|
Attributes:
Name | Type | Description |
---|---|---|
estimator_ |
scikit-learn compatible estimator
|
The fitted underlying estimator. |
multi_output_ |
bool
|
Whether or not the estimator is multi output. |
Source code in sklego/meta/estimator_transformer.py
fit(X, y, **kwargs)
¶
Fit the underlying estimator on training data X
and y
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training data. |
required |
y
|
array-like of shape (n_samples,)
|
Target values. |
required |
**kwargs
|
dict
|
Additional keyword arguments passed to the |
{}
|
Returns:
Name | Type | Description |
---|---|---|
self |
EstimatorTransformer
|
The fitted transformer. |
Source code in sklego/meta/estimator_transformer.py
transform(X)
¶
Transform the data by applying the predict_func
of the fitted estimator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to be transformed. |
required |
Returns:
Name | Type | Description |
---|---|---|
output |
array-like of shape (n_samples,) | (n_samples, n_outputs)
|
The transformed data. Array will be of shape |
Source code in sklego/meta/estimator_transformer.py
sklego.meta.grouped_predictor.GroupedPredictor
¶
Bases: ShrinkageMixin
, 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"
, "equal"
, "min_n_obs"
, "relative"
or a
custom shrinkage function. The shrinkage method is specified by the shrinkage
parameter.
Shrinkage
Shrinkage is only available for regression models.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
estimator
|
scikit-learn compatible estimator/pipeline
|
The estimator/pipeline to be applied per group. |
required |
groups
|
int | str | List[int] | List[str]
|
The column(s) of the array/dataframe to select as a grouping parameter set. |
required |
shrinkage
|
Literal[constant, equal, min_n_obs, relative] | Callable | None
|
How to perform shrinkage:
|
None
|
use_global_model
|
bool
|
|
True
|
check_X
|
bool
|
Whether to validate |
True
|
**shrinkage_kwargs
|
dict
|
Keyword arguments to the shrinkage function |
None
|
Attributes:
Name | Type | Description |
---|---|---|
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 |
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 |
Source code in sklego/meta/grouped_predictor.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 |
|
decision_function(X)
¶
Predict confidence scores for samples in X
.
Warning
Available only if the underlying estimator implements .decision_function()
method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples,) or (n_samples, n_classes)
|
Confidence scores per (n_samples, n_classes) combination. In the binary case, confidence score for self.classes_[1] where > 0 means this class would be predicted. |
Source code in sklego/meta/grouped_predictor.py
fit(X, y=None)
¶
Fit one estimator for each group of training data X
and y
.
Will also learn the groups that exist within the dataset.
If use_global_model=True
a fallback estimator will be fitted on the entire dataset in case a group is not
found during .predict()
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training data. |
required |
y
|
array-like of shape (n_samples,)
|
Target values. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
GroupedPredictor
|
The fitted estimator. |
Source code in sklego/meta/grouped_predictor.py
predict(X)
¶
Predict target values on new data X
by predicting on each group. If a group is not found during
.predict()
and use_global_model=True
the fallback estimator will be used. If use_global_model=False
a
ValueError
will be raised.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples,)
|
Predicted target values. |
Source code in sklego/meta/grouped_predictor.py
predict_proba(X)
¶
Predict probabilities on new data X
.
Warning
Available only if the underlying estimator implements .predict_proba()
method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples, n_classes)
|
Predicted probabilities per class. |
Source code in sklego/meta/grouped_predictor.py
sklego.meta.grouped_predictor.GroupedClassifier
¶
Bases: GroupedPredictor
, ClassifierMixin
GroupedClassifier
is a meta-estimator that fits a separate classifier for each group in the input data.
Its equivalent to GroupedPredictor
with shrinkage=None
but it is available only for classification models.
New in version 0.8.0
Source code in sklego/meta/grouped_predictor.py
fit(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:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training data. |
required |
y
|
array-like of shape (n_samples,)
|
Target values. |
required |
Returns:
Name | Type | Description |
---|---|---|
self |
GroupedClassifier
|
The fitted regressor. |
Raises:
Type | Description |
---|---|
ValueError
|
If the supplied estimator is not a classifier. |
Source code in sklego/meta/grouped_predictor.py
sklego.meta.grouped_predictor.GroupedRegressor
¶
Bases: GroupedPredictor
, RegressorMixin
GroupedRegressor
is a meta-estimator that fits a separate regressor for each group in the input data.
Its spec is the same as GroupedPredictor
but it is available
only for regression models.
New in version 0.8.0
Source code in sklego/meta/grouped_predictor.py
fit(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:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training data. |
required |
y
|
array-like of shape (n_samples,)
|
Target values. |
required |
Returns:
Name | Type | Description |
---|---|---|
self |
GroupedRegressor
|
The fitted regressor. |
Raises:
Type | Description |
---|---|
ValueError
|
If the supplied estimator is not a regressor. |
Source code in sklego/meta/grouped_predictor.py
sklego.meta.grouped_transformer.GroupedTransformer
¶
Bases: TransformerMixin
, MetaEstimatorMixin
, BaseEstimator
Construct a transformer per data group. Splits data by groups from single or multiple columns and transforms remaining columns using the transformers corresponding to the groups.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
transformer
|
scikit-learn compatible transformer
|
The transformer to be applied per group. |
required |
groups
|
int | str | List[int] | List[str] | None
|
The column(s) of the array/dataframe to select as a grouping parameter set. If |
required |
use_global_model
|
bool
|
Whether or not to fall back to a general transformation in case a group is not found during |
True
|
check_X
|
bool
|
Whether or not to check the input data. If False, the checks are delegated to the wrapped estimator. |
True
|
Attributes:
Name | Type | Description |
---|---|---|
transformers_ |
scikit-learn compatible transformer | dict[..., scikit-learn compatible transformer]
|
The fitted transformers per group or a single fitted transformer if |
fallback_ |
scikit-learn compatible transformer | None
|
The fitted transformer to fall back to in case a group is not found during |
Source code in sklego/meta/grouped_transformer.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 |
|
fit(X, y=None)
¶
Fit one transformer for each group of training data X
.
Will also learn the groups that exist within the dataset.
If use_global_model=True
a fallback transformer will be fitted on the entire dataset in case a group is not
found during .transform()
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training data. If |
required |
y
|
array-like of shape (n_samples,)
|
Target values. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
GroupedTransformer
|
The fitted transformer. |
Source code in sklego/meta/grouped_transformer.py
get_feature_names_out()
¶
transform(X)
¶
Transform new data X
by transforming on each group. If a group is not found during .transform()
and
use_global_model=True
the fallback transformer will be used. If use_global_model=False
a ValueError
will
be raised.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Data to transform. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples, n_features)
|
Data transformed per group. |
Source code in sklego/meta/grouped_transformer.py
sklego.meta.ordinal_classification.OrdinalClassifier
¶
Bases: MultiOutputMixin
, ClassifierMixin
, MetaEstimatorMixin
, BaseEstimator
The OrdinalClassifier
allows to use a binary classifier to address an ordinal classification problem.
Suppose we have N ordinal classes to predict, then the original binary classifier is fitted on N-1 by training sets,
each of which represents the samples where y <= y_label
for each y_label
in y
except y.max()
(as every
sample is smaller than the maximum value).
The binary classifiers are then used to predict the probability of each sample to be in each new class
y <= y_label
, and finally the probability of each sample is the difference between two consecutive classes is
computed:
About scikit-learn predict_proba
s
As you can see from the formula above, it is of utmost importance to use proper probabilities to compute the
results. However, not every scikit-learn classifier .predict_proba()
method outputs probabilities (they are
more like a confidence score).
We recommend to use CalibratedClassifierCV
to calibrate the probabilities of the binary classifiers.
You can enable this by setting use_calibration=True
and passing an uncalibrated classifier to the
OrdinalClassifier
or by passing a calibrated classifier to the OrdinalClassifier
constructor.
More on this topic can be found in the scikit-learn documentation.
Computation time
The OrdinalClassifier
is a meta-estimator that fits N-1 binary classifiers. This can be computationally
expensive, especially when using a large number of samples and/or features or a complex classifier.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
estimator
|
scikit-learn compatible classifier
|
The estimator to be applied to the data, used as binary classifier. |
required |
n_jobs
|
int
|
The number of jobs to run in parallel. The same convention of
|
None
|
use_calibration
|
bool
|
Whether or not to calibrate the binary classifiers using |
False
|
calibrarion_kwargs
|
dict | None
|
Keyword arguments to the |
None
|
Attributes:
Name | Type | Description |
---|---|---|
estimators_ |
dict[int, scikit-learn compatible classifier]
|
The fitted underlying binary classifiers. |
classes_ |
np.ndarray of shape (n_classes,)
|
The classes seen during |
n_features_in_ |
int
|
The number of features seen during |
Examples:
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklego.meta import OrdinalClassifier
url = "https://stats.idre.ucla.edu/stat/data/ologit.dta"
df = pd.read_stata(url).assign(apply_codes = lambda t: t["apply"].cat.codes)
target = "apply_codes"
features = [c for c in df.columns if c not in {target, "apply"}]
X, y = df[features].to_numpy(), df[target].to_numpy()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
clf = OrdinalClassifier(LogisticRegression(), n_jobs=-1)
_ = clf.fit(X_train, y_train)
clf.predict_proba(X_test)
Notes
The implementation is based on the paper A simple approach to ordinal classification by Eibe Frank and Mark Hall.
Source code in sklego/meta/ordinal_classification.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
|
n_classes_
property
¶
Number of classes.
fit(X, y)
¶
Fit the OrdinalClassifier
model on training data X
and y
by fitting its underlying estimators on
N-1 datasets X
and y
for each class y_label
in y
except y.max()
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features )
|
The training data. |
required |
y
|
array-like of shape (n_samples,)
|
The target values. |
required |
Returns:
Name | Type | Description |
---|---|---|
self |
OrdinalClassifier
|
Fitted model. |
Raises:
Type | Description |
---|---|
ValueError
|
If the estimator is not a classifier or if it does not implement |
Source code in sklego/meta/ordinal_classification.py
predict(X)
¶
Predict class labels for samples in X
as the class with the highest probability.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples,)
|
The predicted class labels. |
Source code in sklego/meta/ordinal_classification.py
predict_proba(X)
¶
Predict class probabilities for samples in X
. The class probabilities of a sample are computed as the
difference between the probability of the sample to be in class y_label
and the probability of the sample to
be in class y_label - 1
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples, n_classes)
|
The predicted class probabilities. |
Raises:
Type | Description |
---|---|
ValueError
|
If |
Source code in sklego/meta/ordinal_classification.py
sklego.meta.outlier_classifier.OutlierClassifier
¶
Bases: BaseEstimator
, ClassifierMixin
, MetaEstimatorMixin
Morphs an outlier detection model into a classifier.
When an outlier is detected it will output 1 and 0 otherwise. This way you can use familiar metrics again and this allows you to consider outlier models as a fraud detector.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
scikit-learn compatible outlier detection model
|
An outlier detection model that will be used for prediction. |
required |
Attributes:
Name | Type | Description |
---|---|---|
estimator_ |
scikit-learn compatible outlier detection model
|
The fitted underlying outlier detection model. |
classes_ |
array-like of shape (2,)
|
Classes used for prediction (0 or 1) |
Example
from sklearn.ensemble import IsolationForest
from sklego.meta.outlier_classifier import OutlierClassifier
X = [[0], [0.5], [-1], [99]]
y = [0, 0, 0, 1]
isolation_forest = IsolationForest()
outlier_clf = OutlierClassifier(isolation_forest)
_ = outlier_clf.fit(X, y)
preds = outlier_clf.predict([[100], [-0.5], [0.5], [1]])
# array[1. 0. 0. 0.]
proba_preds = outlier_clf.predict_proba([[100], [-0.5], [0.5], [1]])
# [[0.34946567 0.65053433]
# [0.79707913 0.20292087]
# [0.80275406 0.19724594]
# [0.80275406 0.19724594]]
Source code in sklego/meta/outlier_classifier.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 |
|
fit(X, y=None)
¶
Fit the underlying estimator to the training data X
and y
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training data. |
required |
y
|
array-like of shape (n_samples,)
|
Target values. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
OutlierClassifier
|
The fitted estimator. |
Raises:
Type | Description |
---|---|
ValueError
|
|
Source code in sklego/meta/outlier_classifier.py
predict(X)
¶
Predict new data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
np.ndarray of shape (n_samples,)
|
The predicted values. 0 for inliers, 1 for outliers. |
Source code in sklego/meta/outlier_classifier.py
predict_proba(X)
¶
Predict probability estimates for new data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
np.ndarray of shape (n_samples,)
|
The predicted probabilities. |
Source code in sklego/meta/outlier_classifier.py
sklego.meta.regression_outlier_detector.RegressionOutlierDetector
¶
Bases: BaseEstimator
, OutlierMixin
Morphs a regression estimator into one that can detect outliers. We will try to predict column
in X.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
scikit-learn compatible regression model
|
A regression model that will be used for prediction. |
required |
column
|
int | str
|
This should be:
|
required |
lower
|
float
|
Lower threshold for outlier detection. The method used for detection depends on the |
2.0
|
upper
|
float
|
Upper threshold for outlier detection. The method used for detection depends on the |
2.0
|
method
|
Literal[sd, relative, absolute]
|
The method to use for outlier detection.
|
"sd"
|
Attributes:
Name | Type | Description |
---|---|---|
estimator_ |
scikit-learn compatible regression model
|
The fitted underlying regression model. |
sd_ |
float
|
The standard deviation of the differences between true and predicted values. |
idx_ |
int
|
The index of the target column in the input data. |
Notes
Native cross-dataframe support is achieved using Narwhals. Supported dataframes are:
- pandas
- Polars (eager)
- Modin
See Narwhals docs for an up-to-date list (and to learn how you can add your dataframe library to it!), though note that only those supported by sklearn.utils.check_X_y will work with this class.
Source code in sklego/meta/regression_outlier_detector.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
|
fit(X, y=None)
¶
Fit the underlying model on X_to_use
and y
where:
y
is the column we want to predict (X[:, self.column]
)X_to_use
is the rest of the data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training data. |
required |
y
|
array-like of shape (n_samples,)
|
Ignored, present for compatibility. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
RegressionOutlierDetector
|
The fitted estimator. |
Raises:
Type | Description |
---|---|
ValueError
|
If the |
Source code in sklego/meta/regression_outlier_detector.py
predict(X, y=None)
¶
Predict which samples of X
are outliers using the underlying estimator and given method
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
y
|
array-like of shape (n_samples,)
|
Ignored, present for compatibility. |
None
|
Returns:
Type | Description |
---|---|
np.ndarray of shape (n_samples,)
|
The predicted values. 1 for inliers, -1 for outliers. |
Source code in sklego/meta/regression_outlier_detector.py
score_samples(X, y=None)
¶
Calculate the outlier scores for the given data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Data for which outlier scores are calculated. |
required |
y
|
array-like of shape shape=(n_samples,)
|
Ignored, present for compatibility. |
None
|
Returns:
Type | Description |
---|---|
np.ndarray of shape (n_samples,)
|
The outlier scores for the input data. |
Raises:
Type | Description |
---|---|
ValueError
|
If |
Source code in sklego/meta/regression_outlier_detector.py
to_x_y(X)
¶
Split X
into two arrays X_to_use
and y
.
y
is the column we want to predict (specified in the column
parameter) and X_to_use
is the rest of the
data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Data to split. |
required |
Returns:
Name | Type | Description |
---|---|---|
X_to_use |
array-like of shape (n_samples, n_features-1)
|
Data to use for prediction. |
y |
array-like of shape (n_samples,)
|
The target column. |
Source code in sklego/meta/regression_outlier_detector.py
sklego.meta.subjective_classifier.SubjectiveClassifier
¶
Bases: BaseEstimator
, ClassifierMixin
, MetaEstimatorMixin
Corrects predictions of the inner classifier by taking into account a (subjective) prior distribution of the classes.
This can be useful when there is a difference in class distribution between the training data set and the real world. Using the confusion matrix of the inner classifier and the prior, the posterior probability for a class, given the prediction of the inner classifier, can be computed.
The background for this posterior estimation is given in this article.
Based on the evidence
attribute, this meta estimator's predictions are based on simple weighing of the inner
estimator's predict_proba()
results, the posterior probabilities based on the confusion matrix, or a combination
of the two approaches.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
estimator
|
scikit-learn compatible classifier
|
Classifier that will be wrapped with SubjectiveClassifier. It should implement |
required |
prior
|
dict[int, float]
|
A dictionary mapping |
required |
evidence
|
Literal[predict_proba, confusion_matrix, both]
|
A string indicating which evidence should be used to correct the inner estimator's predictions.
|
"both"
|
Attributes:
Name | Type | Description |
---|---|---|
estimator_ |
scikit-learn compatible classifier
|
The fitted classifier. |
classes_ |
array-like, shape=(n_classes,)
|
The classes labels. |
posterior_matrix_ |
array-like, shape=(n_classes, n_classes)
|
The posterior probabilities for each class, given the prediction of the inner classifier. |
Source code in sklego/meta/subjective_classifier.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
|
classes_
property
¶
Alias for .classes_
attribute of the underlying estimator.
fit(X, y)
¶
Fit the inner classfier using X
and y
as training data by fitting the underlying estimator and computing
the posterior probabilities.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features )
|
The training data. |
required |
y
|
array-like of shape (n_samples,)
|
The target values. |
required |
Returns:
Name | Type | Description |
---|---|---|
self |
SubjectiveClassifier
|
The fitted estimator. |
Raises:
Type | Description |
---|---|
ValueError
|
|
Source code in sklego/meta/subjective_classifier.py
predict(X)
¶
Predict target values for X
using fitted estimator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples, )
|
The predicted class. |
Source code in sklego/meta/subjective_classifier.py
predict_proba(X)
¶
Predict probability distribution of the class, based on the provided data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples, n_classes)
|
The predicted probabilities. |
Source code in sklego/meta/subjective_classifier.py
sklego.meta.thresholder.Thresholder
¶
Bases: BaseEstimator
, ClassifierMixin
Takes a binary classifier and moves the threshold. This way you might design the algorithm to only accept a certain class if the probability for it is larger than, say, 90% instead of 50%.
Info
Please note that this only works for binary classification problems.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
scikit-learn compatible classifier
|
Classifier that will be wrapped with Thresholder. It should implement |
required |
threshold
|
float
|
The threshold value to use. |
required |
refit
|
bool
|
|
False
|
check_input
|
bool
|
Whether or not to check the input data. If False, the checks are delegated to the wrapped estimator. |
False
|
Attributes:
Name | Type | Description |
---|---|---|
estimator_ |
scikit-learn compatible classifier
|
The fitted classifier. |
classes_ |
array-like, shape=(2,)
|
The classes labels. |
Source code in sklego/meta/thresholder.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
|
fit(X, y, sample_weight=None)
¶
Fit the underlying estimator using X
and y
as training data. If refit=True
we will always retrain
(a copy of) the estimator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features )
|
The training data. |
required |
y
|
array-like of shape (n_samples,)
|
The target values. |
required |
sample_weight
|
array-like of shape (n_samples, )
|
Individual weights for each sample. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
Thresholder
|
The fitted estimator. |
Raises:
Type | Description |
---|---|
ValueError
|
|
Source code in sklego/meta/thresholder.py
predict(X)
¶
Predict target values for X
using fitted estimator and the given threshold
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples,)
|
The predicted values. |
Source code in sklego/meta/thresholder.py
predict_proba(X)
¶
Alias for .predict_proba()
method of the underlying estimator.
sklego.meta.zero_inflated_regressor.ZeroInflatedRegressor
¶
Bases: BaseEstimator
, RegressorMixin
, MetaEstimatorMixin
A meta regressor for zero-inflated datasets, i.e. the targets contain a lot of zeroes.
ZeroInflatedRegressor
consists of a classifier and a regressor.
- The classifier's task is to find if the target is zero or not.
- The regressor's task is to output a (usually positive) prediction whenever the classifier indicates that there should be a non-zero prediction.
The regressor is only trained on examples where the target is non-zero, which makes it easier for it to focus.
At prediction time, the classifier is first asked if the output should be zero. If yes, output zero. Otherwise, ask the regressor for its prediction and output it.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
classifier
|
scikit-learn compatible classifier
|
A classifier that answers the question "Should the output be zero?". |
required |
regressor
|
scikit-learn compatible regressor
|
A regressor for predicting the target. Its prediction is only used if |
required |
handle_zero
|
Literal[error, ignore]
|
|
"error"
|
Attributes:
Name | Type | Description |
---|---|---|
classifier_ |
scikit-learn compatible classifier
|
The fitted classifier. |
regressor_ |
scikit-learn compatible regressor
|
The fitted regressor. |
Examples:
import numpy as np
from sklearn.ensemble import ExtraTreesClassifier, ExtraTreesRegressor
from sklego.meta import ZeroInflatedRegressor
np.random.seed(0)
X = np.random.randn(10000, 4)
y = ((X[:, 0]>0) & (X[:, 1]>0)) * np.abs(X[:, 2] * X[:, 3]**2)
model = ZeroInflatedRegressor(
classifier=ExtraTreesClassifier(random_state=0, max_depth=10),
regressor=ExtraTreesRegressor(random_state=0)
).fit(X, y)
model.predict(X[:5])
# array([4.91483294, 0. , 0. , 0.04941909, 0. ])
model.score_samples(X[:5]).round(2)
# array([3.73, 0. , 0.11, 0.03, 0.06])
Source code in sklego/meta/zero_inflated_regressor.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 |
|
fit(X, y, sample_weight=None)
¶
Fit the underlying classifier and regressor using X
and y
as training data. The regressor is only trained
on examples where the target is non-zero.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features )
|
The training data. |
required |
y
|
array-like of shape (n_samples,)
|
The target values. |
required |
sample_weight
|
array-like of shape (n_samples, )
|
Individual weights for each sample. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
ZeroInflatedRegressor
|
The fitted estimator. |
Raises:
Type | Description |
---|---|
ValueError
|
If |
Source code in sklego/meta/zero_inflated_regressor.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
|
predict(X)
¶
Predict target values for X
using fitted estimator by first asking the classifier if the output should be
zero. If yes, output zero. Otherwise, ask the regressor for its prediction and output it.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples,)
|
The predicted values. |
Source code in sklego/meta/zero_inflated_regressor.py
score_samples(X)
¶
Predict risk estimate of X
as the probability of X
to not be zero times the expected value of X
:
where:
- \(P(X=0)\) is calculated using the
.predict_proba()
method of the underlying classifier. - \(E[X]\) is the regressor prediction on
X
.
Info
This method requires the underlying classifier to implement .predict_proba()
method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples,)
|
The predicted risk. |
Source code in sklego/meta/zero_inflated_regressor.py
sklego.meta.hierarchical_predictor.HierarchicalPredictor
¶
Bases: ShrinkageMixin
, MetaEstimatorMixin
, BaseEstimator
HierarchicalPredictor
is a meta-estimator that fits a separate estimator for each group in the input data
in a hierarchical manner. This means that an estimator is fitted for each level of the group columns.
The only exception to that is when shrinkage=None
and fallback_method="raise"
, in which case only
one estimator per group value is fitted.
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"
, "equal"
, "min_n_obs"
, "relative"
or a
custom shrinkage function.
Differences with GroupedPredictor
There are two main differences between HierarchicalPredictor
and
GroupedPredictor
:
-
The first difference is the fallback method:
HierarchicalPredictor
has a fallback method that can be set to"parent"
or"raise"
. If set to"parent"
, the estimator will recursively fall back to the parent group in case the group value is not found during.predict()
.As a consequence of this:
groups
order matters!- Potentially a combinatoric number of estimators are fitted, one for each unique combination of group values and each level.
-
HierarchicalPredictor
is meant to properly handle shrinkage in classification tasks. However this requires that the estimator has a.predict_proba()
method.
Inheritance
This class is not meant to be used directly, but to be inherited by a specific hierarchical predictor, such as
HierarchicalRegressor
or HierarchicalClassifier
, which properly implement the .predict()
and
predict
-like methods for the specific task.
New in version 0.8.0
Parameters:
Name | Type | Description | Default |
---|---|---|---|
estimator
|
scikit-learn compatible estimator/pipeline
|
The base estimator to be used for each level. |
required |
groups
|
int | str | List[int] | List[str]
|
The column(s) of the array/dataframe to select as a grouping parameter set. |
required |
shrinkage
|
Literal[constant, equal, min_n_obs, relative] | Callable | None
|
How to perform shrinkage:
|
None
|
fallback_method
|
Literal[parent, 'raise']
|
The fallback strategy to use if a group is not found at prediction time:
|
"parent"
|
n_jobs
|
int | None
|
The number of jobs to run in parallel. The same convention of
|
None
|
check_X
|
bool
|
Whether to validate |
True
|
shrinkage_kwargs
|
dict
|
Keyword arguments to the shrinkage function |
None
|
Attributes:
Name | Type | Description |
---|---|---|
estimators_ |
dict[tuple[Any,...], scikit-learn compatible estimator/pipeline]
|
Fitted estimators for each level. The keys are the group values, and the values are the fitted estimators. The group values are tuples of the group columns, including the global column which has a fixed placeholder value of 1. Let's say we have two group columns, |
shrinkage_function_ |
callable
|
The shrinkage function that is used to calculate the shrinkage factors |
shrinkage_factors_ |
dict[tuple[Any, ...], ndarray]
|
Shrinkage factors applied to each level. The keys are the group values, and the values are the shrinkage factors. The group values are tuples of the group columns, including the global column which has a fixed placeholder value of 1. |
groups_ |
list
|
List of all group columns including a global column. |
n_groups_ |
int
|
Number of unique groups. |
n_features_in_ |
int
|
Number of features in the training data. |
n_features_ |
int
|
Number of features used by the estimators. |
n_levels_ |
int
|
Number of hierarchical levels in the grouping. |
Source code in sklego/meta/hierarchical_predictor.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 |
|
fit(X, y=None)
¶
Fit one estimator for each hierarchical group of training data X
and y
.
Will also learn the groups that exist within the training dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training data. |
required |
y
|
array-like of shape (n_samples,)
|
Target values, if applicable. |
None
|
Returns:
Name | Type | Description |
---|---|---|
self |
BaseHierarchicalEstimator
|
The fitted estimator. |
Raises:
Type | Description |
---|---|
ValueError
|
|
Source code in sklego/meta/hierarchical_predictor.py
sklego.meta.hierarchical_predictor.HierarchicalClassifier
¶
Bases: HierarchicalPredictor
, ClassifierMixin
A hierarchical classifier that predicts labels using hierarchical grouping.
This class extends HierarchicalPredictor
and adds
functionality specific to regression tasks.
Its spec is the same as HierarchicalPredictor
, with additional checks to ensure that the supplied estimator is a
classifier that implements the .predict_proba()
method.
.predict_proba(..)
method required!
In order to use shrinkage with classification tasks, we require the estimator to have .predict_proba()
method.
The only way to blend the predictions of the group-level models is by using the probabilities of each class,
and not the labels themselves.
New in version 0.8.0
Examples:
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklego.meta import HierarchicalClassifier
X, y = make_classification(n_samples=1000, n_features=10, n_informative=3, random_state=42)
X = pd.DataFrame(X, columns=[f"x_{i}" for i in range(X.shape[1])]).assign(
g_1 = ['A'] * 500 + ['B'] * 500,
g_2 = ['X'] * 250 + ['Y'] * 250 + ['Z'] * 250 + ['W'] * 250
)
groups = ["g_1", "g_2"]
hc = HierarchicalClassifier(
estimator=LogisticRegression(),
groups=groups
).fit(X, y)
hc.estimators_
{
(1,): LogisticRegression(), # global estimator
(1, 'A'): LogisticRegression(), # estimator for `g_1 = 'A'`
(1, 'B'): LogisticRegression(), # estimator for `g_1 = 'B'`
(1, 'A', 'X'): LogisticRegression(), # estimator for `(g_1, g_2) = ('A', 'X`)`
(1, 'A', 'Y'): LogisticRegression(), # estimator for `(g_1, g_2) = ('A', 'Y`)`
(1, 'B', 'W'): LogisticRegression(), # estimator for `(g_1, g_2) = ('B', 'W`)`
(1, 'B', 'Z'): LogisticRegression(), # estimator for `(g_1, g_2) = ('B', 'Z`)`
}
As we can see, the estimators are fitted for each level of the group columns. The trailing (1,) is the global estimator, which is fitted on the entire dataset.
If we try to predict a sample in which (g_1, g_2) = ('B', 'X')
, this will fallback to the estimator (1, 'B')
.
when fallback_method="parent"
or will raise a KeyError when fallback_method="raise"
.
As one would expect, estimator
can be a pipeline, and the pipeline will be fitted on each level of the group:
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
hc = HierarchicalClassifier(
estimator=Pipeline([
('scaler', StandardScaler()),
('model', LogisticRegression())
]),
groups=groups
).fit(X, y)
Source code in sklego/meta/hierarchical_predictor.py
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 |
|
decision_function(X)
¶
Predict confidence scores for samples in X
.
Warning
Available only if the underlying estimator implements .decision_function()
method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples,) or (n_samples, n_classes)
|
Confidence scores per (n_samples, n_classes) combination. In the binary case, confidence score for self.classes_[1] where > 0 means this class would be predicted. |
Source code in sklego/meta/hierarchical_predictor.py
fit(X, y)
¶
Fit one classifier for each hierarchical group of training data X
and y
.
Will also learn the groups that exist within the training dataset, the classes and the number of classes in the target values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training data. |
required |
y
|
array-like of shape (n_samples,)
|
Target values. |
required |
Returns:
Name | Type | Description |
---|---|---|
self |
HierarchicalClassifier
|
The fitted classifier. |
Raises:
Type | Description |
---|---|
ValueError
|
If the supplied estimator is not a classifier. |
Source code in sklego/meta/hierarchical_predictor.py
predict(X)
¶
Predict class labels for samples in X
as the class with the highest probability.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples,)
|
The predicted class labels. |
Source code in sklego/meta/hierarchical_predictor.py
predict_proba(X)
¶
Predict probabilities for each class on new data X
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples, n_classes)
|
Predicted probabilities per class. |
Source code in sklego/meta/hierarchical_predictor.py
sklego.meta.hierarchical_predictor.HierarchicalRegressor
¶
Bases: HierarchicalPredictor
, RegressorMixin
A hierarchical regressor that predicts values using hierarchical grouping.
This class extends HierarchicalPredictor
and adds
functionality specific to regression tasks.
Its spec is the same as HierarchicalPredictor
, with additional checks to ensure that the supplied estimator is a
regressor.
New in version 0.8.0
Examples:
import pandas as pd
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklego.meta import HierarchicalRegressor
X, y = make_regression(n_samples=1000, n_features=10, n_informative=3, random_state=42)
X = pd.DataFrame(X, columns=[f"x_{i}" for i in range(X.shape[1])]).assign(
g_1 = ['A'] * 500 + ['B'] * 500,
g_2 = ['X'] * 250 + ['Y'] * 250 + ['Z'] * 250 + ['W'] * 250
)
groups = ["g_1", "g_2"]
hr = HierarchicalRegressor(
estimator=LinearRegression(),
groups=groups
).fit(X, y)
hr.estimators_
{
(1,): LinearRegression(), # global estimator
(1, 'A'): LinearRegression(), # estimator for `g_1 = 'A'`
(1, 'B'): LinearRegression(), # estimator for `g_1 = 'B'`
(1, 'A', 'X'): LinearRegression(), # estimator for `(g_1, g_2) = ('A', 'X`)`
(1, 'A', 'Y'): LinearRegression(), # estimator for `(g_1, g_2) = ('A', 'Y`)`
(1, 'B', 'W'): LinearRegression(), # estimator for `(g_1, g_2) = ('B', 'W`)`
(1, 'B', 'Z'): LinearRegression(), # estimator for `(g_1, g_2) = ('B', 'Z`)`
}
As we can see, the estimators are fitted for each level of the group columns. The trailing (1,) is the global estimator, which is fitted on the entire dataset.
If we try to predict a sample in which (g_1, g_2) = ('B', 'X')
, this will fallback to the estimator (1, 'B')
.
when fallback_method="parent"
or will raise a KeyError when fallback_method="raise"
.
As one would expect, estimator
can be a pipeline, and the pipeline will be fitted on each level of the group:
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
hr = HierarchicalRegressor(
estimator=Pipeline([
('scaler', StandardScaler()),
('model', LinearRegression())
]),
groups=groups
).fit(X, y)
Source code in sklego/meta/hierarchical_predictor.py
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 |
|
fit(X, y)
¶
Fit one regressor for each hierarchical group of training data X
and y
.
Will also learn the groups that exist within the training dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
Training data. |
required |
y
|
array-like of shape (n_samples,)
|
Target values. |
required |
Returns:
Name | Type | Description |
---|---|---|
self |
HierarchicalRegressor
|
The fitted regressor. |
Raises:
Type | Description |
---|---|
ValueError
|
If the supplied estimator is not a regressor. |
Source code in sklego/meta/hierarchical_predictor.py
predict(X)
¶
Predict regression values for new data X
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X
|
array-like of shape (n_samples, n_features)
|
The data to predict. |
required |
Returns:
Type | Description |
---|---|
array-like of shape (n_samples,)
|
Predicted regression values. |