B
    0d                 @   s  d Z ddlZddlZddlZddlmZ ddlZddl	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 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 m!Z!m"Z" ddl#m$Z$m%Z% ddl&m'Z' ddl(m)Z) dddgZ*d)ddZ+dd Z,dd Z-dd Z.G dd de
Z/d d! Z0G d"d deeee
Z1d#d$ Z2d%d& Z3G d'd deee
Z4G d(d deee
Z5dS )*a  
Multiclass classification strategies
====================================

This module implements multiclass learning algorithms:
    - one-vs-the-rest / one-vs-all
    - one-vs-one
    - error correcting output codes

The estimators provided in this module are meta-estimators: they require a base
estimator to be provided in their constructor. For example, it is possible to
use these estimators to turn a binary classifier or a regressor into a
multiclass classifier. It is also possible to use these estimators with
multiclass estimators in the hope that their accuracy or runtime performance
improves.

All classifiers in scikit-learn implement multiclass classification; you
only need to use this module if you want to experiment with custom multiclass
strategies.

The one-vs-the-rest meta-classifier also implements a `predict_proba` method,
so long as such a method is implemented by the base classifier. This method
returns probabilities of class membership in both the single label and
multilabel case.  Note that in the multilabel case, probabilities are the
marginal probability that a given sample falls in the given class. As such, in
the multilabel case the sum of these probabilities over all possible labels
for a given sample *will not* sum to unity, as they do in the single label
case.
    N   )BaseEstimatorClassifierMixincloneis_classifier)MultiOutputMixin)MetaEstimatorMixinis_regressor)_is_pairwise)LabelBinarizer)euclidean_distances)check_random_state)
deprecated)
_safe_tags)_num_samples)check_is_fitted)_check_partial_fit_first_callcheck_classification_targets_ovr_decision_function)_safe_splitavailable_if)delayed)ParallelOneVsRestClassifierOneVsOneClassifierOutputCodeClassifierc             C   sv   t |}t|dkr^|dk	rN|d dkr0d}n|d }tdt||   t ||} nt| } | || | S )zFit a single binary estimator.r   Nr   z-Label %s is present in all training examples.)	npuniquelenwarningswarnstr_ConstantPredictorfitr   )	estimatorXyclassesZunique_yc r*   D/var/www/html/venv/lib/python3.7/site-packages/sklearn/multiclass.py_fit_binaryF   s    
r,   c             C   s   |  ||td | S )z(Partially fit a single binary estimator.)r   r   )partial_fitr   array)r%   r&   r'   r*   r*   r+   _partial_fit_binaryY   s    r/   c          	   C   sZ   t | r| |S yt| |}W n. ttfk
rT   | |dddf }Y nX |S )z1Make predictions using a single binary estimator.Nr   )r	   predictr   raveldecision_functionAttributeErrorNotImplementedErrorpredict_proba)r%   r&   Zscorer*   r*   r+   _predict_binary_   s    
r6   c             C   s    t | dst | dstddS )z=Make sure that an estimator implements the necessary methods.r2   r5   zGThe base estimator should implement decision_function or predict_proba!N)hasattr
ValueError)r%   r*   r*   r+   _check_estimatork   s    r9   c               @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
r#   c             C   s0   t dd ddd}| j||d||fd || _| S )NFT)force_all_finitedtype	ensure_2daccept_sparse)resetZvalidate_separately)dict_validate_datay_)selfr&   r'   Zcheck_paramsr*   r*   r+   r$   v   s    z_ConstantPredictor.fitc             C   s0   t |  | j|dd dddd t| jt|S )NFT)r:   r;   r=   r<   r>   )r   r@   r   repeatrA   r   )rB   r&   r*   r*   r+   r0      s    z_ConstantPredictor.predictc             C   s0   t |  | j|dd dddd t| jt|S )NFT)r:   r;   r=   r<   r>   )r   r@   r   rC   rA   r   )rB   r&   r*   r*   r+   r2      s    z$_ConstantPredictor.decision_functionc             C   sF   t |  | j|dd dddd tjtd| j | jggt|ddS )NFT)r:   r;   r=   r<   r>   r   r   )axis)r   r@   r   rC   ZhstackrA   r   )rB   r&   r*   r*   r+   r5      s    z _ConstantPredictor.predict_probaN)__name__
__module____qualname__r$   r0   r2   r5   r*   r*   r*   r+   r#   u   s   
r#   c                s    fddS )zCheck if self.estimator or self.estimators_[0] has attr.

    If `self.estimators_[0]` has the attr, then its safe to assume that other
    values has it too. This function is used together with `avaliable_if`.
    c                s&   t | j p$t | do$t | jd  S )Nestimators_r   )r7   r%   rH   )rB   )attrr*   r+   <lambda>   s    z!_estimators_has.<locals>.<lambda>r*   )rI   r*   )rI   r+   _estimators_has   s    rK   c               @   s   e Zd ZdZddddZdd Zeedd"d	d
