sparselm.stepwise#

Stepwise model selection for piece-wise fitting.

class sparselm.stepwise.StepwiseEstimator(steps, estimator_feature_indices)[source]#

Bases: _BaseComposition, RegressorMixin, LinearModel

A composite estimator used to do stepwise fitting.

The first estimator in the composite will be used to fit certain features (a piece of the feature matrix) to the target vector, and the residuals are fitted to the rest of features by using the next estimators in the composite.

Each estimator can be either a CVXEstimator, a GridSearchCV or a LineSearchCV.

Parameters:
  • steps (list[(str, CVXEstimator)]) – A list of step names and the CVXEstimators to use for each step. StepwiseEstimator cannot be used as a member of StepwiseEstimator. An estimator will fit the residuals of the previous estimator fits in the list.

  • estimator_feature_indices (tuple[tuple[int]]) –

    Scope of each estimator, which means the indices of features in the scope (features[:, scope]) will be fitted to the residual using the corresponding estimator. Notice:

    If estimators in the composite requires hierarchy or groups, the indices in the groups or hierarchy must be adjusted such that they correspond to the groups or hierarchy relations in the part of features sliced by scope. For example, consider original groups = [0, 1, 1, 2, 2], and an estimator has scope = [3, 4], then the estimator should be initialized with group = [0, 0]. You are fully responsible to initialize the estimators with correct hierarchy, groups and other parameters before wrapping them up with the composite!

Notes

  1. Do not use GridSearchCV or LineSearchCV to search a StepwiseEstimator!

2. No nesting is allowed for StepwiseEstimator, which means no step of a StepwiseEstimator can be a StepwiseEstimator.

3. Since stepwise estimator requires specifying a list of feature indices for each step estimator, it requires fixing n_features_in_ before fitting, which violates sklearn convention for a regressor. Therefore, StepwiseEstimator is not checked by sklearn check_estimator method, and there is no guarantee that it is fully compatible with all scikit-learn features.

steps: List[Any]#
get_params(deep=True)[source]#

Get parameters of all estimators in the composite.

Parameters:

deep (bool) – If True, will return the parameters for estimators in composite, and their contained sub-objects if they are also estimators.

set_params(**params)[source]#

Set parameters for each estimator in the composite.

This will be called when model selection optimizes all hyper parameters.

Parameters:
  • params – A Dictionary of parameters. Each parameter

  • specify (name must end with an underscore and a number to) –

  • is (on which estimator in the composite the parameter) –

  • set. (going to be) –

  • optimize! (Remember only to set params you wish to) –

fit(X, y, sample_weight=None, *args, **kwargs)[source]#

Prepare fit input with sklearn help then call fit method.

Parameters:
  • X (ArrayLike) – Training data of shape (n_samples, n_features).

  • y (ArrayLike) – Target values. Will be cast to X’s dtype if necessary of shape (n_samples,) or (n_samples, n_targets)

  • sample_weight (ArrayLike) – Individual weights for each sample of shape (n_samples,) default=None

  • *args – Positional arguments passed to _fit method

  • **kwargs – Keyword arguments passed to _fit method

Returns:

instance of self

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

predict(X)#

Predict using the linear model.

Parameters:

X (array-like or sparse matrix, shape (n_samples, n_features)) – Samples.

Returns:

C – Returns predicted values.

Return type:

array, shape (n_samples,)

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(*, sample_weight='$UNCHANGED$')#

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.

New 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.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 fit.

  • self (StepwiseEstimator) –

Returns:

self – The updated object.

Return type:

object

set_score_request(*, sample_weight='$UNCHANGED$')#

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.

New 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.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.

  • self (StepwiseEstimator) –

Returns:

self – The updated object.

Return type:

object