B
    0dSq                 @   sb  d Z ddlmZmZ ddlmZ ddlZddlm	Z	 ddl
mZ ddlmZ ddlmZ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 ddlmZ ddlmZ ddlmZ ddlmZ ddl m!Z! ddl"m#Z# ddl$m%Z% ddl&m'Z' ddl(m)Z) ddl(m*Z* ddl+m,Z, G dd deeedZ-G dd dee-Z.G dd  d ee-Z/dS )!z"Stacking classifier and regressor.    )ABCMetaabstractmethod)deepcopyN)Parallel   )clone)ClassifierMixinRegressorMixinTransformerMixin)is_classifieris_regressor)NotFittedError)_VisualBlock   )_fit_single_estimator)_BaseHeterogeneousEnsemble)LogisticRegression)RidgeCV)cross_val_predict)check_cv)LabelEncoder)Bunch)if_delegate_has_method)check_classification_targets)check_is_fitted)column_or_1d)delayedc                   s   e Zd ZdZeddddddd fddZd	d
 Zdd Zedd Z	dddZ
edd Zdd Zedddd Zdd Z  ZS )_BaseStackingzBase class for stacking method.Nautor   F)cvstack_methodn_jobsverbosepassthroughc               s6   t  j|d || _|| _|| _|| _|| _|| _d S )N)
estimators)super__init__final_estimatorr   r    r!   r"   r#   )selfr$   r'   r   r    r!   r"   r#   )	__class__ L/var/www/html/venv/lib/python3.7/site-packages/sklearn/ensemble/_stacking.pyr&   )   s    z_BaseStacking.__init__c             C   s&   | j d k	rt| j | _n
t|| _d S )N)r'   r   final_estimator_)r(   defaultr*   r*   r+   _clone_final_estimator=   s    
z$_BaseStacking._clone_final_estimatorc             C   s   g }xtt |D ]h\}}|jdkr4||dd q| j| dkrlt| jdkrl||ddddf  q|| qW | jr|| t	|rtj
||jdS t
|S )a1  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)
        r   predict_probar   N)format)	enumeratendimappendZreshapestack_method_lenclasses_r#   sparseissparseZhstackr1   np)r(   XpredictionsX_metaZest_idxpredsr*   r*   r+   _concatenate_predictionsC   s    


z&_BaseStacking._concatenate_predictionsc             C   s\   |dkrd S |dkr:t |dd r$dS t |dd r4dS dS nt||sTtd| ||S d S )Ndropr   r0   decision_functionpredictz9Underlying estimator {} does not implement the method {}.)getattrhasattr
ValueErrorr1   )nameZ	estimatormethodr*   r*   r+   _method_nameg   s    

z_BaseStacking._method_namec                s|    \}}  jgt| }tjd fdd|D _t _d}xXt	||D ]J\}}	|	dkrj| }
|
j|< |d7 }t
|
dr|
j_q`dj|< q`W tjtdt
d	rjd
krtj _fddt	|||D _d
k	rdind
tjd fddt	|jD }dd t	j|D _ |}tj|d 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,) or default=None
            Sample weights. If None, then samples are equally weighted.
            Note that this is supported only if all underlying estimators
            support sample weights.

            .. versionchanged:: 0.23
               when not None, `sample_weight` is passed to all underlying
               estimators

        Returns
        -------
        self : object
        )r!   c             3   s,   | ]$}|d krt tt| V  qdS )r@   N)r   r   r   ).0est)r;   sample_weightyr*   r+   	<genexpr>   s   z$_BaseStacking.fit.<locals>.<genexpr>r   r@   r   feature_names_in_)rL   
classifierrandom_stateNc                s    g | ]\}}}  |||qS r*   )rH   )rI   rF   rJ   meth)r(   r*   r+   
<listcomp>   s   z%_BaseStacking.fit.<locals>.<listcomp>rK   c             3   sB   | ]:\}}|d krt tt| t|jjdV  qdS )r@   )r   rG   r!   
fit_paramsr"   N)r   r   r   r   r!   r"   )rI   rJ   rQ   )r;   r   rS   r(   rL   r*   r+   rM      s   
c             S   s   g | ]\}}|d kr|qS )r@   r*   )rI   rQ   rJ   r*   r*   r+   rR      s   )rK   )Z_validate_estimators_validate_final_estimatorr    r6   r   r!   estimators_r   Znamed_estimators_ziprD   rN   r   r   r   rP   r:   randomZRandomStater5   r?   r   r,   )r(   r;   rL   rK   namesZall_estimatorsr    Zest_fitted_idxZname_estZorg_estZcurrent_estimatorr<   r=   r*   )r;   r   rS   rK   r(   rL   r+   fit{   s>    







z_BaseStacking.fitc          
   C   sP   yt |  W n6 tk
rB } zt| jj d|W dd}~X Y nX | jd jS )z+Number of features seen during :term:`fit`.z' object has no attribute n_features_in_Nr   )r   r   AttributeErrorr)   __name__rU   n_features_in_)r(   Znfer*   r*   r+   r\      s    z_BaseStacking.n_features_in_c                s0   t |   fddt| j| jD }|  |S )z9Concatenate and return the predictions of the estimators.c                s&   g | ]\}}|d krt || qS )r@   )rC   )rI   rJ   rQ   )r;   r*   r+   rR      s   z,_BaseStacking._transform.<locals>.<listcomp>)r   rV   rU   r5   r?   )r(   r;   r<   r*   )r;   r+   
_transform   s    
z_BaseStacking._transformr,   )delegatec             K   s   t |  | jj| |f|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
            accounts for uncertainty in the final estimator.

        Returns
        -------
        y_pred : ndarray of shape (n_samples,) or (n_samples, n_output)
            Predicted targets.
        )r   r,   rB   	transform)r(   r;   predict_paramsr*   r*   r+   rB      s    z_BaseStacking.predictc             C   sD   t | j \}}td||dd}td|gdgdd}td||fddS )NparallelF)rX   dash_wrappedr'   serial)rb   )rV   r$   r   )r(   r'   rX   r$   ra   Zfinal_blockr*   r*   r+   _sk_visual_block_  s
    z_BaseStacking._sk_visual_block_)N)N)r[   
__module____qualname____doc__r   r&   r.   r?   staticmethodrH   rY   propertyr\   r]   r   rB   rd   __classcell__r*   r*   )r)   r+   r   &   s    
$
d
r   )	metaclassc                   s   e Zd ZdZddddddd fddZd	d
 Zd fdd	Zedd fddZedddd Z	edddd Z