Zdd Z	eeddd Z
eeddd Zedd Zedd Zededd Zededd Zededd Zd d! ZdS )#r   a  One-vs-the-rest (OvR) multiclass strategy.

    Also known as one-vs-all, this strategy consists in fitting one classifier
    per class. For each classifier, the class is fitted against all the other
    classes. In addition to its computational efficiency (only `n_classes`
    classifiers are needed), one advantage of this approach is its
    interpretability. Since each class is represented by one and one classifier
    only, it is possible to gain knowledge about the class by inspecting its
    corresponding classifier. This is the most commonly used strategy for
    multiclass classification and is a fair default choice.

    OneVsRestClassifier can also be used for multilabel classification. To use
    this feature, provide an indicator matrix for the target `y` when calling
    `.fit`. In other words, the target labels should be formatted as a 2D
    binary (0/1) matrix, where [i, j] == 1 indicates the presence of label j
    in sample i. This estimator uses the binary relevance method to perform
    multilabel classification, which involves training one binary classifier
    independently for each label.

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

    Parameters
    ----------
    estimator : estimator object
        An estimator object implementing :term:`fit` and one of
        :term:`decision_function` or :term:`predict_proba`.

    n_jobs : int, default=None
        The number of jobs to use for the computation: the `n_classes`
        one-vs-rest problems are computed 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.

        .. versionchanged:: v0.20
           `n_jobs` default changed from 1 to None

    Attributes
    ----------
    estimators_ : list of `n_classes` estimators
        Estimators used for predictions.

    coef_ : ndarray of shape (1, n_features) or (n_classes, n_features)
        Coefficient of the features in the decision function. This attribute
        exists only if the ``estimators_`` defines ``coef_``.

        .. deprecated:: 0.24
            This attribute is deprecated in 0.24 and will
            be removed in 1.1 (renaming of 0.26). If you use this attribute
            in :class:`~sklearn.feature_selection.RFE` or
            :class:`~sklearn.feature_selection.SelectFromModel`,
            you may pass a callable to the `importance_getter`
            parameter that extracts feature the importances
            from `estimators_`.

    intercept_ : ndarray of shape (1, 1) or (n_classes, 1)
        If ``y`` is binary, the shape is ``(1, 1)`` else ``(n_classes, 1)``
        This attribute exists only if the ``estimators_`` defines
        ``intercept_``.

        .. deprecated:: 0.24
            This attribute is deprecated in 0.24 and will
            be removed in 1.1 (renaming of 0.26). If you use this attribute
            in :class:`~sklearn.feature_selection.RFE` or
            :class:`~sklearn.feature_selection.SelectFromModel`,
            you may pass a callable to the `importance_getter`
            parameter that extracts feature the importances
            from `estimators_`.

    classes_ : array, shape = [`n_classes`]
        Class labels.

    n_classes_ : int
        Number of classes.

    label_binarizer_ : LabelBinarizer object
        Object used to transform multiclass labels to binary labels and
        vice-versa.

    multilabel_ : boolean
        Whether a OneVsRestClassifier is a multilabel classifier.

    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 estimator exposes such an attribute when fit.

        .. versionadded:: 1.0

    See Also
    --------
    MultiOutputClassifier : Alternate way of extending an estimator for
        multilabel classification.
    sklearn.preprocessing.MultiLabelBinarizer : Transform iterable of iterables
        to binary indicator matrix.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.multiclass import OneVsRestClassifier
    >>> from sklearn.svm import SVC
    >>> X = np.array([
    ...     [10, 10],
    ...     [8, 10],
    ...     [-5, 5.5],
    ...     [-5.4, 5.5],
    ...     [-20, -20],
    ...     [-15, -20]
    ... ])
    >>> y = np.array([0, 0, 1, 1, 2, 2])
    >>> clf = OneVsRestClassifier(SVC()).fit(X, y)
    >>> clf.predict([[-19, -20], [9, 9], [-5, 5]])
    array([2, 0, 1])
    N)n_jobsc            C   s   || _ || _d S )N)r%   rL   )rB   r%   rL   r*   r*   r+   __init__0  s    zOneVsRestClassifier.__init__c                s   t dd_j|}| }jj_dd |jD }tjd fddt|D _	t
