Custom extensions of sklearn functionalities
Custom expansions of sklearn
functionalities.
Note
This module provides custom expansions of some sklearn
classes and
functions which are necessary to fit the purposes for the desired
functionalities of the MLR module. As
long-term goal we would like to include these functionalities to the
sklearn
package since we believe these additions might be helpful for
everyone. This module serves as interim solution. To ensure that all features
are properly working this module is also covered by extensive tests.
Parts of this code have been copied from sklearn
.
License: BSD 3-Clause License
Copyright (c) 2007-2020 The scikit-learn developers. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- class esmvaltool.diag_scripts.mlr.custom_sklearn.AdvancedPipeline(steps, *, memory=None, verbose=False)[source]
Bases:
Pipeline
Expand
sklearn.pipeline.Pipeline
.- property classes_
The classes labels. Only exist if the last step is a classifier.
- property coef_
Model coefficients.
- Type
- decision_function(X)
Transform the data, and apply decision_function with the final estimator.
Call transform of each transformer in the pipeline. The transformed data are finally passed to the final estimator that calls decision_function method. Only valid if the final estimator implements decision_function.
- Parameters
X (iterable) – Data to predict on. Must fulfill input requirements of first step of the pipeline.
- Returns
y_score – Result of calling decision_function on the final estimator.
- Return type
ndarray of shape (n_samples, n_classes)
- property feature_importances_
Feature importances.
- Type
- property feature_names_in_
Names of features seen during first step fit method.
- fit(X, y=None, **fit_params)
Fit the model.
Fit all the transformers one after the other and transform the data. Finally, fit the transformed data using the final estimator.
- Parameters
X (iterable) – Training data. Must fulfill input requirements of first step of the pipeline.
y (iterable, default=None) – Training targets. Must fulfill label requirements for all steps of the pipeline.
**fit_params (dict of string -> object) – Parameters passed to the
fit
method of each step, where each parameter name is prefixed such that parameterp
for steps
has keys__p
.
- Returns
self – Pipeline with fitted steps.
- Return type
- fit_predict(X, y=None, **fit_params)
Transform the data, and apply fit_predict with the final estimator.
Call fit_transform of each transformer in the pipeline. The transformed data are finally passed to the final estimator that calls fit_predict method. Only valid if the final estimator implements fit_predict.
- Parameters
X (iterable) – Training data. Must fulfill input requirements of first step of the pipeline.
y (iterable, default=None) – Training targets. Must fulfill label requirements for all steps of the pipeline.
**fit_params (dict of string -> object) – Parameters passed to the
fit
method of each step, where each parameter name is prefixed such that parameterp
for steps
has keys__p
.
- Returns
y_pred – Result of calling fit_predict on the final estimator.
- Return type
ndarray
- fit_target_transformer_only(y_data, **fit_kwargs)[source]
Fit only
transform
step of of target regressor.
- fit_transform(X, y=None, **fit_params)
Fit the model and transform with the final estimator.
Fits all the transformers one after the other and transform the data. Then uses fit_transform on transformed data with the final estimator.
- Parameters
X (iterable) – Training data. Must fulfill input requirements of first step of the pipeline.
y (iterable, default=None) – Training targets. Must fulfill label requirements for all steps of the pipeline.
**fit_params (dict of string -> object) – Parameters passed to the
fit
method of each step, where each parameter name is prefixed such that parameterp
for steps
has keys__p
.
- Returns
Xt – Transformed samples.
- Return type
ndarray of shape (n_samples, n_transformed_features)
- get_feature_names_out(input_features=None)
Get output feature names for transformation.
Transform input features using the pipeline.
- Parameters
input_features (array-like of str or None, default=None) – Input features.
- Returns
feature_names_out – Transformed feature names.
- Return type
ndarray of str objects
- get_params(deep=True)
Get parameters for this estimator.
Returns the parameters given in the constructor as well as the estimators contained within the steps of the Pipeline.
- Parameters
deep (bool, default=True) – If True, will return the parameters for this estimator and contained subobjects that are estimators.
- Returns
params – Parameter names mapped to their values.
- Return type
mapping of string to any
- inverse_transform(Xt)
Apply inverse_transform for each step in a reverse order.
All estimators in the pipeline must support inverse_transform.
- Parameters
Xt (array-like of shape (n_samples, n_transformed_features)) – Data samples, where
n_samples
is the number of samples andn_features
is the number of features. Must fulfill input requirements of last step of pipeline’sinverse_transform
method.- Returns
Xt – Inverse transformed data, that is, data in the original feature space.
- Return type
ndarray of shape (n_samples, n_features)
- property n_features_in_
Number of features seen during first step fit method.
- property named_steps
Access the steps by name.
Read-only attribute to access any step by given name. Keys are steps names and values are the steps objects.
- predict(X, **predict_params)
Transform the data, and apply predict with the final estimator.
Call transform of each transformer in the pipeline. The transformed data are finally passed to the final estimator that calls predict method. Only valid if the final estimator implements predict.
- Parameters
X (iterable) – Data to predict on. Must fulfill input requirements of first step of the pipeline.
**predict_params (dict of string -> object) –
Parameters to the
predict
called at the end of all transformations in the pipeline. Note that while this may be used to return uncertainties from some models with return_std or return_cov, uncertainties that are generated by the transformations in the pipeline are not propagated to the final estimator.New in version 0.20.
- Returns
y_pred – Result of calling predict on the final estimator.
- Return type
ndarray
- predict_log_proba(X, **predict_log_proba_params)
Transform the data, and apply predict_log_proba with the final estimator.
Call transform of each transformer in the pipeline. The transformed data are finally passed to the final estimator that calls predict_log_proba method. Only valid if the final estimator implements predict_log_proba.
- Parameters
X (iterable) – Data to predict on. Must fulfill input requirements of first step of the pipeline.
**predict_log_proba_params (dict of string -> object) – Parameters to the
predict_log_proba
called at the end of all transformations in the pipeline.
- Returns
y_log_proba – Result of calling predict_log_proba on the final estimator.
- Return type
ndarray of shape (n_samples, n_classes)
- predict_proba(X, **predict_proba_params)
Transform the data, and apply predict_proba with the final estimator.
Call transform of each transformer in the pipeline. The transformed data are finally passed to the final estimator that calls predict_proba method. Only valid if the final estimator implements predict_proba.
- Parameters
X (iterable) – Data to predict on. Must fulfill input requirements of first step of the pipeline.
**predict_proba_params (dict of string -> object) – Parameters to the predict_proba called at the end of all transformations in the pipeline.
- Returns
y_proba – Result of calling predict_proba on the final estimator.
- Return type
ndarray of shape (n_samples, n_classes)
- score(X, y=None, sample_weight=None)
Transform the data, and apply score with the final estimator.
Call transform of each transformer in the pipeline. The transformed data are finally passed to the final estimator that calls score method. Only valid if the final estimator implements score.
- Parameters
X (iterable) – Data to predict on. Must fulfill input requirements of first step of the pipeline.
y (iterable, default=None) – Targets used for scoring. Must fulfill label requirements for all steps of the pipeline.
sample_weight (array-like, default=None) – If not None, this argument is passed as
sample_weight
keyword argument to thescore
method of the final estimator.
- Returns
score – Result of calling score on the final estimator.
- Return type
- score_samples(X)
Transform the data, and apply score_samples with the final estimator.
Call transform of each transformer in the pipeline. The transformed data are finally passed to the final estimator that calls score_samples method. Only valid if the final estimator implements score_samples.
- Parameters
X (iterable) – Data to predict on. Must fulfill input requirements of first step of the pipeline.
- Returns
y_score – Result of calling score_samples on the final estimator.
- Return type
ndarray of shape (n_samples,)
- set_params(**kwargs)
Set the parameters of this estimator.
Valid parameter keys can be listed with
get_params()
. Note that you can directly set the parameters of the estimators contained in steps.
- steps: List[Any]
- transform(X)
Transform the data, and apply transform with the final estimator.
Call transform of each transformer in the pipeline. The transformed data are finally passed to the final estimator that calls transform method. Only valid if the final estimator implements transform.
This also works where final estimator is None in which case all prior transformations are applied.
- Parameters
X (iterable) – Data to transform. Must fulfill input requirements of first step of the pipeline.
- Returns
Xt – Transformed data.
- Return type
ndarray of shape (n_samples, n_transformed_features)
- class esmvaltool.diag_scripts.mlr.custom_sklearn.AdvancedRFE(estimator, *, n_features_to_select=None, step=1, verbose=0, importance_getter='auto')[source]
Bases:
RFE
Expand
sklearn.feature_selection.RFE
.- property classes_
Classes labels available when estimator is a classifier.
- Return type
ndarray of shape (n_classes,)
- decision_function(X)
Compute the decision function of
X
.- Parameters
X ({array-like or sparse matrix} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to
dtype=np.float32
and if a sparse matrix is provided to a sparsecsr_matrix
.- Returns
score – The decision function of the input samples. The order of the classes corresponds to that in the attribute classes_. Regression and binary classification produce an array of shape [n_samples].
- Return type
array, shape = [n_samples, n_classes] or [n_samples]
- fit_transform(X, y=None, **fit_params)
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
- Parameters
X (array-like of shape (n_samples, n_features)) – Input samples.
y (array-like of shape (n_samples,) or (n_samples, n_outputs), default=None) – Target values (None for unsupervised transformations).
**fit_params (dict) – Additional fit parameters.
- Returns
X_new – Transformed array.
- Return type
ndarray array of shape (n_samples, n_features_new)
- get_feature_names_out(input_features=None)
Mask feature names according to selected features.
- Parameters
input_features (array-like of str or None, default=None) –
Input features.
If input_features is None, then feature_names_in_ is used as feature names in. If feature_names_in_ is not defined, then the following input feature names are generated: [“x0”, “x1”, …, “x(n_features_in_ - 1)”].
If input_features is an array-like, then input_features must match feature_names_in_ if feature_names_in_ is defined.
- Returns
feature_names_out – Transformed feature names.
- Return type
ndarray of str objects
- get_params(deep=True)
Get parameters for this estimator.
- get_support(indices=False)
Get a mask, or integer index, of the features selected.
- Parameters
indices (bool, default=False) – If True, the return value will be an array of integers, rather than a boolean mask.
- Returns
support – An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
- Return type
array
- inverse_transform(X)
Reverse the transformation operation.
- Parameters
X (array of shape [n_samples, n_selected_features]) – The input samples.
- Returns
X_r – X with columns of zeros inserted where features would have been removed by
transform()
.- Return type
array of shape [n_samples, n_original_features]
- predict_log_proba(X)
Predict class log-probabilities for X.
- Parameters
X (array of shape [n_samples, n_features]) – The input samples.
- Returns
p – The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
- Return type
array of shape (n_samples, n_classes)
- predict_proba(X)
Predict class probabilities for X.
- Parameters
X ({array-like or sparse matrix} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to
dtype=np.float32
and if a sparse matrix is provided to a sparsecsr_matrix
.- Returns
p – The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
- Return type
array of shape (n_samples, n_classes)
- score(X, y, **fit_params)
Reduce X to the selected features and return the score of the estimator.
- Parameters
X (array of shape [n_samples, n_features]) – The input samples.
y (array of shape [n_samples]) – The target values.
**fit_params (dict) –
Parameters to pass to the score method of the underlying estimator.
New in version 1.0.
- Returns
score – Score of the underlying base estimator computed with the selected features returned by rfe.transform(X) and y.
- Return type
- set_params(**params)
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as
Pipeline
). The latter have parameters of the form<component>__<parameter>
so that it’s possible to update each component of a nested object.- Parameters
**params (dict) – Estimator parameters.
- Returns
self – Estimator instance.
- Return type
estimator instance
- transform(X)
Reduce X to the selected features.
- Parameters
X (array of shape [n_samples, n_features]) – The input samples.
- Returns
X_r – The input samples with only the selected features.
- Return type
array of shape [n_samples, n_selected_features]
- class esmvaltool.diag_scripts.mlr.custom_sklearn.AdvancedRFECV(estimator, step=1, min_features_to_select=1, cv=None, scoring=None, verbose=0, n_jobs=None)[source]
Bases:
AdvancedRFE
Expand
sklearn.feature_selection.RFECV
.- property classes_
Classes labels available when estimator is a classifier.
- Return type
ndarray of shape (n_classes,)
- decision_function(X)
Compute the decision function of
X
.- Parameters
X ({array-like or sparse matrix} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to
dtype=np.float32
and if a sparse matrix is provided to a sparsecsr_matrix
.- Returns
score – The decision function of the input samples. The order of the classes corresponds to that in the attribute classes_. Regression and binary classification produce an array of shape [n_samples].
- Return type
array, shape = [n_samples, n_classes] or [n_samples]
- fit_transform(X, y=None, **fit_params)
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
- Parameters
X (array-like of shape (n_samples, n_features)) – Input samples.
y (array-like of shape (n_samples,) or (n_samples, n_outputs), default=None) – Target values (None for unsupervised transformations).
**fit_params (dict) – Additional fit parameters.
- Returns
X_new – Transformed array.
- Return type
ndarray array of shape (n_samples, n_features_new)
- get_feature_names_out(input_features=None)
Mask feature names according to selected features.
- Parameters
input_features (array-like of str or None, default=None) –
Input features.
If input_features is None, then feature_names_in_ is used as feature names in. If feature_names_in_ is not defined, then the following input feature names are generated: [“x0”, “x1”, …, “x(n_features_in_ - 1)”].
If input_features is an array-like, then input_features must match feature_names_in_ if feature_names_in_ is defined.
- Returns
feature_names_out – Transformed feature names.
- Return type
ndarray of str objects
- get_params(deep=True)
Get parameters for this estimator.
- get_support(indices=False)
Get a mask, or integer index, of the features selected.
- Parameters
indices (bool, default=False) – If True, the return value will be an array of integers, rather than a boolean mask.
- Returns
support – An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
- Return type
array
- inverse_transform(X)
Reverse the transformation operation.
- Parameters
X (array of shape [n_samples, n_selected_features]) – The input samples.
- Returns
X_r – X with columns of zeros inserted where features would have been removed by
transform()
.- Return type
array of shape [n_samples, n_original_features]
- predict_log_proba(X)
Predict class log-probabilities for X.
- Parameters
X (array of shape [n_samples, n_features]) – The input samples.
- Returns
p – The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
- Return type
array of shape (n_samples, n_classes)
- predict_proba(X)
Predict class probabilities for X.
- Parameters
X ({array-like or sparse matrix} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to
dtype=np.float32
and if a sparse matrix is provided to a sparsecsr_matrix
.- Returns
p – The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.
- Return type
array of shape (n_samples, n_classes)
- score(X, y, **fit_params)
Reduce X to the selected features and return the score of the estimator.
- Parameters
X (array of shape [n_samples, n_features]) – The input samples.
y (array of shape [n_samples]) – The target values.
**fit_params (dict) –
Parameters to pass to the score method of the underlying estimator.
New in version 1.0.
- Returns
score – Score of the underlying base estimator computed with the selected features returned by rfe.transform(X) and y.
- Return type
- set_params(**params)
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as
Pipeline
). The latter have parameters of the form<component>__<parameter>
so that it’s possible to update each component of a nested object.- Parameters
**params (dict) – Estimator parameters.
- Returns
self – Estimator instance.
- Return type
estimator instance
- transform(X)
Reduce X to the selected features.
- Parameters
X (array of shape [n_samples, n_features]) – The input samples.
- Returns
X_r – The input samples with only the selected features.
- Return type
array of shape [n_samples, n_selected_features]
- class esmvaltool.diag_scripts.mlr.custom_sklearn.AdvancedTransformedTargetRegressor(regressor=None, *, transformer=None, func=None, inverse_func=None, check_inverse=True)[source]
Bases:
TransformedTargetRegressor
Expand
sklearn.compose.TransformedTargetRegressor
.- property coef_
Model coefficients.
- Type
- property feature_importances_
Feature importances.
- Type
- get_params(deep=True)
Get parameters for this estimator.
- predict(x_data, always_return_1d=True, **predict_kwargs)[source]
Expand
predict()
to accept kwargs.
- score(X, y, sample_weight=None)
Return the coefficient of determination of the prediction.
The coefficient of determination \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares
((y_true - y_pred)** 2).sum()
and \(v\) is the total sum of squares((y_true - y_true.mean()) ** 2).sum()
. The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.- Parameters
X (array-like of shape (n_samples, n_features)) – Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape
(n_samples, n_samples_fitted)
, wheren_samples_fitted
is the number of samples used in the fitting for the estimator.y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – True values for X.
sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.
- Returns
score – \(R^2\) of
self.predict(X)
wrt. y.- Return type
Notes
The \(R^2\) score used when calling
score
on a regressor usesmultioutput='uniform_average'
from version 0.23 to keep consistent with default value ofr2_score()
. This influences thescore
method of all the multioutput regressors (except forMultiOutputRegressor
).
- set_params(**params)
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as
Pipeline
). The latter have parameters of the form<component>__<parameter>
so that it’s possible to update each component of a nested object.- Parameters
**params (dict) – Estimator parameters.
- Returns
self – Estimator instance.
- Return type
estimator instance
- class esmvaltool.diag_scripts.mlr.custom_sklearn.FeatureSelectionTransformer(grid_scores, n_features, ranking, support)[source]
Bases:
BaseEstimator
,SelectorMixin
Transformer step of a feature selection estimator.
- fit_transform(X, y=None, **fit_params)
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
- Parameters
X (array-like of shape (n_samples, n_features)) – Input samples.
y (array-like of shape (n_samples,) or (n_samples, n_outputs), default=None) – Target values (None for unsupervised transformations).
**fit_params (dict) – Additional fit parameters.
- Returns
X_new – Transformed array.
- Return type
ndarray array of shape (n_samples, n_features_new)
- get_feature_names_out(input_features=None)
Mask feature names according to selected features.
- Parameters
input_features (array-like of str or None, default=None) –
Input features.
If input_features is None, then feature_names_in_ is used as feature names in. If feature_names_in_ is not defined, then the following input feature names are generated: [“x0”, “x1”, …, “x(n_features_in_ - 1)”].
If input_features is an array-like, then input_features must match feature_names_in_ if feature_names_in_ is defined.
- Returns
feature_names_out – Transformed feature names.
- Return type
ndarray of str objects
- get_params(deep=True)
Get parameters for this estimator.
- get_support(indices=False)
Get a mask, or integer index, of the features selected.
- Parameters
indices (bool, default=False) – If True, the return value will be an array of integers, rather than a boolean mask.
- Returns
support – An index that selects the retained features from a feature vector. If indices is False, this is a boolean array of shape [# input features], in which an element is True iff its corresponding feature is selected for retention. If indices is True, this is an integer array of shape [# output features] whose values are indices into the input feature vector.
- Return type
array
- inverse_transform(X)
Reverse the transformation operation.
- Parameters
X (array of shape [n_samples, n_selected_features]) – The input samples.
- Returns
X_r – X with columns of zeros inserted where features would have been removed by
transform()
.- Return type
array of shape [n_samples, n_original_features]
- set_params(**params)
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as
Pipeline
). The latter have parameters of the form<component>__<parameter>
so that it’s possible to update each component of a nested object.- Parameters
**params (dict) – Estimator parameters.
- Returns
self – Estimator instance.
- Return type
estimator instance
- transform(X)
Reduce X to the selected features.
- Parameters
X (array of shape [n_samples, n_features]) – The input samples.
- Returns
X_r – The input samples with only the selected features.
- Return type
array of shape [n_samples, n_selected_features]
- esmvaltool.diag_scripts.mlr.custom_sklearn.cross_val_score_weighted(estimator, x_data, y_data=None, groups=None, scoring=None, cv=None, n_jobs=None, verbose=0, fit_params=None, pre_dispatch='2*n_jobs', error_score=nan, sample_weights=None)[source]