StackingClassifier#

classsklearn.ensemble.StackingClassifier(estimators,final_estimator=None,*,cv=None,stack_method='auto',n_jobs=None,passthrough=False,verbose=0)[source]#

Stack of estimators with a final classifier.

Stacked generalization consists in stacking the output of individualestimator and use a classifier to compute the final prediction. Stackingallows to use the strength of each individual estimator by using theiroutput as input of a final estimator.

Note thatestimators_ are fitted on the fullX whilefinal_estimator_is trained using cross-validated predictions of the base estimators usingcross_val_predict.

Read more in theUser Guide.

Added in version 0.22.

Parameters:
estimatorslist of (str, estimator)

Base estimators which will be stacked together. Each element of thelist is defined as a tuple of string (i.e. name) and an estimatorinstance. An estimator can be set to ‘drop’ usingset_params.

The type of estimator is generally expected to be a classifier.However, one can pass a regressor for some use case (e.g. ordinalregression).

final_estimatorestimator, default=None

A classifier which will be used to combine the base estimators.The default classifier is aLogisticRegression.

cvint, cross-validation generator, iterable, or “prefit”, default=None

Determines the cross-validation splitting strategy used incross_val_predict to trainfinal_estimator. Possible inputs forcv are:

  • None, to use the default 5-fold cross validation,

  • integer, to specify the number of folds in a (Stratified) KFold,

  • An object to be used as a cross-validation generator,

  • An iterable yielding train, test splits,

  • "prefit", to assume theestimators are prefit. In this case, theestimators will not be refitted.

For integer/None inputs, if the estimator is a classifier and y iseither binary or multiclass,StratifiedKFold is used.In all other cases,KFold is used.These splitters are instantiated withshuffle=False so the splitswill be the same across calls.

ReferUser Guide for the variouscross-validation strategies that can be used here.

If “prefit” is passed, it is assumed that allestimators havebeen fitted already. Thefinal_estimator_ is trained on theestimatorspredictions on the full training set and arenot cross validatedpredictions. Please note that if the models have been trained on the samedata to train the stacking model, there is a very high risk of overfitting.

Added in version 1.1:The ‘prefit’ option was added in 1.1

Note

A larger number of split will provide no benefits if the numberof training samples is large enough. Indeed, the training timewill increase.cv is not used for model evaluation but forprediction.

stack_method{‘auto’, ‘predict_proba’, ‘decision_function’, ‘predict’}, default=’auto’

Methods called for each base estimator. It can be:

  • if ‘auto’, it will try to invoke, for each estimator,'predict_proba','decision_function' or'predict' in thatorder.

  • otherwise, one of'predict_proba','decision_function' or'predict'. If the method is not implemented by the estimator, itwill raise an error.

n_jobsint, default=None

The number of jobs to run in parallel forfit of allestimators.None means 1 unless in ajoblib.parallel_backend context. -1 meansusing all processors. SeeGlossary for more details.

passthroughbool, default=False

When False, only the predictions of estimators will be used astraining data forfinal_estimator. When True, thefinal_estimator is trained on the predictions as well as theoriginal training data.

verboseint, default=0

Verbosity level.

Attributes:
classes_ndarray of shape (n_classes,) or list of ndarray ify is of type"multilabel-indicator".

Class labels.

estimators_list of estimators

The elements of theestimators parameter, having been fitted on thetraining data. If an estimator has been set to'drop', itwill not appear inestimators_. Whencv="prefit",estimators_is set toestimators and is not fitted again.

named_estimators_Bunch

Attribute to access any fitted sub-estimators by name.

n_features_in_int

Number of features seen duringfit.

feature_names_in_ndarray of shape (n_features_in_,)

Names of features seen duringfit. Only defined if theunderlying estimators expose such an attribute when fit.

Added in version 1.0.

final_estimator_estimator

The classifier fit on the output ofestimators_ and responsible forfinal predictions.

stack_method_list of str

The method used by each base estimator.

See also

StackingRegressor