j	d dr~j	d j_t
j	d d	rj	d j_S )
a  Fit underlying estimators.

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

        y : (sparse) array-like of shape (n_samples,) or (n_samples, n_classes)
            Multi-class targets. An indicator matrix turns on multilabel
            classification.

        Returns
        -------
        self : object
            Instance of fitted estimator.
        T)sparse_outputc             s   s   | ]}|   V  qd S )N)toarrayr1   ).0colr*   r*   r+   	<genexpr>M  s    z*OneVsRestClassifier.fit.<locals>.<genexpr>)rL   c             3   s@   | ]8\}}t tj |d jj|  jj| gdV  qdS )znot %s)r(   N)r   r,   r%   label_binarizer_classes_)rP   icolumn)r&   rB   r*   r+   rR   R  s   	r   n_features_in_feature_names_in_)r   rS   Zfit_transformtocscrT   Tr   rL   	enumeraterH   r7   rW   rX   )rB   r&   r'   Ycolumnsr*   )r&   rB   r+   r$   4  s    

	zOneVsRestClassifier.fitr-   c                s   t |rZtjds&tdjfddtjD _tdd_	j	
j tt|jrtdt|jj	|}| }dd	 |jD }tjd
 fdd	tj|D _tjd drjd j_S )a  Partially fit underlying estimators.

        Should be used when memory is inefficient to train all data.
        Chunks of data can be passed in several iteration.

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

        y : (sparse) array-like of shape (n_samples,) or (n_samples, n_classes)
            Multi-class targets. An indicator matrix turns on multilabel
            classification.

        classes : array, shape (n_classes, )
            Classes across all calls to partial_fit.
            Can be obtained via `np.unique(y_all)`, where y_all is the
            target vector of the entire dataset.
            This argument is only required in the first call of partial_fit
            and can be omitted in the subsequent calls.

        Returns
        -------
        self : object
            Instance of partially fitted estimator.
        r-   z3Base estimator {0}, doesn't have partial_fit methodc                s   g | ]}t  jqS r*   )r   r%   )rP   _)rB   r*   r+   
<listcomp>  s    z3OneVsRestClassifier.partial_fit.<locals>.<listcomp>T)rN   z;Mini-batch contains {0} while classes must be subset of {1}c             s   s   | ]}|   V  qd S )N)rO   r1   )rP   rQ   r*   r*   r+   rR     s    z2OneVsRestClassifier.partial_fit.<locals>.<genexpr>)rL   c             3   s"   | ]\}}t t| |V  qd S )N)r   r/   )rP   r%   rV   )r&   r*   r+   rR     s   r   rW   )r   r7   r%   r8   formatrange
n_classes_rH   r   rS   r$   rT   r   r   	setdiff1dr   Z	transformrY   rZ   r   rL   ziprW   )rB   r&   r'   r(   r\   r]   r*   )r&   rB   r+   r-   e  s*    



