
    >[gJ                        d Z ddlmZmZ ddlmZ ddlmZ ddlZ	ddl
mZ ddlmZmZmZmZmZmZmZ ddlmZ dd	lmZmZ dd
lmZmZ ddlmZ ddlmZ ddl m!Z! ddl"m#Z#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z)m*Z* ddl+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z;m<Z<  G d dee;e      Z= G d dee=      Z> G d dee=      Z?y)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)_VisualBlock)
HasMethods
StrOptions)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_deprecate_positional_args_estimator_hascheck_is_fittedcolumn_or_1d   )_BaseHeterogeneousEnsemble_fit_single_estimatorc                       e Zd ZU dZegd ed      gd edh      gdegdgdgdZe	e
d	<   e	 ddd
dddd fd       Zd Zd Zed        Z ed      d        Zed        Zd ZddZ e edd            d        Zd Zd Z xZS )_BaseStackingz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                z    t         |   |       || _        || _        || _        || _        || _        || _        y )N)r3   )super__init__r4   r5   r:   r6   r2   r7   )	selfr3   r4   r5   r:   r6   r2   r7   	__class__s	           U/var/www/html/bid-api/venv/lib/python3.12/site-packages/sklearn/ensemble/_stacking.pyr=   z_BaseStacking.__init__>   sB     	J/.(&    c                 r    | j                   t        | j                         | _        y t        |      | _        y N)r4   r   final_estimator_)r>   defaults     r@   _clone_final_estimatorz$_BaseStacking._clone_final_estimatorR   s-    +$)$*>*>$?D!$)'ND!rA   c                    g }t        |      D ]  \  }}t        |t              r"|D ]  }|j                  |ddddf           8|j                  dk(  r"|j                  |j                  dd             i| j                  |   dk(  r3t        | j                        dk(  r|j                  |ddddf          |j                  |        |D cg c]  }|j                  d    c}| _
        | j                  rG|j                  |       t        j                  |      r!t        j                  ||j                        S t!        j                  |      S c c}w )ad  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hstackrJ   np)r>   XpredictionsX_metaest_idxpredspreds          r@   _concatenate_predictionsz&_BaseStacking._concatenate_predictionsX   s!   $ '4NGU%& "DMM$q!"u+. "q emmB23""7+>&!+
 eAqrEl+e$1 54 ;AA&$

1&AMM!q!}}VAHH==yy    Bs   Ec                     |dk(  ry |dk(  rg d}	 t        ||      j                  }|S # t        $ r}t        d|  d| d      |d }~ww xY w)Ndropr9   )rI   decision_functionpredictzUnderlying estimator z does not implement the method .)r$   __name__AttributeError
ValueError)name	estimatormethodmethod_namees        r@   _method_namez_BaseStacking._method_name   so    VFF	0FCLLK   	'v-LVHTUV	s   ) 	A
AA
)prefer_skip_nested_validationc           
      D     j                         \  }} j                           j                  gt        |      z  }t	               rt         dfi |n:t               |D ]+  }t        i       |<   d|v s|d   |   j                  d<   -  j                  dk(  r;g  _	        |D ].  }|dk7  s	t        |        j                  j                  |       0 n6 t         j                        fdt        ||      D               _	        t                _        d}	t        ||      D ][  \  }
}|dk7  rB j                  |	   }| j                  |
<   |	d	z  }	t!        |d
      s;|j"                   _        Md j                  |
<   ] t        |||      D cg c]  \  }}} j%                  |||       c}}} _         j                  dk(  r>t        | j&                        D cg c]  \  }}|dk7  r t)        ||             }}}nt+         j                  t-                     t!        d      r/j.                  #t0        j2                  j5                         _         t         j                         fdt        || j&                        D              }t         j&                  |      D cg c]  \  }}|dk7  r| c}} _         j7                  |      }t9         j:                  ||        S c c}}}w c c}}w c c}}w )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
            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   rb   )r6   c              3   |   K   | ]3  \  }}|d k7  r) t        t              t        |      |   d          5 yw)rb   r.   N)r"   r+   r   ).0ri   estrZ   routed_paramsys      r@   	<genexpr>z$_BaseStacking.fit.<locals>.<genexpr>   sL      < "<ID#&=	 /-.#J1mD&9%&@ "<s   9<r   r)   feature_names_in_)rv   
