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:

numpy.ndarray

decision_function(X, **params)#

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.

  • **params (dict of string -> object) –

    Parameters requested and accepted by steps. Each step must have requested certain metadata for these parameters to be forwarded to them.

    Added in version 1.4: Only available if enable_metadata_routing=True. See Metadata Routing User Guide for more details.

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:

numpy.ndarray

property feature_names_in_#

Names of features seen during first step fit method.

fit(X, y=None, **params)#

Fit the model.

Fit all the transformers one after the other and sequentially 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.

  • **params (dict of str -> object) –

    • If enable_metadata_routing=False (default):

      Parameters passed to the fit method of each step, where each parameter name is prefixed such that parameter p for step s has key s__p.

    • If enable_metadata_routing=True:

      Parameters requested and accepted by steps. Each step must have requested certain metadata for these parameters to be forwarded to them.

    Changed in version 1.4: Parameters are now passed to the transform method of the intermediate steps as well, if requested, and if enable_metadata_routing=True is set via set_config().

    See Metadata Routing User Guide for more details.

Returns:

self – Pipeline with fitted steps.

Return type:

object

fit_predict(X, y=None, **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.

  • **params (dict of str -> object) –

    • If enable_metadata_routing=False (default):

      Parameters to the predict called at the end of all transformations in the pipeline.

    • If enable_metadata_routing=True:

      Parameters requested and accepted by steps. Each step must have requested certain metadata for these parameters to be forwarded to them.

    Added in version 0.20.

    Changed in version 1.4: Parameters are now passed to the transform method of the intermediate steps as well, if requested, and if enable_metadata_routing=True.

    See Metadata Routing User Guide for more details.

    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.

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, **params)#

Fit the model and transform with the final estimator.

Fit all the transformers one after the other and sequentially transform the data. Only valid if the final estimator either implements fit_transform or fit and transform.

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.

  • **params (dict of str -> object) –

    • If enable_metadata_routing=False (default):

      Parameters passed to the fit method of each step, where each parameter name is prefixed such that parameter p for step s has key s__p.

    • If enable_metadata_routing=True:

      Parameters requested and accepted by steps. Each step must have requested certain metadata for these parameters to be forwarded to them.

    Changed in version 1.4: Parameters are now passed to the transform method of the intermediate steps as well, if requested, and if enable_metadata_routing=True.

    See Metadata Routing User Guide for more details.

Returns:

Xt – Transformed samples.

Return type:

ndarray of shape (n_samples, n_transformed_features)

fit_transformers_only(x_data, y_data, **fit_kwargs)[source]#

Fit only transform steps of Pipeline.

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_metadata_routing()#

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:

routing – A MetadataRouter encapsulating routing information.

Return type:

MetadataRouter

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, **params)#

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 and n_features is the number of features. Must fulfill input requirements of last step of pipeline’s inverse_transform method.

  • **params (dict of str -> object) –

    Parameters requested and accepted by steps. Each step must have requested certain metadata for these parameters to be forwarded to them.

    Added in version 1.4: Only available if enable_metadata_routing=True. See Metadata Routing User Guide for more details.

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, **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.

  • **params (dict of str -> object) –

    • If enable_metadata_routing=False (default):

      Parameters to the predict called at the end of all transformations in the pipeline.

    • If enable_metadata_routing=True:

      Parameters requested and accepted by steps. Each step must have requested certain metadata for these parameters to be forwarded to them.

    Added in version 0.20.

    Changed in version 1.4: Parameters are now passed to the transform method of the intermediate steps as well, if requested, and if enable_metadata_routing=True is set via set_config().

    See Metadata Routing User Guide for more details.

    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.

Returns:

y_pred – Result of calling predict on the final estimator.

Return type:

ndarray