zOneVsRestClassifier.partial_fitc             C   sJ  t |  t|}| jjdkrtj|td}|tj  tj	|t
d}x<t| jD ].\}}t||}tj|||d ||||k< qRW | j| S t| jd drt| jd rd}nd}td}	tddg}
x:| jD ]0}|	tt|||kd  |
t|	 qW tjt|	t
d}tj||	|
f|t| jfd}| j|S d	S )
aW  Predict multi-class targets using underlying estimators.

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

        Returns
        -------
        y : (sparse) array-like of shape (n_samples,) or (n_samples, n_classes)
            Predicted multi-class targets.
        Z
multiclass)r;   )outr   r2   g      ?rU   )shapeN)r   r   rS   y_type_r   emptyfloatfillinfZzerosintr[   rH   r6   maximumrT   r7   r   r.   extendwhereappendr   ZonesspZ
csc_matrixZinverse_transform)rB   r&   Z	n_samplesmaximaZ	argmaximarU   epredZthreshindicesZindptrdataZ	indicatorr*   r*   r+   r0     s0    


zOneVsRestClassifier.predictr5   c                sr   t |  t fdd| jD j}t| jdkrHtjd| |fdd}| jsn|tj|ddddtj	f  }|S )at  Probability estimates.

        The returned estimates for all classes are ordered by label of classes.

        Note that in the multilabel case, each sample can have any number of
        labels. This returns the marginal probability that the given sample has
        the label in question. For example, it is entirely consistent that two
        labels both have a 90% probability of applying to a given sample.

        In the single label multiclass case, the rows of the returned matrix
        sum to 1.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Input data.

        Returns
        -------
        T : (sparse) array-like of shape (n_samples, n_classes)
            Returns the probability of the sample for each class in the model,
            where classes are ordered as they are in `self.classes_`.
        c                s"   g | ]}|  d d df qS )Nr   )r5   )rP   rs   )r&   r*   r+   r_     s    z5OneVsRestClassifier.predict_proba.<locals>.<listcomp>r   )rD   N)
