3
Y]e                 @   sL  d Z ddlZddljZddlmZmZ ddl	m
Z
mZmZ ddl	mZmZmZ ddlmZ ddlmZmZmZ dd	lmZ dd
lmZ ddlmZmZ ddlmZ ddlm Z m!Z! ddddgZ"d ddZ#d!ddZ$G dd de
eedZ%G dd de%eZ&G dd de%eZ'G dd de
edZ(G dd de(eeZ)G dd de(eeZ*dS )"a  
This module implements multioutput regression and classification.

The estimators provided in this module are meta-estimators: they require
a base estimator to be provided in their constructor. The meta-estimator
extends single output estimators to multioutput estimators.
    N)ABCMetaabstractmethod   )BaseEstimatorcloneMetaEstimatorMixin)RegressorMixinClassifierMixinis_classifier)cross_val_predict)check_array	check_X_ycheck_random_state)parallel_helper)if_delegate_has_method)check_is_fittedhas_fit_parameter)check_classification_targets)ParalleldelayedMultiOutputRegressorMultiOutputClassifierClassifierChainRegressorChainc             C   s2   t | } |d k	r"| j|||d n| j|| | S )N)sample_weight)r   fit)	estimatorXyr    r   2lib/python3.6/site-packages/sklearn/multioutput.py_fit_estimator"   s
    r!   Tc             C   sl   |rt | } |d k	rB|d k	r0| j||||d qh| j|||d n&|d k	r\| j|||d n| j|| | S )N)classesr   )r   )r"   )r   partial_fit)r   r   r   r"   r   
first_timer   r   r    _partial_fit_estimator+   s    

r%   c               @   sF   e Zd ZedddZeddddZdddZd	d
 Zdd Z	dS )MultiOutputEstimatorNc             C   s   || _ || _d S )N)r   n_jobs)selfr   r'   r   r   r    __init__@   s    zMultiOutputEstimator.__init__r   c                s   t  ddd\ jdkr&tddk	rDtjd rDtdtd tjd	 fd
dtj	d D _
S )aD  Incrementally fit the model to data.
        Fit a separate model for each output variable.

        Parameters
        ----------
        X : (sparse) array-like, shape (n_samples, n_features)
            Data.

        y : (sparse) array-like, shape (n_samples, n_outputs)
            Multi-output targets.

        classes : list of numpy arrays, shape (n_outputs)
            Each array is unique classes for one output in str/int
            Can be obtained by via
            ``[np.unique(y[:, i]) for i in range(y.shape[1])]``, where y is the
            target matrix of the entire dataset.
            This argument is required for the first call to partial_fit
            and can be omitted in the subsequent calls.
            Note that y doesn't need to contain all labels in `classes`.

        sample_weight : array-like, shape = (n_samples) or None
            Sample weights. If None, then samples are equally weighted.
            Only supported if the underlying regressor supports sample
            weights.

        Returns
        -------
        self : object
        T)multi_outputaccept_sparser   zQy must have at least two dimensions for multi-output regression but has only one.Nr   z5Underlying estimator does not support sample weights.estimators_)r'   c             3   sP   | ]H}t tsj| nj d d |f d k	r>| nd V  qd S )N)r   r%   r,   r   ).0i)r   r"   r$   r   r(   r   r   r    	<genexpr>t   s   z3MultiOutputEstimator.partial_fit.<locals>.<genexpr>)r   ndim
ValueErrorr   r   hasattrr   r'   rangeshaper,   )r(   r   r   r"   r   r   )r   r"   r$   r   r(   r   r    r#   E   s    

z MultiOutputEstimator.partial_fitc                s   t jdstdt ddd\ tr8t jdkrJtddk	rhtjd rhtd	tj	d
 fddt
