StackingClassifier
- class sklearn.ensemble.StackingClassifier(estimators, final_estimator=None, *, cv=None, stack_method='auto', n_jobs=None, passthrough=False,
Stack of estimators with a final classifier.
Stacked generalization consists in stacking the output of individual estimator and use a classifier to compute the final prediction. Stacking allows to use the strength of each individual estimator by using their output as input of a final estimator.
Note that estimators_ are fitted on the full X while final_estimator_
is trained using cross-validated predictions of the base estimators using
cross_val_predict.
Read more in the User Guide.
Base estimators which will be stacked together. Each element of the
list is defined as a tuple of string (i.e. name) and an estimator
instance. An estimator can be set to ‘drop’ using set_params.
The type of estimator is generally expected to be a classifier. However, one can pass a regressor for some use case (e.g. ordinal regression).
A classifier which will be used to combine the base estimators.
The default classifier is a
LogisticRegression.
Determines the cross-validation splitting strategy used in
cross_val_predict to train final_estimator. Possible inputs for
cv 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 the estimators are prefit. In this case, the
estimators will not be refitted.
For integer/None inputs, if the estimator is a classifier and y is
either binary or multiclass,
StratifiedKFold is used.
In all other cases, is used.
These splitters are instantiated with so the splits
will be the same across calls.
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 that
order.
otherwise, one of 'predict_proba', 'decision_function' or
'predict'. If the method is not implemented by the estimator, it
will raise an error.
The number of jobs to run in parallel for fit of all estimators.
None means 1 unless in a joblib.parallel_backend context. -1 means
using all processors. See Glossary for more details.
When False, only the predictions of estimators will be used as
training data for final_estimator. When True, the
final_estimator is trained on the predictions as well as the
original training data.
Verbosity level.
y is of type "multilabel-indicator".Class labels.
The elements of the estimators parameter, having been fitted on the
training data. If an estimator has been set to 'drop', it
will not appear in estimators_. When cv="prefit", estimators_
is set to estimators and is not fitted again.
When predict_proba is used by each estimator (i.e. most of the time for
stack_method='auto' or specifically for stack_method='predict_proba'),
the first column predicted by each estimator will be dropped in the case
of a binary classification problem. Indeed, both feature will be perfectly
collinear.
In some cases (e.g. ordinal regression), one can pass regressors as the
first layer of the StackingClassifier. However, note that y will
be internally encoded in a numerically increasing order or lexicographic
order. If this ordering is not adequate, one should manually numerically
encode the classes in the desired order.
Wolpert, David H. “Stacked generalization.” Neural networks 5.2 (1992): 241-259.
>>> from sklearn.datasets import load_iris
>>> from sklearn.ensemble import RandomForestClassifier
>>> from sklearn.svm import LinearSVC
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.preprocessing import StandardScaler
>>> from
Decision function for samples in X using the final estimator.
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
Fit the estimators.
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
Target values. Note that will be internally encoded in
numerically increasing order or lexicographic order. If the order
matter (e.g. for ordinal regression), one should numerically encode
the target before calling .
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params
and returns a transformed version of X.
Get output feature names for transformation.
Input features. The input feature names are only used when passthrough is
True.
If input_features is , then is
used as feature names in. If is not defined,
then names are generated: .
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
Get the parameters of an estimator from the ensemble.
Returns the parameters given in the constructor as well as the
estimators contained within the estimators parameter.
Setting it to True gets the various estimators and the parameters of the estimators as well.
Dictionary to access any fitted sub-estimators by name.
Predict target for X.
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
Parameters to the called by the . Note
that this may be used to return uncertainties from some estimators
with or . Be aware that it will only
account for uncertainty in the final estimator.
Predict class probabilities for X using the final estimator.
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
Return accuracy on provided data and labels.
In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.
Test samples.
True labels for .
Set output container.
Refer to the user guide for more details and Introducing the set_output API for an example on how to use the API.
Configure output of transform and .
Set the parameters of an estimator from the ensemble.
Valid parameter keys can be listed with get_params(). Note that you
can directly set the parameters of the estimators contained in
estimators.
Specific parameters using e.g.
set_params(parameter_name=new_value). In addition, to setting the
parameters of the estimator, the individual estimator of the
estimators can also be set, or can be removed by setting them to
‘drop’.
Configure whether metadata should be requested to be passed to the method.
Return class labels or probabilities for X for each estimator.
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
shuffle=FalseRefer User Guide for the various cross-validation strategies that can be used here.
If “prefit” is passed, it is assumed that all estimators have
been fitted already. The final_estimator_ is trained on the estimators
predictions on the full training set and are not cross validated
predictions. Please note that if the models have been trained on the same
data to train the stacking model, there is a very high risk of overfitting.
BunchAttribute to access any fitted sub-estimators by name.
n_features_in_ : intNumber of features seen during fit.
n_features_in_,)Names of features seen during fit. Only defined if the underlying estimators expose such an attribute when fit.
The classifier fit on the output of estimators_ and responsible for
final predictions.
The method used by each base estimator.
The decision function computed the final estimator.
yParameters to pass to the underlying estimators.
Returns a fitted instance of estimator.
Input samples.
Target values (None for unsupervised transformations).
Additional fit parameters.
Pass only if the estimator accepts additional params in its fit method.
Transformed array.
feature_names_in_feature_names_in_[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.
If passthrough is False, then only the names of estimators are used
to generate the output feature names.
Transformed feature names.
Parameter and estimator names mapped to their values or parameter names mapped to their values.
final_estimatorreturn_stdreturn_covIf enable_metadata_routing=False (default):
Parameters directly passed to the predict method of the
final_estimator.
If enable_metadata_routing=True: Parameters safely routed to
the predict method of the final_estimator. See Metadata
Routing User Guide for more details.
Predicted targets.
The class probabilities of the input samples.
Sample weights.
Mean accuracy of self.predict(X) w.r.t. y.
"default": Default output format of a transformer
"pandas": DataFrame output
"polars": Polars output
None: Transform configuration is unchanged
Estimator instance.
Estimator instance.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config).
Please check the 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.
Metadata routing for sample_weight parameter in score.
The updated object.
Prediction outputs for each estimator.