r   r   r.   rH   rZ   r   Zconcatenatemultilabel_sumZnewaxis)rB   r&   r\   r*   )r&   r+   r5     s     z!OneVsRestClassifier.predict_probar2   c                sB   t |  t| jdkr&| jd  S t fdd| jD jS )a  Decision function for the OneVsRestClassifier.

        Return the distance of each sample from the decision boundary for each
        class. This can only be used with estimators which implement the
        `decision_function` method.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Input data.

        Returns
        -------
        T : array-like of shape (n_samples, n_classes) or (n_samples,) for             binary classification.
            Result of calling `decision_function` on the final estimator.

            .. versionchanged:: 0.19
                output shape changed to ``(n_samples,)`` to conform to
                scikit-learn conventions for binary classification.
        r   r   c                s   g | ]}|   qS r*   )r2   r1   )rP   est)r&   r*   r+   r_     s    z9OneVsRestClassifier.decision_function.<locals>.<listcomp>)r   r   rH   r2   r   r.   rZ   )rB   r&   r*   )r&   r+   r2     s
    z%OneVsRestClassifier.decision_functionc             C   s   | j jdS )z(Whether this is a multilabel classifier.Z
multilabel)rS   rg   
startswith)rB   r*   r*   r+   rw     s    zOneVsRestClassifier.multilabel_c             C   s
   t | jS )zNumber of classes.)r   rT   )rB   r*   r*   r+   rb     s    zOneVsRestClassifier.n_classes_zAttribute `coef_` was deprecated in version 0.24 and will be removed in 1.1 (renaming of 0.26). If you observe this warning while using RFE or SelectFromModel, use the importance_getter parameter instead.c             C   sR   t |  t| jd ds tddd | jD }t|d rHt|S t|S )Nr   coef_z.Base estimator doesn't have a coef_ attribute.c             S   s   g | ]
}|j qS r*   )r{   )rP   rs   r*   r*   r+   r_   /  s    z-OneVsRestClassifier.coef_.<locals>.<listcomp>)r   r7   rH   r3   rq   issparsevstackr   )rB   Zcoefsr*   r*   r+   r{   #  s    	
zOneVsRestClassifier.coef_zAttribute `intercept_` was deprecated in version 0.24 and will be removed in 1.1 (renaming of 0.26). If you observe this warning while using RFE or SelectFromModel, use the importance_getter parameter instead.c             C   s6   t |  t| jd ds tdtdd | jD S )Nr   
intercept_z4Base estimator doesn't have an intercept_ attribute.c             S   s   g | ]}|j  qS r*   )r~   r1   )rP   rs   r*   r*   r+   r_   B  s    z2OneVsRestClassifier.intercept_.<locals>.<listcomp>)r   r7   rH   r3   r   r.   )rB   r*   r*   r+   r~   6  s    	zOneVsRestClassifier.intercept_zcAttribute `_pairwise` was deprecated in version 0.24 and will be removed in 1.1 (renaming of 0.26).c             C   s   t | jddS )z@Indicate if wrapped estimator is using a precomputed Gram matrix	_pairwiseF)getattrr%   )rB   r*   r*   r+   r   F  s    zOneVsRestClassifier._pairwisec             C   s   dt | jddiS )z@Indicate if wrapped estimator is using a precomputed Gram matrixpairwise)key)r   r%   )rB   r*   r*   r+   
_more_tagsO  s    zOneVsRestClassifier._more_tags)N)rE   rF   rG   __doc__rM   r$   r   rK   r-   r0   r5   r2   propertyrw   rb   r   r{   r~   r   r   r*   r*   r*   r+   r      s(   z1
@+(	c             C   s|   t ||k||k}|| }t |jt}d|||k< d|||k< t t|| }t| t| |d|dd |||gd|fS )z+Fit a single binary estimator (one-vs-one).r   r   N)ru   )r(   )	r   
logical_orrh   rf   rl   Zaranger   r,   r   )r%   r&   r'   rU   jcondy_binaryZindcondr*   r*   r+   _fit_ovo_binaryT  s    
r   c             C   sR   t ||k||k}|| }t|dkrNt |}d|||k< t| || |S | S )z4Partially fit a single binary estimator(one-vs-one).r   r   )r   r   r   Z
zeros_liker/   )r%   r&   r'   rU   r   r   r   r*   r*   r+   _partial_fit_ovo_binaryg  s    
r   c               @   st   e Zd ZdZddddZdd Zeeddd	d
Zdd Z	dd Z
edd Zededd Zdd ZdS )r   a|  One-vs-one multiclass strategy.

    This strategy consists in fitting one classifier per class pair.
    At prediction time, the class which received the most votes is selected.
    Since it requires to fit `n_classes * (n_classes - 1) / 2` classifiers,
    this method is usually slower than one-vs-the-rest, due to its
    O(n_classes^2) complexity. However, this method may be advantageous for
    algorithms such as kernel algorithms which don't scale well with
    `n_samples`. This is because each individual learning problem only involves
    a small subset of the data whereas, with one-vs-the-rest, the complete
    dataset is used `n_classes` times.

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

    Parameters
    ----------
    estimator : estimator object
        An estimator object implementing :term:`fit` and one of
        :term:`decision_function` or :term:`predict_proba`.

    n_jobs : int, default=None
        The number of jobs to use for the computation: the `n_classes * (
        n_classes - 1) / 2` OVO problems are computed 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_classes * (n_classes - 1) / 2`` estimators
        Estimators used for predictions.

    classes_ : numpy array of shape [n_classes]
        Array containing labels.

    n_classes_ : int
        Number of classes.

    pairwise_indices_ : list, length = ``len(estimators_)``, or ``None``
        Indices of samples used when training the estimators.
        ``None`` when ``estimator``'s `pairwise` tag is False.

        .. deprecated:: 0.24

            The _pairwise attribute is deprecated in 0.24. From 1.1
            (renaming of 0.25) and onward, `pairwise_indices_` will use the
            pairwise estimator tag instead.

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

        .. versionadded:: 1.0

    See Also
    --------
    OneVsRestClassifier : One-vs-all multiclass strategy.

    Examples
    --------
    >>> from sklearn.datasets import load_iris
    >>> from sklearn.model_selection import train_test_split
    >>> from sklearn.multiclass import OneVsOneClassifier
    >>> from sklearn.svm import LinearSVC
    >>> X, y = load_iris(return_X_y=True)
    >>> X_train, X_test, y_train, y_test = train_test_split(
    ...     X, y, test_size=0.33, shuffle=True, random_state=0)
    >>> clf = OneVsOneClassifier(
    ...     LinearSVC(random_state=0)).fit(X_train, y_train)
    >>> clf.predict(X_test[:10])
    array([2, 1, 0, 2, 0, 2, 0, 1, 1, 1])
    N)rL   c            C   s   || _ || _d S )N)r%   rL   )rB   r%   rL   r*   r*   r+   rM     s    zOneVsOneClassifier.__init__c                s   j  ddgdd\ t t_tjdkrDtdjjd tt	t