predict_log_proba(X, **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.

  • **params (dict of str -> object) –

    • If enable_metadata_routing=False (default):

      Parameters to the predict_log_proba called at the end of all transformations in the pipeline.

    • If enable_metadata_routing=True:

      Parameters requested and accepted by steps. Each step must have requested certain metadata for these parameters to be forwarded to them.

    Added in version 0.20.

    Changed in version 1.4: Parameters are now passed to the transform method of the intermediate steps as well, if requested, and if enable_metadata_routing=True.

    See Metadata Routing User Guide for more details.

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, **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.

  • **params (dict of str -> object) –

    • If enable_metadata_routing=False (default):

      Parameters to the predict_proba called at the end of all transformations in the pipeline.

    • If enable_metadata_routing=True:

      Parameters requested and accepted by steps. Each step must have requested certain metadata for these parameters to be forwarded to them.

    Added in version 0.20.

    Changed in version 1.4: Parameters are now passed to the transform method of the intermediate steps as well, if requested, and if enable_metadata_routing=True.

    See Metadata Routing User Guide for more details.

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, **params)#

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 the score method of the final estimator.

  • **params (dict of str -> object) –

    Parameters requested and accepted by steps. Each step must have requested certain metadata for these parameters to be forwarded to them.

    Added in version 1.4: Only available if enable_metadata_routing=True. See Metadata Routing User Guide for more details.

Returns:

score – Result of calling score on the final estimator.

Return type:

float

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_output(*, transform=None)#

Set the output container when “transform” and “fit_transform” are called.

Calling set_output will set the output of all estimators in steps.

Parameters:

transform ({"default", "pandas"}, default=None) –

Configure output of transform and fit_transform.

  • ”default”: Default output format of a transformer

  • ”pandas”: DataFrame output

  • ”polars”: Polars output

  • None: Transform configuration is unchanged

Added in version 1.4: “polars” option was added.

Returns:

self – Estimator instance.

Return type:

estimator instance

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.

Parameters:

**kwargs (dict) – Parameters of this estimator or parameters of estimators contained in steps. Parameters of the steps may be set using its name and the parameter name separated by a ‘__’.

Returns:

self – Pipeline class instance.

Return type:

object

set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') AdvancedPipeline#

Request metadata passed to the score method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to score.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:

sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in score.

Returns:

self – The updated object.

Return type:

object

steps: List[Any]#
transform(X, **params)#

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.

  • **params (dict of str -> object) –

    Parameters requested and accepted by steps. Each step must have requested certain metadata for these parameters to be forwarded to them.

    Added in version 1.4: Only available if enable_metadata_routing=True. See Metadata Routing User Guide for more details.

Returns:

Xt – Transformed data.

Return type:

ndarray of shape (n_samples, n_transformed_features)

transform_only(x_data)[source]#

Only perform transform steps of Pipeline.

transform_target_only(y_data)[source]#

Only perform transform steps of target regressor.

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 sparse csr_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(x_data, y_data, **fit_kwargs)[source]#

Expand fit() to accept kwargs.

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_metadata_routing()#

Raise NotImplementedError.

This estimator does not support metadata routing yet.

get_params(deep=True)#

Get parameters for this estimator.

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:

dict

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_rX with columns of zeros inserted where features would have been removed by transform().

Return type:

array of shape [n_samples, n_original_features]

predict(x_data, **predict_kwargs)[source]#

Expand predict() to accept kwargs.

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 sparse csr_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.

    Added 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:

float

set_fit_request(*, x_data: bool | None | str = '$UNCHANGED$', y_data: bool | None | str = '$UNCHANGED$') AdvancedRFE#