dd Z fddZ  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`.

    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 or an iterable, 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.

        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.

        .. 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 all `estimators` `fit`.
        `None` means 1 unless in a `joblib.parallel_backend` context. -1 means
        using all processors. See 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,)
        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_`.

    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 classifier 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 which predicts given the output of `estimators_`.

    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.

    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...
    Nr   Fr   )r   r    r!   r#   r"   c         	      s   t  j|||||||d d S )N)r$   r'   r   r    r!   r#   r"   )r%   r&   )r(   r$   r'   r   r    r!   r#   r"   )r)   r*   r+   r&     s    zStackingClassifier.__init__c             C   s,   | j t d t| js(td| jd S )N)r-   z:'final_estimator' parameter should be a classifier. Got {})r.   r   r   r,   rE   r1   )r(   r*   r*   r+   rT     s
    
z,StackingClassifier._validate_final_estimatorc                s8   t | t || _| jj| _t || j||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.

        Returns
        -------
        self : object
            Returns a fitted instance of estimator.
        )r   r   rY   _ler7   r%   r_   )r(   r;   rL   rK   )r)   r*   r+   rY     s    
zStackingClassifier.fitr,   )r^   c                s   t  j|f|}| j|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
            accounts for uncertainty in the final estimator.

        Returns
        -------
        y_pred : ndarray of shape (n_samples,) or (n_samples, n_output)
            Predicted targets.
        )r%   rB   rm   Zinverse_transform)r(   r;   r`   Zy_pred)r)   r*   r+   rB     s    zStackingClassifier.predictc             C   s   t |  | j| |S )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.
        )r   r,   r0   r_   )r(   r;   r*   r*   r+   r0     s    z StackingClassifier.predict_probac             C   s   t |  | 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   r,   rA   r_   )r(   r;   r*   r*   r+   rA     s    z$StackingClassifier.decision_functionc             C   s
   |  |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(   r;   r*   r*   r+   r_   (  s    zStackingClassifier.transformc                s$   | j d krt }n| j }t |S )N)r'   r   r%   rd   )r(   r'   )r)   r*   r+   rd   9  s    
z$StackingClassifier._sk_visual_block_)N)N)r[   re   rf   rg   r&   rT   rY   r   rB   r0   rA   r_   rd   rj   r*   r*   )r)   r+   rl     s    	rl   c                   sX   e Zd ZdZdddddd fddZdd	 Zd fd
d	Zdd Z fddZ  Z	S )StackingRegressoral  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 or an iterable, 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.

        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.

        .. 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 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 estimator
        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_`.

    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 regressor 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 to stacked the base estimators fitted.

    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   )r   r!   r#   r"   c         	      s   t  j|||d|||d d S )NrB   )r$   r'   r   r    r!   r#   r"   )r%   r&   )r(   r$   r'   r   r!   r#   r"   )r)   r*   r+   r&     s    
zStackingRegressor.__init__c             C   s,   | j t d t| js(td| jd S )N)r-   z9'final_estimator' parameter should be a regressor. Got {})r.   r   r   r,   rE   r1   )r(   r*   r*   r+   rT     s
    
z+StackingRegressor._validate_final_estimatorc                s   t |dd}t |||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.

        Returns
        -------
        self : object
            Returns a fitted instance.
        T)warn)r   r%   rY   )r(   r;   rL   rK   )r)   r*   r+   rY     s    zStackingRegressor.fitc             C   s
   |  |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(   r;   r*   r*   r+   r_     s    zStackingRegressor.transformc                s$   | j d krt }n| j }t |S )N)r'   r   r%   rd   )r(   r'   )r)   r*   r+   rd   	  s    
z#StackingRegressor._sk_visual_block_)N)N)
r[   re   rf   rg   r&   rT   rY   r_   rd   rj   r*   r*   )r)   r+   rn   C  s   ~	rn   )0rg   abcr   r   copyr   numpyr:   Zjoblibr   Zscipy.sparser8   baser   r   r	   r
   r   r   
exceptionsr   Zutils._estimator_html_reprr   _baser   r   Zlinear_modelr   r   Zmodel_selectionr   r   Zpreprocessingr   utilsr   Zutils.metaestimatorsr   Zutils.multiclassr   Zutils.validationr   r   Zutils.fixesr   r   rl   rn   r*   r*   r*   r+   <module>   s:    t  ,