jd fd	d
tD  }|d _t}|r|d nd_S )aP  Fit underlying estimators.

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

        y : array-like of shape (n_samples,)
            Multi-class targets.

        Returns
        -------
        self : object
            The fitted underlying estimator.
        csrcscF)r=   r:   r   zAOneVsOneClassifier can not be fit when only one class is present.r   )rL   c          	   3   sD   | ]<}t |d  D ](}ttj j| j| V  qqdS )r   N)ra   r   r   r%   rT   )rP   rU   r   )r&   	n_classesrB   r'   r*   r+   rR     s   z)OneVsOneClassifier.fit.<locals>.<genexpr>N)r@   r   r   r   rT   r   r8   rf   listrd   r   rL   ra   rH   r
   pairwise_indices_)rB   r&   r'   Zestimators_indicesr   r*   )r&   r   rB   r'   r+   r$     s"    

zOneVsOneClassifier.fitr-   c                s   t |}|r6fddtjjd  d D _ttjr`td	t
jj ddgd|d	\ t ttjd}tjd
 fddtj|D _d_tjd drjd j_S )a  Partially fit underlying estimators.

        Should be used when memory is inefficient to train all data. Chunks
        of data can be passed in several iteration, where the first call
        should have an array of all target variables.

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

        y : array-like of shape (n_samples,)
            Multi-class targets.

        classes : array, shape (n_classes, )
            Classes across all calls to partial_fit.
            Can be obtained via `np.unique(y_all)`, where y_all is the
            target vector of the entire dataset.
            This argument is only required in the first call of partial_fit
            and can be omitted in the subsequent calls.

        Returns
        -------
        self : object
            The partially fitted underlying estimator.
        c                s   g | ]}t  jqS r*   )r   r%   )rP   r^   )rB   r*   r+   r_     s   z2OneVsOneClassifier.partial_fit.<locals>.<listcomp>r      z6Mini-batch contains {0} while it must be subset of {1}r   r   F)r=   r:   r>   )rL   c             3   s6   | ].\}\}}t t| j| j| V  qd S )N)r   r   rT   )rP   r%   rU   r   )r&   rB   r'   r*   r+   rR   ,  s   z1OneVsOneClassifier.partial_fit.<locals>.<genexpr>Nr   rW   )r   ra   rb   rH   r   r   rc   rT   r8   r`   r   r@   r   	itertoolscombinationsr   rL   rd   r   r7   rW   )rB   r&   r'   r(   Z
first_callr   r*   )r&   rB   r'   r+   r-     s.    


zOneVsOneClassifier.partial_fitc             C   s:   |  |}| jdkr(| j|dkt S | j|jdd S )a  Estimate the best class label for each sample in X.

        This is implemented as ``argmax(decision_function(X), axis=1)`` which
        will return the label of the class with most votes by estimators
        predicting the outcome of a decision for each possible class pair.

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

        Returns
        -------
        y : numpy array of shape [n_samples]
            Predicted multi-class targets.
        r   r   r   )rD   )r2   rb   rT   Zastyperl   Zargmax)rB   r&   r\   r*   r*   r+   r0   9  s    