classifierrandom_statec              3      K   | ]V  \  }}}|d k7  rK t        t              t        |      t              |j                  |   d   j
                         X yw)rb   r.   )r5   rk   r6   paramsr2   N)r"   r   r   r   r6   r2   )	rs   ri   rt   methrZ   r5   ru   r>   rv   s	       r@   rw   z$_BaseStacking.fit.<locals>.<genexpr>   sp      7 (VOD#t&= +)*#J|;;(.u5 LL	 	 (Vs   AA)
fit_params)_validate_estimators_validate_final_estimatorr:   rR   r   r   r   r.   r5   estimators_r'   rN   r!   r6   zipnamed_estimators_hasattrrx   rn   rQ   getattrr   r   rz   rY   randomRandomStater`   r+   rD   )r>   rZ   rv   r~   namesall_estimatorsr:   ri   rj   est_fitted_idxname_estorg_estcurrent_estimatorrt   r}   predict_methodr[   r\   r5   ru   s   ```               @@r@   r.   z_BaseStacking.fit   s   < !% 9 9 ;~&&())*S-@@+D%F:FM!GM&+md#"j0?I'@M$'++O<  77h!D+	&#I.$$++I6 ,  <xt{{; < "%UN!;	<  D "'!$UN!;Hg& $($4$4^$D!3D&&x0!#,.AB->-P-PD*39&&x0 "< $'unl#K
#Kc4 dC.#K

 77h 25^TEWEW1X1X-I~& 3	>2151X   $''Q=3FGBr>*r/F"$))"7"7"96($++6 7 (+5.$BTBT'U7 K&  #4#5#5~F
Fsf} F
 ..q+>d33VQ:Va
@
s    L0!LLc                     	 t        |        | j
                  d   j                  S # t        $ r(}t        | j                  j                   d      |d}~ww xY w)z+Number of features seen during :term:`fit`.z' object has no attribute n_features_in_Nr   )r'   r   rg   r?   rf   r   n_features_in_)r>   nfes     r@   r   z_BaseStacking.n_features_in_  s`    	D!
 "111	  	 >>**++RS	s   & 	A#AAc           	          t        |        t        | j                  | j                        D cg c]  \  }}|dk7  r t	        ||      |       }}}| j                  ||      S c c}}w )z9Concatenate and return the predictions of the estimators.rb   )r'   r   r   rQ   r   r`   )r>   rZ   rt   r}   r[   s        r@   
_transformz_BaseStacking._transform%  sr     !!1!143E3EF
F	Tf} GCq!F 	 

 ,,Q<<
s   !A%c                    t        | d       t        | || j                        }| j                  j                  j                         d | j                  D        }g }t        || j                        D ]E  \  }|dk(  r|j                   d        "|j                  fdt        |      D               G | j                  rt        j                  ||f      S t        j                  |t              S )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   2   K   | ]  \  }}|d k7  s|  ywrb   N )rs   ri   rt   s      r@   rw   z6_BaseStacking.get_feature_names_out.<locals>.<genexpr>L  s      "
"1YT3SF]D/s   r)   _c              3   0   K   | ]  } d  |   yw)r   Nr   )rs   i
class_namert   s     r@   rw   z6_BaseStacking.get_feature_names_out.<locals>.<genexpr>T  s%      "6Kzl!C5,6Ks   )dtype)r'   r#   r7   r?   rf   lowerr3   r   rU   rN   extendrangerY   concatenateasarrayobject)r>   input_featuresnon_dropped_estimators
meta_namesn_features_outr   rt   s        @@r@   get_feature_names_outz#_BaseStacking.get_feature_names_out/  s    . 	./0.1A1A
 ^^,,224
"
"&//"
 
#&'=t?S?S#TC"!!ZL#"78!! "6;N6K" 	 $U >>:~">??zz*F33rA   rd   rD   r4   	delegatesc                 p    t        |         | j                  j                  | j                  |      fi |S )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.

        Returns
        -------
        y_pred : ndarray of shape (n_samples,) or (n_samples, n_output)
            Predicted targets.
        )r'   rD   rd   	transform)r>   rZ   predict_paramss      r@   rd   z_BaseStacking.predict]  s3    0 	,t$$,,T^^A->Q.QQrA   c                     t        | j                   \  }}t        d||d      }t        d|gdgd      }t        d||fd      S )NparallelF)r   dash_wrappedr4   serial)r   )r   r3   r   )r>   r4   r   r3   r   final_blocks         r@   %_sk_visual_block_with_final_estimatorz3_BaseStacking._sk_visual_block_with_final_estimatorx  sY    1z