Stack of estimators with a final regressor.

Notes

Whenpredict_proba is used by each estimator (i.e. most of the time forstack_method='auto' or specifically forstack_method='predict_proba'),the first column predicted by each estimator will be dropped in the caseof a binary classification problem. Indeed, both feature will be perfectlycollinear.

In some cases (e.g. ordinal regression), one can pass regressors as thefirst layer of theStackingClassifier. However, note thaty willbe internally encoded in a numerically increasing order or lexicographicorder. If this ordering is not adequate, one should manually numericallyencode the classes in the desired order.

References

[1]

Wolpert, David H. “Stacked generalization.” Neural networks 5.2(1992): 241-259.

Examples

>>>fromsklearn.datasetsimportload_iris>>>fromsklearn.ensembleimportRandomForestClassifier>>>fromsklearn.svmimportLinearSVC>>>fromsklearn.linear_modelimportLogisticRegression>>>fromsklearn.preprocessingimportStandardScaler>>>fromsklearn.pipelineimportmake_pipeline>>>fromsklearn.ensembleimportStackingClassifier>>>X,y=load_iris(return_X_y=True)>>>estimators=[...('rf',RandomForestClassifier(n_estimators=10,random_state=42)),...('svr',make_pipeline(StandardScaler(),...LinearSVC(random_state=42)))...]>>>clf=StackingClassifier(...estimators=estimators,final_estimator=LogisticRegression()...)>>>fromsklearn.model_selectionimporttrain_test_split>>>X_train,X_test,y_train,y_test=train_test_split(...X,y,stratify=y,random_state=42...)>>>clf.fit(X_train,y_train).score(X_test,y_test)0.9...
decision_function(X)[source]#

Decision function for samples inX using the final estimator.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

Training vectors, wheren_samples is the number of samples andn_features is the number of features.

Returns:
decisionsndarray of shape (n_samples,), (n_samples, n_classes), or (n_samples, n_classes * (n_classes-1) / 2)

The decision function computed the final estimator.

fit(X,y,**fit_params)[source]#

Fit the estimators.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

Training vectors, wheren_samples is the number of samples andn_features is the number of features.

yarray-like of shape (n_samples,)

Target values. Note thaty will be internally encoded innumerically increasing order or lexicographic order. If the ordermatter (e.g. for ordinal regression), one should numerically encodethe targety before callingfit.

**fit_paramsdict

Parameters to pass to the underlying estimators.

Added in version 1.6:Only available ifenable_metadata_routing=True, which can beset by usingsklearn.set_config(enable_metadata_routing=True).SeeMetadata Routing User Guide formore details.

Returns:
selfobject

Returns a fitted instance of estimator.

fit_transform(X,y=None,**fit_params)[source]#

Fit to data, then transform it.

Fits transformer toX andy with optional parametersfit_paramsand returns a transformed version ofX.

Parameters:
Xarray-like of shape (n_samples, n_features)

Input samples.

yarray-like of shape (n_samples,) or (n_samples, n_outputs), default=None

Target values (None for unsupervised transformations).

**fit_paramsdict

Additional fit parameters.

Returns:
X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

get_feature_names_out(input_features=None)[source]#

Get output feature names for transformation.

Parameters:
input_featuresarray-like of str or None, default=None

Input features. The input feature names are only used whenpassthrough isTrue.

  • Ifinput_features isNone, thenfeature_names_in_ isused as feature names in. Iffeature_names_in_ is not defined,then names are generated:[x0,x1,...,x(n_features_in_-1)].

  • Ifinput_features is an array-like, theninput_features mustmatchfeature_names_in_ iffeature_names_in_ is defined.

Ifpassthrough isFalse, then only the names ofestimators are usedto generate the output feature names.

Returns:
feature_names_outndarray of str objects

Transformed feature names.

get_metadata_routing()[source]#

Get metadata routing of this object.

Please checkUser Guide on how the routingmechanism works.

Added in version 1.6.

Returns:
routingMetadataRouter

