
    -i                        S r SSKJrJr  SSKJr  SSKJr  SSKr	SSK
Jr  SSKJrJrJrJrJrJrJr  SSKJr  SS	KJrJr  SS
KJrJr  SSKJr  SSKJr  SSK J!r!J"r"  SSK#J$r$  SSK%J&r&J'r'J(r(J)r)J*r*  SSK+J,r,  SSK-J.r.J/r/  SSK0J1r1J2r2  SSK3J4r4J5r5J6r6J7r7J8r8  SSK9J:r:J;r;   " S S\\:\S9r< " S S\\<5      r= " S S\\<5      r>g)z"Stacking classifier and regressor.    )ABCMetaabstractmethod)deepcopy)IntegralN   )ClassifierMixinRegressorMixinTransformerMixin_fit_contextcloneis_classifieris_regressor)NotFittedError)LogisticRegressionRidgeCV)check_cvcross_val_predict)LabelEncoder)Bunch)
HasMethods
StrOptions)_VisualBlock)MetadataRouterMethodMapping_raise_for_params_routing_enabledprocess_routing)available_if)check_classification_targetstype_of_target)Paralleldelayed)_check_feature_names_in_check_response_method_estimator_hascheck_is_fittedcolumn_or_1d   )_BaseHeterogeneousEnsemble_fit_single_estimatorc                     ^  \ rS rSr% Sr\/S\" S5      /S\" S15      /S\/S/S/S	.r	\
\S
'   \ SSSSSSS.U 4S jjj5       rS rS r\S 5       r\" SS9S 5       r\S 5       rS rSS jr\" \" SSS95      S 5       rS rS rSrU =r$ ) _BaseStacking1   zBase class for stacking method.Nfit	cv_objectprefitbooleanverbose)
estimatorsfinal_estimatorcvn_jobspassthroughr2   _parameter_constraintsautor   F)r5   stack_methodr6   r2   r7   c                h   > [         TU ]  US9  X l        X0l        X@l        XPl        X`l        Xpl        g )N)r3   )super__init__r4   r5   r:   r6   r2   r7   )	selfr3   r4   r5   r:   r6   r2   r7   	__class__s	           M/var/www/html/venv/lib/python3.13/site-packages/sklearn/ensemble/_stacking.pyr=   _BaseStacking.__init__=   s6     	J/.(&    c                 t    U R                   b  [        U R                   5      U l        g [        U5      U l        g N)r4   r   final_estimator_)r>   defaults     r@   _clone_final_estimator$_BaseStacking._clone_final_estimatorQ   s-    +$)$*>*>$?D!$)'ND!rB   c                    / n[        U5       H  u  pE[        U[        5      (       a%  U H  nUR                  USS2SS24   5        M     M?  UR                  S:X  a#  UR                  UR                  SS5      5        Mr  U R                  U   S:X  a5  [        U R                  5      S:X  a  UR                  USS2SS24   5        M  UR                  U5        M     U Vs/ s H  ofR                  S   PM     snU l
        U R                  (       aJ  UR                  U5        [        R                  " U5      (       a  [        R                  " X1R                  S9$ [         R                  " U5      $ s  snf )a  Concatenate 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
isinstancelistappendndimreshapestack_method_lenclasses_shape_n_feature_outsr7   sparseissparsehstackrL   np)r>   XpredictionsX_metaest_idxpredspreds          r@   _concatenate_predictions&_BaseStacking._concatenate_predictionsW   s!   $ '4NG%&& "DMM$q!"u+. "q emmB23""7+>&!+
 eAqrEl+e$1 54 ;AA&$

1&AMM!q!!}}VHH==yy    Bs   !E2c                     US:X  a  g US:X  a  / SQn [        X5      R                  nU$ ! [         a  n[        SU  SU S35      UeS nAff = f)Ndropr9   )rK   decision_functionpredictzUnderlying estimator z does not implement the method .)r$   __name__AttributeError
ValueError)name	estimatormethodmethod_namees        r@   _method_name_BaseStacking._method_name   sm    VFF	0CLLK   	'v-LVHTUV	s   * 
AAA)prefer_skip_nested_validationc           
      r  ^ ^^^^ T R                  5       u  pET R                  5         T R                  /[        U5      -  n[	        5       (       a  [        T S40 UD6mO<[        5       mU H,  n[        0 S9TU'   SU;   d  M  US   TU   R                  S'   M.     T R                  S:X  a?  / T l	        U H1  nUS:w  d  M  [        U5        T R                  R                  U5        M3     O3[        T R                  S9" UUU4S j[        XE5       5       5      T l	        [        5       T l        Sn	[        XE5       Hc  u  pUS:w  aI  T R                  U	   nUT R                  U
'   U	S	-  n	[!        US
5      (       a  UR"                  T l        MR  MT  ST R                  U
'   Me     [        XEU5       VVVs/ s H  u  p}nT R%                  X}U5      PM     snnnT l        T R                  S:X  aB  [        UT R&                  5       VVs/ s H  u  pUS:w  d  M  [)        X5      " T5      PM      nnnO[+        T R                  T[-        T 5      S9m[!        TS5      (       a0  TR.                  c#  [0        R2                  R5                  5       Tl        [        T R                  S9" UUUU U4S j[        XET R&                  5       5       5      n[        T R&                  U5       VVs/ s H  u  pUS:w  d  M  UPM     snnT l        T R7                  TU5      n[9        T R:                  UTUS9  T $ s  snnnf s  snnf s  snnf )ad  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
    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_weightr0   re   )r6   c              3      >#    U  H6  u  pUS :w  d  M  [        [        5      " [        U5      TTTU   S   5      v   M8     g7f)re   r.   N)r"   r*   r   ).0rl   estr\   routed_paramsys      r@   	<genexpr>$_BaseStacking.fit.<locals>.<genexpr>   sN      < "<ID&=	-.#J1mD&9%&@  "<s
   A.Ar   r(   feature_names_in_)rz   
classifierrandom_statec              3      >#    U  HV  u  pnUS :w  d  M  [        [        5      " [        U5      TT[        T5      UTR                  TU   S   TR
                  S9v   MX     g7f)re   r.   )r5   rn   r6   paramsr2   N)r"   r   r   r   r6   r2   )	rw   rl   rx   methr\   r5   ry   r>   rz   s	       r@   r{   r|      sh      7 (VODt&=	)*#J|;;(.u5 LL	 (Vs   A!AA!)
fit_params)_validate_estimators_validate_final_estimatorr:   rT   r   r   r   r.   r5   estimators_r&   rP   r!   r6   zipnamed_estimators_hasattrr}   rq   rS   getattrr   r   r   r[   randomRandomStaterb   r*   rE   )r>   r\   rz   r   namesall_estimatorsr:   rl   rm   est_fitted_idxname_estorg_estcurrent_estimatorrx   r   predict_methodr]   r^   r5   ry   s   ```               @@r@   r.   _BaseStacking.fit   s   < !% 9 9 ;&&())*S-@@+D%F:FM!GM&+md#"j0?I'@M$'++O<  77h!D+	&#I.$$++I6 ,  (t{{; < "%U!;	<  D "'!$U!;H& $($4$4^$D!3D&&x0!#,.ABB->-P-PD* C 4:&&x0 "< $'ul#K
#K4 d.#K

 77h 25^TEWEW1X1X-I& 6	2151X  K $''Q=3FGBr>**r/F"$))"7"7"9"$++6 7 7 (+5$BTBT'U7 K&  #4#5#5~F