JeRWX #)2C1DSX
 Hx&=ERRrA   c           
      x   t        | j                  j                        }| j                  D ]6  \  }} |j                  di ||idt               j	                  dd      i 8 	 | j                  }|j	                  |t               j	                  dd             |S # t        $ r | j                  }Y Ew xY w)	aj  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callerrd   )r   r   )rD   r   r   )	r   r?   rf   r3   addr   rD   rg   r4   )r>   routerri   rj   rD   s        r@   get_metadata_routingz"_BaseStacking.get_metadata_routing  s      dnn&=&=>  $OD)FJJ #,22%2N  /	4#44 	

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

   	4#33	4s   'B! !B98B9rC   )rf   
__module____qualname____doc__rM   r   r   r   r8   dict__annotations__r   r=   rF   r`   staticmethodrn   r   r.   propertyr   r   r   r   r&   rd   r   r   __classcell__r?   s   @r@   r-   r-   2   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!rA   r-   )	metaclassc                   B    e Zd ZU dZi ej
                  d eh d      giZeed<   	 ddddddd	 fd
Z	d Z
d Z ed      dd fd
       Z e edd             fd       Z e edd            d        Z e edd            d        Zd Z fdZ xZS )StackingClassifiera  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   rd   rI   rc   r8   Nr9   Fr   )r5   r:   r6   r7   r2   c          	      2    t         |   |||||||       y )Nr3   r4   r5   r:   r6   r7   r2   r<   r=   )	r>   r3   r4   r5   r:   r6   r7   r2   r?   s	           r@   r=   zStackingClassifier.__init___  s,     	!+%# 	 	
rA   c                     | j                  t                      t        | j                        s$t	        dj                  | j                              y )NrE   z:'final_estimator' parameter should be a classifier. Got {})rF   r   r   rD   rh   rJ   r>   s    r@   r   z,StackingClassifier._validate_final_estimatort  sN    ##,>,@#AT223LSS))  4rA   c                     t        | j                        dk(  rt        d      t        | j                   \  }}| j	                  |       t        d |D              }|st        d      ||fS )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   &   K   | ]	  }|d k7    ywr   r   )rs   rt   s     r@   rw   z:StackingClassifier._validate_estimators.<locals>.<genexpr>  s     @ZcC6MZs   zHAll estimators are dropped. At least one is required to be an estimator.)rR   r3   rh   r   _validate_namesany)r>   r   r3   has_estimators       r@   r   z'StackingClassifier._validate_estimators}  s}     t1$@   1zU#@Z@@& 
 j  rA   1.7versionrq   c          	         t        || d       t        |       t        |      dk(  r|j                  D cg c]  }t	               j                  |       c}| _        | j                  D cg c]  }|j                   c}| _        t        j                  t        |j                        D cg c]#  \  }}| j                  |   j                  |      % c}}      j                  }	nTt	               j                  |      | _        | j                  j                  | _        | j                  j                  |      }	|||d<   t        
|   ||	fi |S c c}w c c}w c c}}w )aL  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`.

        sample_weight : array-like of shape (n_samples,), default=None
            Sample weights. If None, then samples are equally weighted.
            Note that this is supported only if all underlying estimators
            support sample weights.

        **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.   zmultilabel-indicatorrq   )r   r   r    Tr   r.   _label_encoderrS   rY   arrayrK   r   r<   )r>   rZ   rv   rq   r~   ykle
target_idxtarget	y_encodedr?   s             r@   r.   zStackingClassifier.fit  s>   H 	*dE2$Q'! 66DECC"HCb<>#5#5b#9C"HD373F3FG3FRR[[3FGDM /8n.<*
F ''
3==fE.<
 a  #/."4"4Q"7D //88DM++55a8I$*7J'w{1i6:66 #IGs    E,E.(E
rd   r   r   c           	         t               rt        | dfi |}n,t               }t        i       |_        ||j                  _        t        |   |fi |j                  d   }t        | j                  t              rct        j                  t        |j                        D cg c]#  \  }}| j                  |   j                  |      % c}}      j                  }|S | j                  j                  |      }|S c c}}w 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.
        rd   )rd   )r   r   r   rD   rd   r<   rL   r   rM   rY   r   rK   r   inverse_transform)r>   rZ   r   ru   y_predr   r   r?   s          r@   rd   zStackingClassifier.predict  s    D +D)N~NM "GM-22->M*5CM**2Pm&D&DY&OPd))40XX /8.A.A*