AMetadataRouter encapsulatingrouting information.

get_params(deep=True)[source]#

Get the parameters of an estimator from the ensemble.

Returns the parameters given in the constructor as well as theestimators contained within theestimators parameter.

Parameters:
deepbool, default=True

Setting it to True gets the various estimators and the parametersof the estimators as well.

Returns:
paramsdict

Parameter and estimator names mapped to their values or parameternames mapped to their values.

propertynamed_estimators#

Dictionary to access any fitted sub-estimators by name.

Returns:
Bunch
predict(X,**predict_params)[source]#

Predict target for X.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

Training vectors, wheren_samples is the number of samples andn_features is the number of features.

**predict_paramsdict of str -> obj

Parameters to thepredict called by thefinal_estimator. Notethat this may be used to return uncertainties from some estimatorswithreturn_std orreturn_cov. Be aware that it will onlyaccount for uncertainty in the final estimator.

  • Ifenable_metadata_routing=False (default):Parameters directly passed to thepredict method of thefinal_estimator.

  • Ifenable_metadata_routing=True: Parameters safely routed tothepredict method of thefinal_estimator. SeeMetadataRouting User Guide for more details.

Changed in version 1.6:**predict_params can be routed via metadata routing API.

Returns:
y_predndarray of shape (n_samples,) or (n_samples, n_output)

Predicted targets.

predict_proba(X)[source]#

Predict class probabilities forX using the final estimator.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

Training vectors, wheren_samples is the number of samples andn_features is the number of features.

Returns:
probabilitiesndarray of shape (n_samples, n_classes) or list of ndarray of shape (n_output,)

The class probabilities of the input samples.

score(X,y,sample_weight=None)[source]#

Returnaccuracy on provided data and labels.

In multi-label classification, this is the subset accuracywhich is a harsh metric since you require for each sample thateach label set be correctly predicted.

Parameters:
Xarray-like of shape (n_samples, n_features)

Test samples.

yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True labels forX.

sample_weightarray-like of shape (n_samples,), default=None

Sample weights.

Returns:
scorefloat

Mean accuracy ofself.predict(X) w.r.t.y.

set_output(*,transform=None)[source]#

Set output container.

SeeIntroducing the set_output APIfor an example on how to use the API.

Parameters:
transform{“default”, “pandas”, “polars”}, default=None

Configure output oftransform andfit_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:
selfestimator instance

Estimator instance.

set_params(**params)[source]#

Set the parameters of an estimator from the ensemble.

Valid parameter keys can be listed withget_params(). Note that youcan directly set the parameters of the estimators contained inestimators.

Parameters:
**paramskeyword arguments

Specific parameters using e.g.set_params(parameter_name=new_value). In addition, to setting theparameters of the estimator, the individual estimator of theestimators can also be set, or can be removed by setting them to‘drop’.

Returns:
selfobject

Estimator instance.

set_score_request(*,sample_weight:bool|None|str='$UNCHANGED$')StackingClassifier[source]#

Configure whether metadata should be requested to be passed to thescore method.

Note that this method is only relevant when this estimator is used as asub-estimator within ameta-estimator and metadata routing is enabledwithenable_metadata_routing=True (seesklearn.set_config).Please check theUser Guide on how the routingmechanism works.

The options for each parameter are:

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

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

  • 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 theexisting request. This allows you to change the request for someparameters and not others.

Added in version 1.3.

Parameters:
sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing forsample_weight parameter inscore.

Returns:
selfobject

The updated object.

transform(X)[source]#

Return class labels or probabilities for X for each estimator.

Parameters:
X{array-like, sparse matrix} of shape (n_samples, n_features)

Training vectors, wheren_samples is the number of samples andn_features is the number of features.

Returns:
y_predsndarray of shape (n_samples, n_estimators) or (n_samples, n_classes * n_estimators)

Prediction outputs for each estimator.

Gallery examples#

Release Highlights for scikit-learn 0.22

Release Highlights for scikit-learn 0.22