jd D _S )a   Fit the model to data.
        Fit a separate model for each output variable.

        Parameters
        ----------
        X : (sparse) array-like, shape (n_samples, n_features)
            Data.

        y : (sparse) array-like, shape (n_samples, n_outputs)
            Multi-output targets. An indicator matrix turns on multilabel
            estimation.

        sample_weight : array-like, shape = (n_samples) or None
            Sample weights. If None, then samples are equally weighted.
            Only supported if the underlying regressor supports sample
            weights.

        Returns
        -------
        self : object
        r   z0The base estimator should implement a fit methodT)r*   r+   r   zQy must have at least two dimensions for multi-output regression but has only one.Nr   z5Underlying estimator does not support sample weights.)r'   c             3   s.   | ]&}t tj d d |f V  qd S )N)r   r!   r   )r-   r.   )r   r   r(   r   r   r    r/      s   z+MultiOutputEstimator.fit.<locals>.<genexpr>)r2   r   r1   r   r
   r   r0   r   r   r'   r3   r4   r,   )r(   r   r   r   r   )r   r   r(   r   r    r   {   s     

zMultiOutputEstimator.fitc                sV   t | d t| jdstdt dd t| jd fdd| jD }tj	|j
S )	a  Predict multi-output variable using a model
         trained for each target variable.

        Parameters
        ----------
        X : (sparse) array-like, shape (n_samples, n_features)
            Data.

        Returns
        -------
        y : (sparse) array-like, shape (n_samples, n_outputs)
            Multi-output targets predicted across multiple predictors.
            Note: Separate models are generated for each predictor.
        r,   predictz4The base estimator should implement a predict methodT)r+   )r'   c             3   s   | ]}t t|d  V  qdS )r5   N)r   r   )r-   e)r   r   r    r/      s   z/MultiOutputEstimator.predict.<locals>.<genexpr>)r   r2   r   r1   r   r   r'   r,   npZasarrayT)r(   r   r   r   )r   r    r5      s    


zMultiOutputEstimator.predictc             C   s   ddiS )Nmultioutput_onlyTr   )r(   r   r   r    
_more_tags   s    zMultiOutputEstimator._more_tags)N)NN)N)
__name__
__module____qualname__r   r)   r   r#   r   r5   r:   r   r   r   r    r&   >   s   5
1r&   )	metaclassc                   sB   e Zd ZdZd
 fdd	Zedd fdd	Zddd	Z  ZS )r   a  Multi target regression

    This strategy consists of fitting one regressor per target. This is a
    simple strategy for extending regressors that do not natively support
    multi-target regression.

    Parameters
    ----------
    estimator : estimator object
        An estimator object implementing `fit` and `predict`.

    n_jobs : int or None, optional (default=None)
        The number of jobs to run in parallel for `fit`.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

        When individual estimators are fast to train or predict
        using `n_jobs>1` can result in slower performance due
        to the overhead of spawning processes.

    Attributes
    ----------
    estimators_ : list of ``n_output`` estimators
        Estimators used for predictions.
    Nc                s   t  j|| d S )N)superr)   )r(   r   r'   )	__class__r   r    r)      s    zMultiOutputRegressor.__init__r   c                s   t  j|||d dS )aY  Incrementally fit the model to data.
        Fit a separate model for each output variable.

        Parameters
        ----------
        X : (sparse) array-like, shape (n_samples, n_features)
            Data.

        y : (sparse) array-like, shape (n_samples, n_outputs)
            Multi-output targets.

        sample_weight : array-like, shape = (n_samples) or None
            Sample weights. If None, then samples are equally weighted.
            Only supported if the underlying regressor supports sample
            weights.

        Returns
        -------
        self : object
        )r   N)r?   r#   )r(   r   r   r   )r@   r   r    r#      s    z MultiOutputRegressor.partial_fitc             C   s"   ddl m} ||| j||ddS )aE  Returns the coefficient of determination R^2 of the prediction.

        The coefficient R^2 is defined as (1 - u/v), where u is the residual
        sum of squares ((y_true - y_pred) ** 2).sum() and v is the regression
        sum of squares ((y_true - y_true.mean()) ** 2).sum().
        Best possible score is 1.0 and it can be negative (because the
        model can be arbitrarily worse). A constant model that always
        predicts the expected value of y, disregarding the input features,
        would get a R^2 score of 0.0.

        Notes
        -----
        R^2 is calculated by weighting all the targets equally using
        `multioutput='uniform_average'`.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Test samples.

        y : array-like, shape (n_samples) or (n_samples, n_outputs)
            True values for X.

        sample_weight : array-like, shape [n_samples], optional
            Sample weights.

        Returns
        -------
        score : float
            R^2 of self.predict(X) wrt. y.
        r   )r2_scoreZuniform_average)r   Zmultioutput)ZmetricsrA   r5   )r(   r   r   r   rA   r   r   r    score  s    !zMultiOutputRegressor.score)N)N)N)	r;   r<   r=   __doc__r)   r   r#   rB   __classcell__r   r   )r@   r    r      s
   c                   s:   e Zd ZdZd fdd	Zdd Zdd Zd	d
 Z  ZS )r   a/  Multi target classification

    This strategy consists of fitting one classifier per target. This is a
    simple strategy for extending classifiers that do not natively support
    multi-target classification

    Parameters
    ----------
    estimator : estimator object
        An estimator object implementing `fit`, `score` and `predict_proba`.

    n_jobs : int or None, optional (default=None)
        The number of jobs to use for the computation.
        It does each target variable in y in parallel.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    Attributes
    ----------
    estimators_ : list of ``n_output`` estimators
        Estimators used for predictions.
    Nc                s   t  j|| d S )N)r?   r)   )r(   r   r'   )r@   r   r    r)   D  s    zMultiOutputClassifier.__init__c                s>   t | d tdd | jD s&td fdd| jD }|S )am  Probability estimates.
        Returns prediction probabilities for each class of each output.

        This method will raise a ``ValueError`` if any of the
        estimators do not have ``predict_proba``.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Data

        Returns
        -------
        p : array of shape = [n_samples, n_classes], or a list of n_outputs             such arrays if n_outputs > 1.
            The class probabilities of the input samples. The order of the
            classes corresponds to that in the attribute `classes_`.
        r,   c             S   s   g | ]}t |d qS )predict_proba)r2   )r-   r   r   r   r    