F ''
3EEfM.A
 a   ((::6BFs   $(C=
rI   c                    t        |        | j                  j                  | j                  |            }t	        | j
                  t              r4t        j                  |D cg c]  }|dddf    c}      j                  }|S c c}w )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'   rD   rI   r   rL   r   rM   rY   r   r   )r>   rZ   r   r^   s       r@   rI   z StackingClassifier.predict_proba  sq    ( 	&&44T^^A5FGd))40XX?uuQT{?@BBF @s   #Brc   c                 l    t        |        | j                  j                  | j                  |            S )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'   rD   rc   r   r>   rZ   s     r@   rc   z$StackingClassifier.decision_function"  s,    ( 	$$66t~~a7HIIrA   c                 $    | j                  |      S )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   zStackingClassifier.transform9  s     q!!rA   c                 h    | j                   t               }n| j                   }t        |   |      S rC   )r4   r   r<   r   r>   r4   r?   s     r@   _sk_visual_block_z$StackingClassifier._sk_visual_block_J  s4     '02O"22Ow<_MMrA   rC   )rf   r   r   r   r-   r8   r   r   r   r=   r   r   r%   r.   r   r&   rd   rI   rc   r   r   r   r   s   @r@   r   r     s
   n`$

.
.$PQ
$D  

 
*!4  .)- 57 /57n y,ST22h 'N	


. +R	

J
J$""N NrA   r   c                        e Zd ZdZ	 dddddd fdZd Z ed	      dd
 fd
       Zd Z ed	      dd
 fd
       Z	 e
 edd             fd       Z fdZ xZS )StackingRegressorag  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          	      2    t         |   |||d|||       y )Nrd   r   r   )r>   r3   r4   r5   r6   r7   r2   r?   s          r@   r=   zStackingRegressor.__init__  s,     	!+"# 	 	
rA   c                     | j                  t                      t        | j                        s$t	        dj                  | j                              y )Nr   z9'final_estimator' parameter should be a regressor. Got {})rF   r   r   rD   rh   rJ   r   s    r@   r   z+StackingRegressor._validate_final_estimator  sL    ##GI#6D112KRR))  3rA   r   r   r   c                h    t        || d       t        |d      }|||d<   t        |   ||fi |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.

        sample_weight : array-like of shape (n_samples,), default=None
            Sample weights. If None, then samples are equally weighted.
            Note that this is supported only if all underlying estimators
            support sample weights.

        **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.   T)warnrq   )r   r(   r<   r.   r>   rZ   rv   rq   r~   r?   s        r@   r.   zStackingRegressor.fit  sD    B 	*dE2&$*7J'w{1a.:..rA   c                 $    | j                  |      S )a  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   zStackingRegressor.transform)  s     q!!rA   c                N    t        || d       |||d<   t        |   ||fi |S )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.

        sample_weight : array-like of shape (n_samples,), default=None
            Sample weights. If None, then samples are equally weighted.
            Note that this is supported only if all underlying estimators
            support sample weights.

        **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.   rq   )r   r<   fit_transformr   s        r@   r   zStackingRegressor.fit_transform<  s9    B 	*dE2$*7J'w$Q8Z88rA   rd   r   r   c                     t               rt        | dfi |}n,t               }t        i       |_        ||j                  _        t        |   |fi |j                  d   }|S r   )r   r   r   rD   rd   r<   )r>   rZ   r   ru   r   r?   s        r@   rd   zStackingRegressor.predictb  sd    D +D)N~NM "GM-22->M*5CM**2Pm&D&DY&OPrA   c                 h    | j                   t               }n| j                   }t        |   |      S rC   )r4   r   r<   r   r   s     r@   r   z#StackingRegressor._sk_visual_block_  s3     '%iO"22Ow<_MMrA   rC   )rf   r   r   r   r=   r   r%   r.   r   r   r   r&   rd   r   r   r   s   @r@   r   r   T  s    K` 

 
(  .)- $/ /$/L"&  .37 #9 /#9J y,ST))VN NrA   r   )@r   abcr   r   copyr   numbersr   numpyrY   scipy.sparserV   baser   r	   r
   r   r   r   r   
exceptionsr   linear_modelr   r   model_selectionr   r   preprocessingr   utilsr   utils._estimator_html_reprr   utils._param_validationr   r   utils.metadata_routingr   r   r   r   r   utils.metaestimatorsr   utils.multiclassr   r    utils.parallelr!   r"   utils.validationr#   r$   r%   r&   r'   r(   _baser*   r+   r-   r   r   r   rA   r@   <module>r     s    (
 (       ( 6 9 (  5 <  0 K .  Er$&@G rjjN- jNZCN CNrA   