zOneVsOneClassifier.predictc                s   t |  | j dddd | j}|dkr: gt| j }n fdd|D }tdd t| j|D j}tdd t| j|D j}t	||t| j
}| jd	kr|ddd
f S |S )a.  Decision function for the OneVsOneClassifier.

        The decision values for the samples are computed by adding the
        normalized sum of pair-wise classification confidence levels to the
        votes in order to disambiguate between the decision values when the
        votes for all the classes are equal leading to a tie.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Input data.

        Returns
        -------
        Y : array-like of shape (n_samples, n_classes) or (n_samples,)
            Result of calling `decision_function` on the final estimator.

            .. versionchanged:: 0.19
                output shape changed to ``(n_samples,)`` to conform to
                scikit-learn conventions for binary classification.
        TF)r=   r:   r>   Nc                s   g | ]} d d |f qS )Nr*   )rP   idx)r&   r*   r+   r_   q  s    z8OneVsOneClassifier.decision_function.<locals>.<listcomp>c             S   s   g | ]\}}| |qS r*   )r0   )rP   ry   Xir*   r*   r+   r_   t  s    c             S   s   g | ]\}}t ||qS r*   )r6   )rP   ry   r   r*   r*   r+   r_   w  s    r   r   )r   r@   r   r   rH   r   r}   rd   rZ   r   rT   rb   )rB   r&   ru   ZXsZpredictionsZconfidencesr\   r*   )r&   r+   r2   O  s$    
z$OneVsOneClassifier.decision_functionc             C   s
   t | jS )zNumber of classes.)r   rT   )rB   r*   r*   r+   rb   ~  s    zOneVsOneClassifier.n_classes_zcAttribute `_pairwise` was deprecated in version 0.24 and will be removed in 1.1 (renaming of 0.26).c             C   s   t | jddS )z@Indicate if wrapped estimator is using a precomputed Gram matrixr   F)r   r%   )rB   r*   r*   r+   r     s    zOneVsOneClassifier._pairwisec             C   s   dt | jddiS )z@Indicate if wrapped estimator is using a precomputed Gram matrixr   )r   )r   r%   )rB   r*   r*   r+   r     s    zOneVsOneClassifier._more_tags)N)rE   rF   rG   r   rM   r$   r   rK   r-   r0   r2   r   rb   r   r   r   r*   r*   r*   r+   r   s  s   N1
@/c               @   s2   e Zd ZdZddddddZdd Zd	d
 ZdS )r   a  (Error-Correcting) Output-Code multiclass strategy.

    Output-code based strategies consist in representing each class with a
    binary code (an array of 0s and 1s). At fitting time, one binary
    classifier per bit in the code book is fitted.  At prediction time, the
    classifiers are used to project new points in the class space and the class
    closest to the points is chosen. The main advantage of these strategies is
    that the number of classifiers used can be controlled by the user, either
    for compressing the model (0 < code_size < 1) or for making the model more
    robust to errors (code_size > 1). See the documentation for more details.

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

    Parameters
    ----------
    estimator : estimator object
        An estimator object implementing :term:`fit` and one of
        :term:`decision_function` or :term:`predict_proba`.

    code_size : float, default=1.5
        Percentage of the number of classes to be used to create the code book.
        A number between 0 and 1 will require fewer classifiers than
        one-vs-the-rest. A number greater than 1 will require more classifiers
        than one-vs-the-rest.

    random_state : int, RandomState instance, default=None
        The generator used to initialize the codebook.
        Pass an int for reproducible output across multiple function calls.
        See :term:`Glossary <random_state>`.

    n_jobs : int, default=None
        The number of jobs to use for the computation: the multiclass problems
        are computed 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 `int(n_classes * code_size)` estimators
        Estimators used for predictions.

    classes_ : ndarray of shape (n_classes,)
        Array containing labels.

    code_book_ : ndarray of shape (n_classes, code_size)
        Binary array containing the code of each class.

    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 estimator exposes such an attribute when fit.

        .. versionadded:: 1.0

    See Also
    --------
    OneVsRestClassifier : One-vs-all multiclass strategy.
    OneVsOneClassifier : One-vs-one multiclass strategy.

    References
    ----------

    .. [1] "Solving multiclass learning problems via error-correcting output
       codes",
       Dietterich T., Bakiri G.,
       Journal of Artificial Intelligence Research 2,
       1995.

    .. [2] "The error coding method and PICTs",
       James G., Hastie T.,
       Journal of Computational and Graphical statistics 7,
       1998.

    .. [3] "The Elements of Statistical Learning",
       Hastie T., Tibshirani R., Friedman J., page 606 (second-edition)
       2008.

    Examples
    --------
    >>> from sklearn.multiclass import OutputCodeClassifier
    >>> from sklearn.ensemble import RandomForestClassifier
    >>> from sklearn.datasets import make_classification
    >>> X, y = make_classification(n_samples=100, n_features=4,
    ...                            n_informative=2, n_redundant=0,
    ...                            random_state=0, shuffle=False)
    >>> clf = OutputCodeClassifier(
    ...     estimator=RandomForestClassifier(random_state=0),
    ...     random_state=0).fit(X, y)
    >>> clf.predict([[0, 0, 0, 0]])
    array([1])
    g      ?N)	code_sizerandom_staterL   c            C   s   || _ || _|| _|| _d S )N)r%   r   r   rL   )rB   r%   r   r   rL   r*   r*   r+   rM     s    zOutputCodeClassifier.__init__c                sv  j ddjdkr(tdjtj tj}t t	