<listcomp>[  s   z7MultiOutputClassifier.predict_proba.<locals>.<listcomp>z8The base estimator should implement predict_proba methodc                s   g | ]}|j  qS r   )rE   )r-   r   )r   r   r    rF   `  s    )r   allr,   r1   )r(   r   Zresultsr   )r   r    rE   G  s    


z#MultiOutputClassifier.predict_probac             C   sl   t | d t| j}|jdkr&td|jd |krJtdj||jd | j|}tj	tj
||kddS )a~  Returns the mean accuracy on the given test data and labels.

        Parameters
        ----------
        X : array-like, shape [n_samples, n_features]
            Test samples

        y : array-like, shape [n_samples, n_outputs]
            True values for X

        Returns
        -------
        scores : float
            accuracy_score of self.predict(X) versus y
        r,   r   zTy must have at least two dimensions for multi target classification but has only onezCThe number of outputs of Y for fit {0} and score {1} should be same)Zaxis)r   lenr,   r0   r1   r4   formatr5   r7   ZmeanrG   )r(   r   r   Z
n_outputs_Zy_predr   r   r    rB   d  s    



zMultiOutputClassifier.scorec             C   s   ddiS )N
_skip_testTr   )r(   r   r   r    r:     s    z MultiOutputClassifier._more_tags)N)	r;   r<   r=   rC   r)   rE   rB   r:   rD   r   r   )r@   r    r   +  s
   c               @   s*   e Zd ZdddZedd Zdd ZdS )	
_BaseChainNc             C   s   || _ || _|| _|| _d S )N)base_estimatorordercvrandom_state)r(   rL   rM   rN   rO   r   r   r    r)     s    z_BaseChain.__init__c                s\  t ||ddd\}}t j}t|dd  j _ jdkrTtjt|j	d  _nNt
 jtr~ jdkr|j|j	d  _n$t jtt|j	d krtd fdd	t|j	d D  _ jdkr|dd jf }tj|rtj||fd
d}|j }ntj||f}nbtj|rPtj|j	d |j	d f}tj||fd
d}n(tj|j	d |j	d f}tj||f}~xt jD ]\}}|dd j| f }|j|ddd|j	d | f |  jdk	r|t jd k r|j	d | }	t j|ddd|	f | jd}
tj|rBtj|
d|dd|	f< n|
|dd|	f< qW  S )aK  Fit the model to data matrix X and targets Y.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            The input data.
        Y : array-like, shape (n_samples, n_classes)
            The target values.

        Returns
        -------
        self : object
        T)r*   r+   )r+   Nr   Zrandomzinvalid orderc                s   g | ]}t  jqS r   )r   rL   )r-   _)r(   r   r    rF     s   z"_BaseChain.fit.<locals>.<listcomp>Zlil)rI   r   )r   rN   )r   r   rO   r   rM   order_r7   Zarrayr3   r4   
isinstancestrZpermutationsortedlistr1   r,   rN   spissparsehstackZtocsrZ
lil_matrixzeros	enumerater   rH   r   rL   Zexpand_dims)r(   r   YrO   Y_pred_chainX_aug	chain_idxr   r   Zcol_idxZ	cv_resultr   )r(   r    r     sJ    




& z_BaseChain.fitc       	      C   s   t | d t|dd}tj|jd t| jf}xvt| jD ]h\}}|ddd|f }tj	|r|dkrp|}qtj
||f}ntj
||f}|j||dd|f< q<W tj| j}tjt| j|| j< |dd|f }|S )aN  Predict on the data matrix X using the ClassifierChain model.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            The input data.

        Returns
        -------
        Y_pred : array-like, shape (n_samples, n_classes)
            The predicted values.

        r,   T)r+   r   N)r   r   r7   rY   r4   rH   r,   rZ   rV   rW   rX   r5   
empty_likerQ   arange)	r(   r   r\   r^   r   previous_predictionsr]   	inv_orderZY_predr   r   r    r5     s    

z_BaseChain.predict)NNN)r;   r<   r=   r)   r   r   r5   r   r   r   r    rK     s   
@rK   c                   sH   e Zd ZdZ fddZeddd Zeddd Zd	d
 Z  Z	S )r   aa
  A multi-label model that arranges binary classifiers into a chain.

    Each model makes a prediction in the order specified by the chain using
    all of the available features provided to the model plus the predictions
    of models that are earlier in the chain.

    Read more in the :ref:`User Guide <classifierchain>`.

    Parameters
    ----------
    base_estimator : estimator
        The base estimator from which the classifier chain is built.

    order : array-like, shape=[n_outputs] or 'random', optional
        By default the order will be determined by the order of columns in
        the label matrix Y.::

            order = [0, 1, 2, ..., Y.shape[1] - 1]

        The order of the chain can be explicitly set by providing a list of
        integers. For example, for a chain of length 5.::

            order = [1, 3, 2, 4, 0]

        means that the first model in the chain will make predictions for
        column 1 in the Y matrix, the second model will make predictions
        for column 3, etc.

        If order is 'random' a random ordering will be used.

    cv : int, cross-validation generator or an iterable, optional     (default=None)
        Determines whether to use cross validated predictions or true
        labels for the results of previous estimators in the chain.
        If cv is None the true labels are used when fitting. Otherwise
        possible inputs for cv are:

        - integer, to specify the number of folds in a (Stratified)KFold,
        - :term:`CV splitter`,
        - An iterable yielding (train, test) splits as arrays of indices.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

        The random number generator is used to generate random chain orders.

    Attributes
    ----------
    classes_ : list
        A list of arrays of length ``len(estimators_)`` containing the
        class labels for each estimator in the chain.

    estimators_ : list
        A list of clones of base_estimator.

    order_ : list
        The order of labels in the classifier chain.

    See also
    --------
    RegressorChain: Equivalent for regression
    MultioutputClassifier: Classifies each output independently rather than
        chaining.

    References
    ----------
    Jesse Read, Bernhard Pfahringer, Geoff Holmes, Eibe Frank, "Classifier
    Chains for Multi-label Classification", 2009.

    c                s(   t  j|| dd t| jD | _| S )aK  Fit the model to data matrix X and targets Y.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            The input data.
        Y : array-like, shape (n_samples, n_classes)
            The target values.

        Returns
        -------
        self : object
        c             S   s   g | ]\}}|j qS r   )classes_)r-   r^   r   r   r   r    rF   I  s   z'ClassifierChain.fit.<locals>.<listcomp>)r?   r   rZ   r,   rc   )r(   r   r[   )r@   r   r    r   :  s    zClassifierChain.fitrL   c       
      C   s  t |dd}tj|jd t| jf}tj|jd t| jf}xt| jD ]|\}}|ddd|f }tj|rtj	||f}ntj	||f}|j
|dddf |dd|f< |j||dd|f< qLW tj| j}tjt| j|| j< |dd|f }	|	S )zPredict probability estimates.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)

        Returns
        -------
        Y_prob : array-like, shape (n_samples, n_classes)
        T)r+   r   Nr   )r   r7   rY   r4   rH   r,   rZ   rV   rW   rX   rE   r5   r_   rQ   r`   )