Ff} F
 ..q+>d33VQ:Va
@
s   /L&L-L-L3-L3c                      [        U 5        U R
                  S   R                  $ ! [         a(  n[        U R                  R                   S35      UeSnAff = f)z+Number of features seen during :term:`fit`.z' object has no attribute n_features_in_Nr   )r&   r   rj   r?   ri   r   n_features_in_)r>   nfes     r@   r   _BaseStacking.n_features_in_  s`    	D!
 "111	  	 >>**++RS	s   & 
A#AAc                     [        U 5        [        U R                  U R                  5       VVs/ s H  u  p#US:w  d  M  [	        X#5      " U5      PM      nnnU R                  X5      $ s  snnf )z9Concatenate and return the predictions of the estimators.re   )r&   r   r   rS   r   rb   )r>   r\   rx   r   r]   s        r@   
_transform_BaseStacking._transform$  sl     !!1!143E3EF
F	f} "GCq!F 	 

 ,,Q<<
s
   A(A(c                   ^^ [        U S5        [        XU R                  S9nU R                  R                  R                  5       mS U R                   5       n/ n[        X R                  5       HI  u  mnUS:X  a  UR                  T ST 35        M$  UR                  UU4S j[        U5       5       5        MK     U R                  (       a  [        R                  " X145      $ [        R                  " U[        S9$ )a  Get 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_namesc              3   :   #    U  H  u  pUS :w  d  M  Uv   M     g7fre   N )rw   rl   rx   s      r@   r{   6_BaseStacking.get_feature_names_out.<locals>.<genexpr>K  s      "
"1YTSF]DD/s   	r(   _c              3   6   >#    U  H  nT S T U 3v   M     g7f)r   Nr   )rw   i
class_namerx   s     r@   r{   r   S  s$      "6Kzl!C5,6Ks   )dtype)r&   r#   r7   r?   ri   lowerr3   r   rW   rP   extendranger[   concatenateasarrayobject)r>   input_featuresnon_dropped_estimators
meta_namesn_features_outr   rx   s        @@r@   get_feature_names_out#_BaseStacking.get_feature_names_out.  s    . 	./01A1A
 ^^,,224
"
"&//"
 
#&'=?S?S#TC"!!ZL#"78!! "6;N6K" 	 $U >>:">??zz*F33rB   rg   rE   r4   	delegatesc                 p    [        U 5        U R                  R                  " U R                  U5      40 UD6$ )aq  Predict 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&   rE   rg   	transform)r>   r\   predict_paramss      r@   rg   _BaseStacking.predict\  s1    0 	$$,,T^^A->Q.QQrB   c                 t    [        U R                  6 u  p#[        SX2SS9n[        SU/S/SS9n[        SXE4SS9$ )NparallelF)r   dash_wrappedr4   serial)r   )r   r3   r   )r>   r4   r   r3   r   final_blocks         r@   %_sk_visual_block_with_final_estimator3_BaseStacking._sk_visual_block_with_final_estimatorw  sS    1
JRWX #)2C1DSX
 Hx&=ERRrB   c                 b   [        U R                  R                  S9nU R                   H2  u  p#UR                  " S0 X#0DS[        5       R	                  SSS90D6  M4      U R                  nUR	                  U[        5       R	                  SSS9S9  U$ ! [         a    U R                  n N@f = f)	a"  Get metadata routing of this object.

Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.

.. versionadded:: 1.6

Returns
-------
routing : MetadataRouter
    A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
    routing information.
)ownermethod_mappingr.   )calleecallerrg   )r   r   )rE   r   r   )	r   r?   ri   r3   addr   rE   rj   r4   )r>   routerrl   rm   rE   s        r@   get_metadata_routing"_BaseStacking.get_metadata_routing  s      dnn&=&=>  $ODJJ #,22%2N  /	4#44 	

-(?..i	.R 	 	

   	4#33	4s   !B B.-B.)rW   r5   r   r}   r4   rE   r6   r   r7   r:   rS   r2   rD   )ri   
__module____qualname____firstlineno____doc__rO   r   r   r   r8   dict__annotations__r   r=   rG   rb   staticmethodrq   r   r.   propertyr   r   r   r   r%   rg   r   r   __static_attributes____classcell__r?   s   @r@   r,   r,   1   s   ) f *U"34Jz23"!{;$D   '
 ' ' '&33!j   &+x	xt 2 2=,4\ y,STRR0	S! !rB   r,   )	metaclassc                   &  ^  \ rS rSr% Sr0 \R                  ES\" 1 Sk5      /0Er\\	S'    SSSSSS	S
.U 4S jjjr
S rS rU 4S jr\" \" SSS95      U 4S j5       r\" \" SSS95      S 5       r\" \" SSS95      S 5       rS rU 4S jrSrU =r$ )StackingClassifieri  a  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 :ref:`User Guide <stacking>`.

.. 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 <cross_validation>` 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 <n_jobs>` 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...
r:   >   r9   rg   rK   rf   r8   Nr9   Fr   )r5   r:   r6   r7   r2   c          
      ,   > [         TU ]  UUUUUUUS9  g )Nr3   r4   r5   r:   r6   r7   r2   r<   r=   )	r>   r3   r4   r5   r:   r6   r7   r2   r?   s	           r@   r=   StackingClassifier.__init__^  s,     	!+%# 	 	
rB   c                     U R                  [        5       S9  [        U R                  5      (       d$  [	        SR                  U R                  5      5      eg )NrF   z:'final_estimator' parameter should be a classifier. Got {})rG   r   r   rE   rk   rL   r>   s    r@   r   ,StackingClassifier._validate_final_estimators  sQ    ##,>,@#AT2233LSS))  4rB   c                     [        U R                  5      S:X  a  [        S5      e[        U R                  6 u  pU R	                  U5        [        S U 5       5      nU(       d  [        S5      eX4$ )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.
r   zfInvalid 'estimators' attribute, 'estimators' should be a non-empty list of (string, estimator) tuples.c              3   *   #    U  H	  oS :g  v   M     g7fr   r   )rw   rx   s     r@   r{   :StackingClassifier._validate_estimators.<locals>.<genexpr>  s     @Zc6MZs   zHAll estimators are dropped. At least one is required to be an estimator.)rT   r3   rk   r   _validate_namesany)r>   r   r3   has_estimators       r@   r   'StackingClassifier._validate_estimators|  sy     t1$@   1U#@Z@@& 
   rB   c           	        > [        X0SS/S9  [        U5        [        U5      S:X  a  UR                   Vs/ s H  n[	        5       R                  U5      PM     snU l        U R                   Vs/ s H  oUR                  PM     snU l        [        R                  " [        UR                  5       VVs/ s H#  u  pgU R                  U   R                  U5      PM%     snn5      R                  nOT[	        5       R                  U5      U l        U R                  R                  U l        U R                  R                  U5      n[        T	U ]  " X40 UD6$ s  snf s  snf s  snnf )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. 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 <metadata_routing>` for
        more details.

Returns
-------
self : object
    Returns a fitted instance of estimator.
r.   ru   allowzmultilabel-indicator)r   r   r    Tr   r.   _label_encoderrU   r[   arrayrM   r   r<   )
r>   r\   rz   r   ykle
target_idxtarget	y_encodedr?   s
            r@   r.   StackingClassifier.fit  s*   < 	*E/9JK$Q'! 66DECC"HCb<>#5#5b#9C"HD373F3FG3FR[[3FGDM /8n.<*
 ''
3==fE.<
 a  #/."4"4Q"7D //88DM++55a8Iw{16:66 #IGs   #E/E4*E 
rg   r   r   c           	        > [        5       (       a  [        U S40 UD6nO([        5       n[        0 S9Ul        X#R                  l        [
        TU ]  " U40 UR                  S   D6n[        U R                  [        5      (       af  [        R                  " [        UR                  5       VVs/ s H#  u  pVU R                  U   R                  U5      PM%     snn5      R                  nU$ U R                  R                  U5      nU$ s  snnf a,  Predict 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 <metadata_routing>` 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.
rg   )rg   )r   r   r   rE   rg   r<   rN   r   rO   r[   r   rM   r   inverse_transform)r>   r\   r   ry   y_predr   r   r?   s          r@   rg   StackingClassifier.predict  s    D +D)N~NM "GM-22->M*5C**2Pm&D&DY&OPd))400XX /8.A.A*
 ''
3EEfM.A
 a   ((::6BFs   ,*D
rK   c                 &   [        U 5        U R                  R                  U R                  U5      5      n[	        U R
                  [        5      (       a7  [        R                  " U Vs/ s H  o3SS2S4   PM     sn5      R                  nU$ s  snf )a  Predict 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&   rE   rK   r   rN   r   rO   r[   r   r   )r>   r\   r   r`   s       r@   rK    StackingClassifier.predict_proba  sr    ( 	&&44T^^A5FGd))400XX?uQT{?@BBF @s   )Brf   c                 l    [        U 5        U R                  R                  U R                  U5      5      $ )a  Decision 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&   rE   rf   r   r>   r\   s     r@   rf   $StackingClassifier.decision_function  s,    ( 	$$66t~~a7HIIrB   c                 $    U R                  U5      $ )a  Return 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.
r   r   s     r@   r   StackingClassifier.transform.  s     q!!rB   c                 j   > U R                   c  [        5       nOU R                   n[        TU ]  U5      $ rD   )r4   r   r<   r   r>   r4   r?   s     r@   _sk_visual_block_$StackingClassifier._sk_visual_block_?  s4     '02O"22Ow<_MMrB   )r   rU   rD   )ri   r   r   r   r   r,   r8   r   r   r   r=   r   r   r.   r   r%   rg   rK   rf   r   r  r   r   r   s   @r@   r   r     s    n`$

.
.$PQ
$D  

 
 
*!./7b y,ST22h 'N	


. +R	

J
J$""N NrB   r   c                      ^  \ rS rSrSr SSSSSS.U 4S jjjrS rU 4S	 jrS
 rU 4S jr	\
" \" SSS95      U 4S j5       rU 4S jrSrU =r$ )StackingRegressoriI  a  Stack 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 <stacking>`.

.. 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 <cross_validation>` 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 <n_jobs>` 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   )r5   r6   r7   r2   c          
      ,   > [         TU ]  UUUSUUUS9  g )Nrg   r   r   )r>   r3   r4   r5   r6   r7   r2   r?   s          r@   r=   StackingRegressor.__init__  s,     	!+"# 	 	
rB   c                     U R                  [        5       S9  [        U R                  5      (       d$  [	        SR                  U R                  5      5      eg )Nr   z9'final_estimator' parameter should be a regressor. Got {})rG   r   r   rE   rk   rL   r   s    r@   r   +StackingRegressor._validate_final_estimator  sO    ##GI#6D1122KRR))  3rB   c                 R   > [        X0SS/S9  [        USS9n[        TU ]  " X40 UD6$ )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 <metadata_routing>` for
        more details.

Returns
-------
self : object
    Returns a fitted instance.
r.   ru   r   T)warn)r   r'   r<   r.   r>   r\   rz   r   r?   s       r@   r.   StackingRegressor.fit  s4    6 	*E/9JK&w{1.:..rB   c                 $    U R                  U5      $ )ak  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.

Returns
-------
y_preds : ndarray of shape (n_samples, n_estimators)
    Prediction outputs for each estimator.
r   r   s     r@   r   StackingRegressor.transform  s     q!!rB   c                 >   > [        X0SS/S9  [        TU ]  " X40 UD6$ )a  Fit 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 <metadata_routing>` for
        more details.

Returns
-------
y_preds : ndarray of shape (n_samples, n_estimators)
    Prediction outputs for each estimator.
r.   ru   r   )r   r<   fit_transformr  s       r@   r  StackingRegressor.fit_transform%  s)    6 	*E/9JKw$Q8Z88rB   rg   r   r   c                    > [        5       (       a  [        U S40 UD6nO([        5       n[        0 S9Ul        X#R                  l        [
        TU ]  " U40 UR                  S   D6nU$ r   )r   r   r   rE   rg   r<   )r>   r\   r   ry   r   r?   s        r@   rg   StackingRegressor.predictD  se    D +D)N~NM "GM-22->M*5C**2Pm&D&DY&OPrB   c                 j   > U R                   c  [        5       nOU R                   n[        TU ]  U5      $ rD   )r4   r   r<   r   r  s     r@   r  #StackingRegressor._sk_visual_block_r  s3     '%iO"22Ow<_MMrB   r   rD   )ri   r   r   r   r   r=   r   r.   r   r  r   r%   rg   r  r   r   r   s   @r@   r  r  I  sr    K` 

 
 
(/B" 9> y,ST))VN NrB   r  )?r   abcr   r   copyr   numbersr   numpyr[   scipy.sparserX   baser   r	   r
   r   r   r   r   
exceptionsr   linear_modelr   r   model_selectionr   r   preprocessingr   utilsr   utils._param_validationr   r   utils._repr_html.estimatorr   utils.metadata_routingr   r   r   r   r   utils.metaestimatorsr   utils.multiclassr   r    utils.parallelr!   r"   utils.validationr#   r$   r%   r&   r'   _baser)   r*   r,   r   r  r   rB   r@   <module>r*     s    (
 (       ( 6 9 (  < 5  0 K .  Er$&@G rj`N- `NFpN pNrB   