`L idZddlmZmZddlmZddlmZddlZ ddl m Z ddl m Z mZmZmZmZmZmZddlmZdd lmZmZdd lmZmZdd lmZdd lmZdd l m!Z!m"Z"ddl#m$Z$ddl%m&Z&m'Z'm(Z(m)Z)m*Z*ddl+m,Z,ddl-m.Z.m/Z/ddl0m1Z1m2Z2ddl3m4Z4m5Z5m6Z6m7Z7m8Z8ddl9m:Z:m;Z;Gddee:eZ<Gdde e<Z=Gddee<Z>y)z"Stacking classifier and regressor.)ABCMetaabstractmethod)deepcopy)IntegralN)ClassifierMixinRegressorMixinTransformerMixin _fit_contextclone is_classifier is_regressor)NotFittedError)LogisticRegressionRidgeCV)check_cvcross_val_predict) LabelEncoder)Bunch) HasMethods StrOptions) _VisualBlock)MetadataRouter MethodMapping_raise_for_params_routing_enabledprocess_routing) available_if)check_classification_targetstype_of_target)Paralleldelayed)_check_feature_names_in_check_response_method_estimator_hascheck_is_fitted column_or_1d)_BaseHeterogeneousEnsemble_fit_single_estimatorceZdZUdZegdedgdedhgdegdgdgdZe e d <e ddd dd d d fd Z dZ dZedZed dZedZdZddZeedddZdZdZxZS) _BaseStackingzBase class for stacking method.Nfit cv_objectprefitbooleanverbose) estimatorsfinal_estimatorcvn_jobs passthroughr1_parameter_constraintsautorF)r4 stack_methodr5r1r6czt||||_||_||_||_||_||_y)N)r2)super__init__r3r4r9r5r1r6) selfr2r3r4r9r5r1r6 __class__s `/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/ensemble/_stacking.pyr<z_BaseStacking.__init__=sB J/.(  &cr|jt|j|_yt||_yN)r3r final_estimator_)r=defaults r?_clone_final_estimatorz$_BaseStacking._clone_final_estimatorQs-    +$)$*>*>$?D !$)'ND !r@cg}t|D]\}}t|tr"|D]}|j|ddddf8|jdk(r"|j|j ddi|j |dk(r3t|jdk(r|j|ddddf|j||Dcgc]}|jdc}|_ |jrG|j|tj|r!tj||jSt!j|Scc}w)adConcatenate the predictions of each first layer learner and possibly the input dataset `X`. If `X` is sparse and `self.passthrough` is False, the output of `transform` will be dense (the predictions). If `X` is sparse and `self.passthrough` is True, the output of `transform` will be sparse. This helper is in charge of ensuring the predictions are 2D arrays and it will drop one of the probability column when using probabilities in the binary case. Indeed, the p(y|c=0) = 1 - p(y|c=1) When `y` type is `"multilabel-indicator"`` and the method used is `predict_proba`, `preds` can be either a `ndarray` of shape `(n_samples, n_class)` or for some estimators a list of `ndarray`. This function will drop one of the probability column in this situation as well. Nr( predict_probar)format) enumerate isinstancelistappendndimreshape stack_method_lenclasses_shape_n_feature_outsr6sparseissparsehstackrInp)r=X predictionsX_metaest_idxpredspreds r?_concatenate_predictionsz&_BaseStacking._concatenate_predictionsWs'$' 4 %NGU%&"/DMM$q!"u+./q emmB23""7+> &!+  eAqrEl+ e$1 %4;AA$ 1 A    MM! q!}}VAHH==yy  BsEc|dk(ry|dk(rgd} t||j}|S#t$r}td|d|d|d}~wwxYw)Ndropr8)rHdecision_functionpredictzUnderlying estimator z does not implement the method .)r$__name__AttributeError ValueError)name estimatormethod method_namees r? _method_namez_BaseStacking._method_nameso   V FF 0FCLLK   'v-LVHTUV  s) A AA )prefer_skip_nested_validationc Dj\}}jjgt|z}t rt dfi|n:t |D]+}t i|<d|vs|d|jd<-jdk(r;g_ |D].}|dk7s t|jj|0n6tjfdt||D_ t _d} t||D][\} } | dk7rBj| } | j| <| d z } t!| d s;| j"_Mdj| <]t|||D cgc]\}} }j%|| |c}} }_jdk(r>t|j&Dcgc]\}}|dk7rt)||}}}nt+jt- t!d r/j.#t0j2j5_tjfd t||j&D}tj&|D cgc] \}} | dk7r|c} }_j7|}t9j:||Scc}} }wcc}}wcc} }w)aFit the estimators. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) Target values. **fit_params : dict Dict of metadata, potentially containing sample_weight as a key-value pair. If sample_weight is not present, then samples are equally weighted. Note that sample_weight is supported only if all underlying estimators support sample weights. .. versionadded:: 1.6 Returns ------- self : object r-)r- sample_weightr/ra)r5c3|K|]3\}}|dk7r)ttt||d5yw)rar-N)r"r*r ).0rhestrY routed_paramsys r? z$_BaseStacking.fit..sJ<D#&= /-.#J1mD&9%&@<s9<rr(feature_names_in_)ru classifier random_statec 3K|]V\}}}|dk7rKttt|t|j|dj Xyw)rar-)r4rjr5paramsr1N)r"rr rr5r1) rrrhrsmethrYr4rtr=rus r?rvz$_BaseStacking.fit..sl 7$D#t&=+)*#J|;;(.u5 LL   7sAA) fit_params)_validate_estimators_validate_final_estimatorr9rQrrrr-r4 estimators_r&rMr!r5zipnamed_estimators_hasattrrwrmrPgetattrrr ryrXrandom RandomStater_r*rC)r=rYrur}namesall_estimatorsr9rhriest_fitted_idxname_estorg_estcurrent_estimatorrsr|predict_methodrZr[r4rts``` @@r?r-z_BaseStacking.fits<!% 9 9 ;~ &&())*S-@@  +D%F:FM!GM &+m d#"j0?I'@M$'++O<  77h !D + 7 &#I.$$++I6 7 -P-PD*39&&x0 :$'unl#K  c4   dC .  77h 25^TEWEW1X-I~&3 >215K$''Q=3FGBr>*r/F"$))"7"7"96($++6 7(+5.$BTBT'U 7 K& #4#5#5~F sf}   ..q+>d33VQ:V a @ s L0!LLc t||j dj S#t$r(}t|jjd|d}~wwxYw)z+Number of features seen during :term:`fit`.z' object has no attribute n_features_in_Nr)r&rrfr>rern_features_in_)r=nfes r?rz_BaseStacking.n_features_in_s`  D ! "111   >>**++RS  s & A#AAc t|t|j|jDcgc]\}}|dk7rt |||}}}|j ||Scc}}w)z9Concatenate and return the predictions of the estimators.ra)r&rrrPrr_)r=rYrsr|rZs r? _transformz_BaseStacking._transform$so!!1!143E3EF Tf} GC q !  ,,Q <<  s!A%ct|dt|||j}|jjj d|j D}g}t||jD]E\}|dk(r|jd"|jfdt|DG|jrtj||fStj|tS)aGet output feature names for transformation. Parameters ---------- input_features : array-like of str or None, default=None Input features. The input feature names are only used when `passthrough` is `True`. - If `input_features` is `None`, then `feature_names_in_` is used as feature names in. If `feature_names_in_` is not defined, then 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. If `passthrough` is `False`, then only the names of `estimators` are used to generate the output feature names. Returns ------- feature_names_out : ndarray of str objects Transformed feature names. r)generate_namesc32K|]\}}|dk7s |ywraN)rrrhrss r?rvz6_BaseStacking.get_feature_names_out..Ks" T3SF]D" s r(_c30K|] }d|yw)rNr)rri class_namerss r?rvz6_BaseStacking.get_feature_names_out..Ss%"12zl!C5,"s)dtype)r&r#r6r>relowerr2rrTrMextendrangerX concatenateasarrayobject)r=input_featuresnon_dropped_estimators meta_namesn_features_outrrss @@r?get_feature_names_outz#_BaseStacking.get_feature_names_out.s. ./0 .1A1A ^^,,224 " "&//"  #&'=t?S?S#T  C"!!ZL#"78!!"6;N6K"     >>:~">? ?zz*F33r@rcrCr3 delegatesc pt||jj|j|fi|S)aPredict target for X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. **predict_params : dict of str -> obj Parameters to the `predict` called by the `final_estimator`. Note that this may be used to return uncertainties from some estimators with `return_std` or `return_cov`. Be aware that it will only account for uncertainty in the final estimator. Returns ------- y_pred : ndarray of shape (n_samples,) or (n_samples, n_output) Predicted targets. )r&rCrc transform)r=rYpredict_paramss r?rcz_BaseStacking.predict\s30 ,t$$,,T^^A->Q.QQr@ct|j\}}td||d}td|gdgd}td||fdS)NparallelF)r dash_wrappedr3serial)r)rr2r)r=r3rr2r final_blocks r?%_sk_visual_block_with_final_estimatorz3_BaseStacking._sk_visual_block_with_final_estimatorwsY1z JeRWX# )2C1DSX Hx&=ERRr@c xt|jj}|jD]6\}}|jdi||idt j ddi8 |j }|j |t j dd|S#t$r|j}YEwxYw) ajGet metadata routing of this object. Please check :ref:`User Guide ` on how the routing mechanism works. .. versionadded:: 1.6 Returns ------- routing : MetadataRouter A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating routing information. )ownermethod_mappingr-)calleecallerrc)rr)rCrr) rr>rer2addrrCrfr3)r=routerrhrirCs r?get_metadata_routingz"_BaseStacking.get_metadata_routings dnn&=&=> $ OD) FJJ # ,22%2N    4#44   -(?..i .R    4#33  4s' B!!B98B9rB)re __module__ __qualname____doc__rLrrrr7dict__annotations__rr<rEr_ staticmethodrmr r-propertyrrrrr%rcrr __classcell__r>s@r?r,r,1s)f *U"34Jz23"!{; $D' ''&3 3!j  &+x xt22=,4\y,STRR0 S!r@r,) metaclassc$eZdZUdZiej dehdgiZeed< ddddddd fd Z d Z d Z fd Z e eddfdZe edddZe edddZdZfdZxZS)StackingClassifieraStack 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 :ref:`User Guide `. .. versionadded:: 0.22 Parameters ---------- estimators : list of (str, estimator) 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). final_estimator : estimator, default=None A classifier which will be used to combine the base estimators. The default classifier is a :class:`~sklearn.linear_model.LogisticRegression`. cv : int, cross-validation generator, iterable, or "prefit", default=None 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, :class:`~sklearn.model_selection.StratifiedKFold` is used. In all other cases, :class:`~sklearn.model_selection.KFold` is used. These splitters are instantiated with `shuffle=False` so the splits will be the same across calls. Refer :ref:`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. .. versionadded:: 1.1 The 'prefit' option was added in 1.1 .. note:: A larger number of split will provide no benefits if the number of training samples is large enough. Indeed, the training time will increase. ``cv`` is not used for model evaluation but for prediction. 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 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. n_jobs : int, default=None 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 :term:`Glossary ` for more details. passthrough : bool, default=False 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. verbose : int, default=0 Verbosity level. Attributes ---------- classes_ : ndarray of shape (n_classes,) or list of ndarray if `y` is of type `"multilabel-indicator"`. Class labels. estimators_ : list of estimators 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. named_estimators_ : :class:`~sklearn.utils.Bunch` Attribute to access any fitted sub-estimators by name. n_features_in_ : int Number of features seen during :term:`fit`. Only defined if the underlying estimator exposes such an attribute when fit. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Only defined if the underlying estimators expose such an attribute when fit. .. versionadded:: 1.0 final_estimator_ : estimator The classifier fit on the output of `estimators_` and responsible for final predictions. stack_method_ : list of str The method used by each base estimator. See Also -------- StackingRegressor : Stack of estimators with a final regressor. Notes ----- 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 :class:`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. References ---------- .. [1] Wolpert, David H. "Stacked generalization." Neural networks 5.2 (1992): 241-259. Examples -------- >>> 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 sklearn.pipeline import make_pipeline >>> from sklearn.ensemble import StackingClassifier >>> 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() ... ) >>> from sklearn.model_selection import train_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... r9>r8rcrHrbr7Nr8Fr)r4r9r5r6r1c 2t||||||||y)Nr2r3r4r9r5r6r1r;r<) r=r2r3r4r9r5r6r1r>s r?r<zStackingClassifier.__init__^s, !+%#  r@c|jtt|js$t dj |jy)NrDz:'final_estimator' parameter should be a classifier. Got {})rErr rCrgrIr=s r?rz,StackingClassifier._validate_final_estimatorssN ##,>,@#AT223LSS)) 4r@ct|jdk(r tdt|j\}}|j |t d|D}|s td||fS)zOverload the method of `_BaseHeterogeneousEnsemble` to be more lenient towards the type of `estimators`. Regressors can be accepted for some cases such as ordinal regression. rzfInvalid 'estimators' attribute, 'estimators' should be a non-empty list of (string, estimator) tuples.c3&K|] }|dk7 ywrr)rrrss r?rvz:StackingClassifier._validate_estimators..s@cC6M@szHAll estimators are dropped. At least one is required to be an estimator.)rQr2rgr_validate_namesany)r=rr2 has_estimators r?r~z'StackingClassifier._validate_estimators|s} t 1 $@  1z U#@Z@@ &  j  r@c t||ddgt|t|dk(r|jDcgc]}t j |c}|_|j Dcgc]}|jc}|_tjt|jDcgc]#\}}|j |j|%c}}j}nTt j ||_|j j|_|j j|}t |||fi|Scc}wcc}wcc}}w)aNFit the estimators. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) Target values. Note that `y` 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 `y` before calling :term:`fit`. **fit_params : dict Parameters to pass to the underlying estimators. .. versionadded:: 1.6 Only available if `enable_metadata_routing=True`, which can be set by using ``sklearn.set_config(enable_metadata_routing=True)``. See :ref:`Metadata Routing User Guide ` for more details. Returns ------- self : object Returns a fitted instance of estimator. r-rpallowzmultilabel-indicator) rrr Trr-_label_encoderrRrXarrayrJrr;) r=rYrur}ykle target_idxtarget y_encodedr>s r?r-zStackingClassifier.fits"< *dE/9JK$Q' !  6 6DECC"Hb<>#5#5b#9"HD 373F3FGRR[[GDM/8n* F'' 3==fE a #/."4"4Q"7D  //88DM++55a8Iw{1i6:66#IGs E/E1(E rcrrc trt|dfi|}n,t}ti|_||j_t ||fi|jd}t |jtrctjt|jDcgc]#\}}|j|j|%c}}j}|S|jj|}|Scc}}waPredict target for X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. **predict_params : dict of str -> obj Parameters to the `predict` called by the `final_estimator`. Note that this may be used to return uncertainties from some estimators with `return_std` or `return_cov`. Be aware that it will only account for uncertainty in the final estimator. - If `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 :ref:`Metadata Routing User Guide ` for more details. .. versionchanged:: 1.6 `**predict_params` can be routed via metadata routing API. Returns ------- y_pred : ndarray of shape (n_samples,) or (n_samples, n_output) Predicted targets. rc)rc)rrrrCrcr;rKrrLrXrrJrinverse_transform)r=rYrrty_predrrr>s r?rczStackingClassifier.predictsD  +D)N~NM"GM-22->M *5CM * * 2Pm&D&DY&OP d))4 0XX/8.A* F'' 3EEfM a  ((::6BF s$(C= rHct||jj|j|}t |j t r4tj|Dcgc] }|dddf c}j}|Scc}w)aPredict class probabilities for `X` using the final estimator. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. Returns ------- probabilities : ndarray of shape (n_samples, n_classes) or list of ndarray of shape (n_output,) The class probabilities of the input samples. Nr) r&rCrHrrKrrLrXrr)r=rYrr]s r?rHz StackingClassifier.predict_probasm( &&44T^^A5FG d))4 0XX?uuQT{?@BBF @s#Brbclt||jj|j|S)aDecision function for samples in `X` using the final estimator. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. Returns ------- decisions : ndarray of shape (n_samples,), (n_samples, n_classes), or (n_samples, n_classes * (n_classes-1) / 2) The decision function computed the final estimator. )r&rCrbrr=rYs r?rbz$StackingClassifier.decision_functions,( $$66t~~a7HIIr@c$|j|S)aReturn class labels or probabilities for X for each estimator. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. Returns ------- y_preds : ndarray of shape (n_samples, n_estimators) or (n_samples, n_classes * n_estimators) Prediction outputs for each estimator. rrs r?rzStackingClassifier.transform.sq!!r@ch|j t}n |j}t| |SrB)r3rr;rr=r3r>s r?_sk_visual_block_z$StackingClassifier._sk_visual_block_?s4    '02O"22Ow<_MMr@rB)rerrrr,r7rrrr<rr~r-rr%rcrHrbrrrrs@r?rrsn`$  . .$ P Q $D  *!./7by,ST22h 'N    . +R  J  J$""NNr@rceZdZdZ ddddddfd ZdZfdZd Zfd Ze e d d fdZ fdZ xZ S)StackingRegressoragStack of estimators with a final regressor. Stacked generalization consists in stacking the output of individual estimator and use a regressor 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 :ref:`User Guide `. .. versionadded:: 0.22 Parameters ---------- estimators : list of (str, estimator) 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`. final_estimator : estimator, default=None A regressor which will be used to combine the base estimators. The default regressor is a :class:`~sklearn.linear_model.RidgeCV`. cv : int, cross-validation generator, iterable, or "prefit", default=None 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, :class:`~sklearn.model_selection.StratifiedKFold` is used. In all other cases, :class:`~sklearn.model_selection.KFold` is used. These splitters are instantiated with `shuffle=False` so the splits will be the same across calls. Refer :ref:`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. .. versionadded:: 1.1 The 'prefit' option was added in 1.1 .. note:: A larger number of split will provide no benefits if the number of training samples is large enough. Indeed, the training time will increase. ``cv`` is not used for model evaluation but for prediction. n_jobs : int, default=None 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 :term:`Glossary ` for more details. passthrough : bool, default=False 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. verbose : int, default=0 Verbosity level. Attributes ---------- estimators_ : list of estimators 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. named_estimators_ : :class:`~sklearn.utils.Bunch` Attribute to access any fitted sub-estimators by name. n_features_in_ : int Number of features seen during :term:`fit`. Only defined if the underlying estimator exposes such an attribute when fit. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Only defined if the underlying estimators expose such an attribute when fit. .. versionadded:: 1.0 final_estimator_ : estimator The regressor fit on the output of `estimators_` and responsible for final predictions. stack_method_ : list of str The method used by each base estimator. See Also -------- StackingClassifier : Stack of estimators with a final classifier. References ---------- .. [1] Wolpert, David H. "Stacked generalization." Neural networks 5.2 (1992): 241-259. Examples -------- >>> from sklearn.datasets import load_diabetes >>> from sklearn.linear_model import RidgeCV >>> from sklearn.svm import LinearSVR >>> from sklearn.ensemble import RandomForestRegressor >>> from sklearn.ensemble import StackingRegressor >>> X, y = load_diabetes(return_X_y=True) >>> estimators = [ ... ('lr', RidgeCV()), ... ('svr', LinearSVR(random_state=42)) ... ] >>> reg = StackingRegressor( ... estimators=estimators, ... final_estimator=RandomForestRegressor(n_estimators=10, ... random_state=42) ... ) >>> from sklearn.model_selection import train_test_split >>> X_train, X_test, y_train, y_test = train_test_split( ... X, y, random_state=42 ... ) >>> reg.fit(X_train, y_train).score(X_test, y_test) 0.3... NFr)r4r5r6r1c 2t||||d|||y)Nrcrr)r=r2r3r4r5r6r1r>s r?r<zStackingRegressor.__init__s, !+"#  r@c|jtt|js$t dj |jy)Nrz9'final_estimator' parameter should be a regressor. Got {})rErrrCrgrIrs r?rz+StackingRegressor._validate_final_estimatorsL ##GI#6D112KRR)) 3r@c `t||ddgt|d}t| ||fi|S)a@Fit the estimators. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) Target values. **fit_params : dict Parameters to pass to the underlying estimators. .. versionadded:: 1.6 Only available if `enable_metadata_routing=True`, which can be set by using ``sklearn.set_config(enable_metadata_routing=True)``. See :ref:`Metadata Routing User Guide ` for more details. Returns ------- self : object Returns a fitted instance. r-rprT)warn)rr'r;r-r=rYrur}r>s r?r-zStackingRegressor.fits86 *dE/9JK  &w{1a.:..r@c$|j|S)aReturn the predictions for X for each estimator. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. Returns ------- y_preds : ndarray of shape (n_samples, n_estimators) Prediction outputs for each estimator. rrs r?rzStackingRegressor.transformsq!!r@c Ft||ddgt|||fi|S)aFit the estimators and return the predictions for X for each estimator. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) Target values. **fit_params : dict Parameters to pass to the underlying estimators. .. versionadded:: 1.6 Only available if `enable_metadata_routing=True`, which can be set by using ``sklearn.set_config(enable_metadata_routing=True)``. See :ref:`Metadata Routing User Guide ` for more details. Returns ------- y_preds : ndarray of shape (n_samples, n_estimators) Prediction outputs for each estimator. r-rpr)rr; fit_transformrs r?rzStackingRegressor.fit_transform%s-6 *dE/9JKw$Q8Z88r@rcrrc trt|dfi|}n,t}ti|_||j_t ||fi|jd}|Sr)rrrrCrcr;)r=rYrrtrr>s r?rczStackingRegressor.predictDsdD  +D)N~NM"GM-22->M *5CM * * 2Pm&D&DY&OP r@ch|j t}n |j}t| |SrB)r3rr;rrs r?rz#StackingRegressor._sk_visual_block_rs3    '%iO"22Ow<_MMr@rB)rerrrr<rr-rrrr%rcrrrs@r?rrIsmK`  (/B" 9>y,ST))VNNr@r)?rabcrrcopyrnumbersrnumpyrX scipy.sparserUbaserr r r r r r exceptionsr linear_modelrrmodel_selectionrr preprocessingrutilsrutils._param_validationrrutils._repr_html.estimatorrutils.metadata_routingrrrrrutils.metaestimatorsrutils.multiclassrr utils.parallelr!r"utils.validationr#r$r%r&r'_baser)r*r,rrrr@r?r s( ((69(<50K.Er$&@Grj `N-`NF pN pNr@