r(   r   ZY_prob_chainr\   r^   r   ra   r]   rb   ZY_probr   r   r    rE   N  s    
"zClassifierChain.predict_probac       
      C   s   t j|jd t| jf}t j|jd t| jf}x~t| jD ]p\}}|ddd|f }tj|rvtj||f}nt j||f}|j	||dd|f< |j
||dd|f< q@W t j| j}t jt| j|| j< |dd|f }	|	S )aa  Evaluate the decision_function of the models in the chain.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)

        Returns
        -------
        Y_decision : array-like, shape (n_samples, n_classes )
            Returns the decision function of the sample for each model
            in the chain.
        r   N)r7   rY   r4   rH   r,   rZ   rV   rW   rX   decision_functionr5   r_   rQ   r`   )
r(   r   ZY_decision_chainr\   r^   r   ra   r]   rb   Z
Y_decisionr   r   r    rd   k  s    
z!ClassifierChain.decision_functionc             C   s
   dddS )NT)rJ   r9   r   )r(   r   r   r    r:     s    zClassifierChain._more_tags)
r;   r<   r=   rC   r   r   rE   rd   r:   rD   r   r   )r@   r    r     s
   Ic                   s(   e Zd ZdZ fddZdd Z  ZS )r   a+	  A multi-label model that arranges regressions into a chain.

    Each model makes a prediction in the order specified by the chain using
    all of the available features provided to the model plus the predictions
    of models that are earlier in the chain.

    Read more in the :ref:`User Guide <regressorchain>`.

    Parameters
    ----------
    base_estimator : estimator
        The base estimator from which the classifier chain is built.

    order : array-like, shape=[n_outputs] or 'random', optional
        By default the order will be determined by the order of columns in
        the label matrix Y.::

            order = [0, 1, 2, ..., Y.shape[1] - 1]

        The order of the chain can be explicitly set by providing a list of
        integers. For example, for a chain of length 5.::

            order = [1, 3, 2, 4, 0]

        means that the first model in the chain will make predictions for
        column 1 in the Y matrix, the second model will make predictions
        for column 3, etc.

        If order is 'random' a random ordering will be used.

    cv : int, cross-validation generator or an iterable, optional     (default=None)
        Determines whether to use cross validated predictions or true
        labels for the results of previous estimators in the chain.
        If cv is None the true labels are used when fitting. Otherwise
        possible inputs for cv are:

        - integer, to specify the number of folds in a (Stratified)KFold,
        - :term:`CV splitter`,
        - An iterable yielding (train, test) splits as arrays of indices.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

        The random number generator is used to generate random chain orders.

    Attributes
    ----------
    estimators_ : list
        A list of clones of base_estimator.

    order_ : list
        The order of labels in the classifier chain.

    See also
    --------
    ClassifierChain: Equivalent for classification
    MultioutputRegressor: Learns each output independently rather than
        chaining.

    c                s   t  j|| | S )aK  Fit the model to data matrix X and targets Y.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            The input data.
        Y : array-like, shape (n_samples, n_classes)
            The target values.

        Returns
        -------
        self : object
        )r?   r   )r(   r   r[   )r@   r   r    r     s    zRegressorChain.fitc             C   s   ddiS )Nr9   Tr   )r(   r   r   r    r:     s    zRegressorChain._more_tags)r;   r<   r=   rC   r   r:   rD   r   r   )r@   r    r     s   @)N)NNT)+rC   Znumpyr7   Zscipy.sparseZsparserV   abcr   r   baser   r   r   r   r	   r
   Zmodel_selectionr   Zutilsr   r   r   Zutils.fixesr   Zutils.metaestimatorsr   Zutils.validationr   r   Zutils.multiclassr   Zutils._joblibr   r   __all__r!   r%   r&   r   r   rK   r   r   r   r   r   r    <module>   s4   


	 
 _Zj !