Request metadata passed to the fit method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
  • x_data (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for x_data parameter in fit.

  • y_data (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for y_data parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_output(*, transform=None)#

Set output container.

See Introducing the set_output API for an example on how to use the API.

Parameters:

transform ({"default", "pandas"}, default=None) –

Configure output of transform and fit_transform.

  • ”default”: Default output format of a transformer

  • ”pandas”: DataFrame output

  • ”polars”: Polars output

  • None: Transform configuration is unchanged

Added in version 1.4: “polars” option was added.

Returns:

self – Estimator instance.

Return type:

estimator instance

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

set_predict_request(*, x_data: bool | None | str = '$UNCHANGED$') AdvancedRFE#

Request metadata passed to the predict method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to predict.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:

x_data (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for x_data parameter in predict.

Returns:

self – The updated object.

Return type:

object

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 sparse csr_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(x_data, y_data, groups=None, **fit_kwargs)[source]#

Expand fit() to accept kwargs.

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_metadata_routing()#

Raise NotImplementedError.

This estimator does not support metadata routing yet.

get_params(deep=True)#

Get parameters for this estimator.

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:

dict

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_rX with columns of zeros inserted where features would have been removed by transform().

Return type:

array of shape [n_samples, n_original_features]

predict(x_data, **predict_kwargs)#

Expand predict() to accept kwargs.

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 sparse csr_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.

    Added 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:

float

set_fit_request(*, groups: bool | None | str = '$UNCHANGED$', x_data: bool | None | str = '$UNCHANGED$', y_data: bool | None | str = '$UNCHANGED$') AdvancedRFECV#

Request metadata passed to the fit method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
  • groups (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for groups parameter in fit.

  • x_data (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for x_data parameter in fit.

  • y_data (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for y_data parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_output(*, transform=None)#

Set output container.

See Introducing the set_output API for an example on how to use the API.

Parameters:

transform ({"default", "pandas"}, default=None) –

Configure output of transform and fit_transform.

  • ”default”: Default output format of a transformer

  • ”pandas”: DataFrame output

  • ”polars”: Polars output

  • None: Transform configuration is unchanged

Added in version 1.4: “polars” option was added.

Returns:

self – Estimator instance.

Return type:

estimator instance

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

set_predict_request(*, x_data: bool | None | str = '$UNCHANGED$') AdvancedRFECV#

Request metadata passed to the predict method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to predict.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:

x_data (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for x_data parameter in predict.

Returns:

self – The updated object.

Return type:

object

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:

numpy.ndarray

property feature_importances_#

Feature importances.

Type:

numpy.ndarray

fit(x_data, y_data, **fit_kwargs)[source]#

Expand fit() to accept kwargs.

fit_transformer_only(y_data, **fit_kwargs)[source]#

Fit only transformer step.

get_metadata_routing()#

Raise NotImplementedError.

This estimator does not support metadata routing yet.

get_params(deep=True)#

Get parameters for this estimator.

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:

dict

property n_features_in_#

Number of features seen during fit.

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), where n_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) w.r.t. y.

Return type:

float

Notes

The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score(). This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_fit_request(*, x_data: bool | None | str = '$UNCHANGED$', y_data: bool | None | str = '$UNCHANGED$') AdvancedTransformedTargetRegressor#

Request metadata passed to the fit method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
  • x_data (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for x_data parameter in fit.

  • y_data (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for y_data parameter in fit.

Returns:

self – The updated object.

Return type:

object

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

set_predict_request(*, always_return_1d: bool | None | str = '$UNCHANGED$', x_data: bool | None | str = '$UNCHANGED$') AdvancedTransformedTargetRegressor#

Request metadata passed to the predict method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to predict.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
  • always_return_1d (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for always_return_1d parameter in predict.

  • x_data (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for x_data parameter in predict.

Returns:

self – The updated object.

Return type:

object

set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') AdvancedTransformedTargetRegressor#

Request metadata passed to the score method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to score.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:

sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in score.

Returns:

self – The updated object.

Return type:

object

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(*_, **__)[source]#

Empty method.

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_metadata_routing()#

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:

routing – A MetadataRequest encapsulating routing information.

Return type:

MetadataRequest

get_params(deep=True)#

Get parameters for this estimator.

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:

dict

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_rX with columns of zeros inserted where features would have been removed by transform().

Return type:

array of shape [n_samples, n_original_features]

set_output(*, transform=None)#

Set output container.

See Introducing the set_output API for an example on how to use the API.

Parameters:

transform ({"default", "pandas"}, default=None) –

Configure output of transform and fit_transform.

  • ”default”: Default output format of a transformer

  • ”pandas”: DataFrame output

  • ”polars”: Polars output

  • None: Transform configuration is unchanged

Added in version 1.4: “polars” option was added.

Returns:

self – Estimator instance.

Return type:

estimator instance

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]#

Expand sklearn.model_selection.cross_val_score().

esmvaltool.diag_scripts.mlr.custom_sklearn.get_rfecv_transformer(rfecv_estimator)[source]#

Get transformer step of RFECV estimator.

esmvaltool.diag_scripts.mlr.custom_sklearn.perform_efecv(estimator, x_data, y_data, **kwargs)[source]#

Perform exhaustive feature selection.