_jjd }|dkrltdt|j }|||f_djjdk< tjdrd	jjdk< ndjjdk< d
d tjD t	jfddttD tdtjd fddtjd D _tjd drRjd j_tjd drrjd j_S )aR  Fit underlying estimators.

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

        y : array-like of shape (n_samples,)
            Multi-class targets.

        Returns
        -------
        self : object
            Returns a fitted instance of self.
        Zno_validation)r&   r'   r   z+code_size should be greater than 0, got {0}z=OutputCodeClassifier can not be fit when no class is present.r   g      ?r2   r   c             S   s   i | ]\}}||qS r*   r*   )rP   rU   r)   r*   r*   r+   
<dictcomp>*  s    z,OutputCodeClassifier.fit.<locals>.<dictcomp>c                s   g | ]}j  |   qS r*   )
code_book_)rP   rU   )classes_indexrB   r'   r*   r+   r_   -  s    z,OutputCodeClassifier.fit.<locals>.<listcomp>)r;   )rL   c             3   s,   | ]$}t tj d d |f V  qd S )N)r   r,   r%   )rP   rU   )r&   r\   rB   r*   r+   rR   2  s    z+OutputCodeClassifier.fit.<locals>.<genexpr>rW   rX   )r@   r   r8   r`   r9   r%   r   r   r   r   r   rT   rf   rl   Zrandom_sampler   r7   r[   r.   ra   r   r   rL   rH   rW   rX   )rB   r&   r'   r   r   Z
code_size_r*   )r&   r\   r   rB   r'   r+   r$     s:    



$zOutputCodeClassifier.fitc                sB   t |  t fdd| jD j}t|| jjdd}| j| S )a1  Predict multi-class targets using underlying estimators.

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

        Returns
        -------
        y : ndarray of shape (n_samples,)
            Predicted multi-class targets.
        c                s   g | ]}t | qS r*   )r6   )rP   rs   )r&   r*   r+   r_   J  s    z0OutputCodeClassifier.predict.<locals>.<listcomp>r   )rD   )	r   r   r.   rH   rZ   r   r   ZargminrT   )rB   r&   r\   rt   r*   )r&   r+   r0   <  s    zOutputCodeClassifier.predict)rE   rF   rG   r   rM   r$   r0   r*   r*   r*   r+   r     s   b?)N)6r   r.   numpyr   r    Zscipy.sparsesparserq   r   baser   r   r   r   r   r   r	   r
   Zpreprocessingr   Zmetrics.pairwiser   utilsr   Zutils.deprecationr   Zutils._tagsr   Zutils.validationr   r   Zutils.multiclassr   r   r   Zutils.metaestimatorsr   r   Zutils.fixesr   Zjoblibr   __all__r,   r/   r6   r9   r#   rK   r   r   r   r   r   r*   r*   r*   r+   <module>   sP   

3
   "  "