
    0Phլ                        d Z ddlZddlZddlZddlmZ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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 ddl m!Z!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z' ddl(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3 g dZ4d dZ5d Z6d Z7d Z8 G d de          Z9d Z: G d deeee          Z;d Z<d Z= G d deee          Z> G d deee          Z?dS )!a  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)IntegralReal   )BaseEstimatorClassifierMixinMetaEstimatorMixinMultiOutputMixin_fit_contextcloneis_classifieris_regressor)pairwise_distances_argmin)LabelBinarizer)check_random_state)
HasMethodsInterval)get_tags)MetadataRouterMethodMapping_raise_for_paramsprocess_routing)_safe_splitavailable_if)_check_partial_fit_first_call_ovr_decision_functioncheck_classification_targets)Paralleldelayed)_check_method_params_num_samplescheck_is_fittedvalidate_data)OneVsRestClassifierOneVsOneClassifierOutputCodeClassifierc                 \   t          j        |          }t          |          dk    rf|A|d         dk    rd}n|d         }t          j        dt          ||                   z             t                                          ||          } nt          |           }  | j        ||fi | | 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
fit_paramsclassesunique_ycs          R/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/multiclass.py_fit_binaryr8   Q   s    y||H
8}}trzzaDM?#gaj//Q   '((,,Q99		)$$		a))j)))    c                 L     | j         ||fdt          j        d          i| | S )z(Partially fit a single binary estimator.r4   )r   r   )partial_fitr(   array)r0   r1   r2   partial_fit_paramss       r7   _partial_fit_binaryr>   d   s5    I!QOO(8(8O<NOOOr9   c                    t          |           r|                     |          S 	 t          j        |                     |                    }n6# t
          t          f$ r" |                     |          dddf         }Y nw xY w|S )z1Make predictions using a single binary estimator.Nr   )r   predictr(   raveldecision_functionAttributeErrorNotImplementedErrorpredict_proba)r0   r1   scores      r7   _predict_binaryrG   j   s    I $  ###144Q7788/0 1 1 1''**111a401 Ls   'A 0B Bc                 H    t          | d          rt          |           rdS dS )z0Threshold for predictions from binary estimator.rB                 ?)hasattrr   )r0   s    r7   _threshold_for_binary_predictrL   v   s0    y-.. =3K3K s sr9   c                   *    e Zd ZdZd Zd Zd Zd ZdS )r.   z;Helper predictor to be used when only one class is present.c                 f    t          dd dd          }t          | ||d||f           || _        | S )NFT)ensure_all_finitedtype	ensure_2daccept_sparse)resetvalidate_separately)dictr"   y_)selfr1   r2   check_paramss       r7   r/   z_ConstantPredictor.fit   sW    #45PT
 
 
 	!Qd|8T	
 	
 	
 	
 r9   c           	          t          |            t          | |dd ddd           t          j        | j        t          |                    S NFTrO   rP   rR   rQ   rS   r!   r"   r(   repeatrV   r    rW   r1   s     r7   r@   z_ConstantPredictor.predict   X    #	
 	
 	
 	
 y,q//222r9   c           	          t          |            t          | |dd ddd           t          j        | j        t          |                    S rZ   r\   r^   s     r7   rB   z$_ConstantPredictor.decision_function   r_   r9   c           	         t          |            t          | |dd ddd           | j                            t          j                  }t	          j        t	          j        d|z
  |g          gt          |          d          S )NFTr[   r   r   axis)	r!   r"   rV   astyper(   float64r]   hstackr    )rW   r1   rV   s      r7   rE   z _ConstantPredictor.predict_proba   s    #	
 	
 	
 	
 W^^BJ''y")QVRL112LOO!LLLLr9   N)__name__
__module____qualname____doc__r/   r@   rB   rE    r9   r7   r.   r.      s[        EE  3 3 33 3 3M M M M Mr9   r.   c                       fd}|S )a!  Check if self.estimator or self.estimators_[0] has attr.

    If `self.estimators_[0]` has the attr, then its safe to assume that other
    estimators have it too. We raise the original `AttributeError` if `attr`
    does not exist. This function is used together with `available_if`.
    c                     t          | d          rt          | j        d                    nt          | j                   dS )Nestimators_r   T)rK   getattrrn   r0   )rW   attrs    r7   checkz_estimators_has.<locals>.check   sG    4'' 	*D$Q'....DND)))tr9   rk   )rp   rq   s   ` r7   _estimators_hasrr      s#         Lr9   c                       e Zd ZdZ edg          gedgdgdZddddZ ed	
          d             Z	 e
 ed                     ed	
          dd                        Zd Z e
 ed                    d             Z e
 ed                    d             Zed             Zed             Z fdZd Z xZ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
        A regressor or a classifier that implements :term:`fit`.
        When a classifier is passed, :term:`decision_function` will be used
        in priority and it will fallback to :term:`predict_proba` if it is not
        available.
        When a regressor is passed, :term:`predict` is used.

    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:: 0.20
           `n_jobs` default changed from 1 to None

    verbose : int, default=0
        The verbosity level, if non zero, progress messages are printed.
        Below 50, the output is sent to stderr. Otherwise, the output is sent
        to stdout. The frequency of the messages increases with the verbosity
        level, reporting all iterations at 10. See :class:`joblib.Parallel` for
        more details.

        .. versionadded:: 1.1

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

    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
    --------
    OneVsOneClassifier : One-vs-one multiclass strategy.
    OutputCodeClassifier : (Error-Correcting) Output-Code multiclass strategy.
    sklearn.multioutput.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])
    r/   Nverboser0   n_jobsrt   r   rv   rt   c                0    || _         || _        || _        d S Nru   )rW   r0   rv   rt   s       r7   __init__zOneVsRestClassifier.__init__B  s    "r9   Fprefer_skip_nested_validationc                 d    t          | d           t           dfi |t          d           _         j                            |          }|                                } j        j         _        d |j        D             } t           j	         j
                   f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 : {array-like, sparse matrix} of shape (n_samples, n_features)
            Data.

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

        **fit_params : dict
            Parameters passed to the ``estimator.fit`` method of each
            sub-estimator.

            .. versionadded:: 1.4
                Only available if `enable_metadata_routing=True`. See
                :ref:`Metadata Routing User Guide <metadata_routing>` for more
                details.

        Returns
        -------
        self : object
            Instance of fitted estimator.
        r/   Tsparse_outputc              3   b   K   | ]*}|                                                                 V  +d S ry   toarrayrA   .0cols     r7   	<genexpr>z*OneVsRestClassifier.fit.<locals>.<genexpr>t  6      88S3;;==&&((888888r9   rw   c           
   3      K   | ]]\  }} t          t                    j        |j        j        d j        j        |         z  j        j        |         g          V  ^dS )znot %sr3   r4   N)r   r8   r0   r/   label_binarizer_classes_)r   icolumnr1   routed_paramsrW   s      r7   r   z*OneVsRestClassifier.fit.<locals>.<genexpr>x  s       N
 N
 6 !GK  (26t4=a@@)215	 	 	N
 N
 N
 N
 N
 N
r9   r   n_features_in_feature_names_in_)r   r   r   r   fit_transformtocscr   Tr   rv   rt   	enumeratern   rK   r   r   )rW   r1   r2   r3   Ycolumnsr   s   ``    @r7   r/   zOneVsRestClassifier.fitG  sg   < 	*dE222'
 
 
 
 !/T B B B!//22GGII-688AC888 N84;MMM N
 N
 N
 N
 N
 N
 'w//N
 N
 N
 
 
 4#A&(899 	E"&"21"5"DD4#A&(;<< 	K%)%5a%8%JD"r9   r;   c                 F    t          | d           t           dfi |t           |          rY fdt           j                  D              _        t          d           _         j                             j	                   t          t          j        | j	                            r:t          d                    t          j        |           j	                             j                            |          }|                                }d |j        D             } t'           j                  f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 iterations.

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

        y : {array-like, sparse matrix} 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.

        **partial_fit_params : dict
            Parameters passed to the ``estimator.partial_fit`` method of each
            sub-estimator.

            .. versionadded:: 1.4
                Only available if `enable_metadata_routing=True`. See
                :ref:`Metadata Routing User Guide <metadata_routing>` for more
                details.

        Returns
        -------
        self : object
            Instance of partially fitted estimator.
        r;   c                 8    g | ]}t          j                  S rk   r   r0   r   _rW   s     r7   
<listcomp>z3OneVsRestClassifier.partial_fit.<locals>.<listcomp>  s#    VVV!dn 5 5VVVr9   Tr~   z;Mini-batch contains {0} while classes must be subset of {1}c              3   b   K   | ]*}|                                                                 V  +d S ry   r   r   s     r7   r   z2OneVsRestClassifier.partial_fit.<locals>.<genexpr>  r   r9   rv   c              3   t   K   | ]2\  }} t          t                    ||j        j                   V  3dS r=   N)r   r>   r0   r;   )r   r0   r   r1   r   s      r7   r   z2OneVsRestClassifier.partial_fit.<locals>.<genexpr>  si       8
 8
 "	6 )G'((#0#:#F	  8
 8
 8
 8
 8
 8
r9   r   r   )r   r   r   range
n_classes_rn   r   r   r/   r   r*   r(   	setdiff1d
ValueErrorformatr)   	transformr   r   r   rv   ziprK   r   )rW   r1   r2   r4   r=   r   r   r   s   ``     @r7   r;   zOneVsRestClassifier.partial_fit  s   R 	,dMBBB'
 
 !
 
 )w77 	5VVVVuT_?U?UVVVD %3$F$F$FD!!%%dm444r|At}--.. 	V&1t}55   !++A..GGII88AC888784;777 8
 8
 8
 8
 8
 &))97%C%C8
 8
 8
 
 
 4#A&(899 	E"&"21"5"DDr9   c           	         t          |            t          |          }| j        j        dk    rt	          j        |t                    }|                    t          j                    t	          j	        |t                    }t          | j                  D ]5\  }}t          ||          }t	          j        |||           ||||k    <   6| j        |         S t!          | j        d                   }t#          j        d          }	t#          j        ddg          }
| j        D ]c}|	                    t	          j        t          ||          |k              d                    |
                    t+          |	                     dt	          j        t+          |	          t                    }t/          j        ||	|
f|t+          | j                  f          }| j                            |          S )ag  Predict multi-class targets using underlying estimators.

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

        Returns
        -------
        y : {array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_classes)
            Predicted multi-class targets.
        
multiclassrP   )outr   r   )shape)r!   r    r   y_type_r(   emptyfloatfillinfzerosintr   rn   rG   maximumr   rL   r<   extendwhereappendr*   onessp
csc_matrixinverse_transform)rW   r1   	n_samplesmaxima	argmaximar   epredthreshindicesindptrdata	indicators                r7   r@   zOneVsRestClassifier.predict  s    	 OO	 (L88Xiu555FKK   #666I!$"233 . .1&q!,,
64V4444,-	&D.))=++243CA3FGGFk#&&G[qc**F% , ,rx1(=(=(FGGJKKKc'll++++73w<<s333Dw'	3t?O;P;P/Q  I (::9EEEr9   rE   c                 H   t          |            t          j        fd| j        D                       j        }t          | j                  dk    rt          j        d|z
  |fd          }| j        s-|t          j        |d          ddt          j	        f         z  }|S )a|  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, sparse matrix} of shape (n_samples, n_features)
            Input data.

        Returns
        -------
        T : 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                 N    g | ]!}|                               d d df         "S )Nr   )rE   r   r   r1   s     r7   r   z5OneVsRestClassifier.predict_proba.<locals>.<listcomp>$  s2    III1aooa((A.IIIr9   r   rb   N)
r!   r(   r<   rn   r   r*   concatenatemultilabel_sumnewaxis)rW   r1   r   s    ` r7   rE   z!OneVsRestClassifier.predict_proba  s    2 	 HIIII8HIIIJJLt  A%% Q|!444A 	2"""111bj=11Ar9   rB   c                     t          |            t          | j                  dk    r | j        d                                       S t	          j        f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                 ^    g | ])}|                                                               *S rk   )rB   rA   )r   estr1   s     r7   r   z9OneVsRestClassifier.decision_function.<locals>.<listcomp>K  s3    JJJ#S""1%%++--JJJr9   )r!   r*   rn   rB   r(   r<   r   r^   s    `r7   rB   z%OneVsRestClassifier.decision_function0  sv    . 	t  A%%#A&88;;;xJJJJ9IJJJ
 

	r9   c                 @    | j         j                            d          S )z(Whether this is a multilabel classifier.
multilabel)r   r   
startswithrW   s    r7   r   zOneVsRestClassifier.multilabel_N  s     $,77EEEr9   c                 *    t          | j                  S zNumber of classes.r*   r   r   s    r7   r   zOneVsRestClassifier.n_classes_S       4=!!!r9   c                     t                                                      }t          | j                  j        j        |j        _        t          | j                  j        j        |j        _        |S z@Indicate if wrapped estimator is using a precomputed Gram matrixsuper__sklearn_tags__r   r0   
input_tagspairwisesparserW   tags	__class__s     r7   r   z$OneVsRestClassifier.__sklearn_tags__X  Q    ww''))#+DN#;#;#F#O !)$.!9!9!D!Kr9   c                     t          | j        j                                      |                               | j        t                                          dd                              dd                    }|S j  Get metadata routing of this object.

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

        .. versionadded:: 1.4

        Returns
        -------
        routing : MetadataRouter
            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
            routing information.
        ownerr/   callercalleer;   r0   method_mappingr   r   rg   add_self_requestaddr0   r   rW   routers     r7   get_metadata_routingz(OneVsRestClassifier.get_metadata_routing_  s      !8999d##S.,E%00M-@@	    	 r9   ry   )rg   rh   ri   rj   r   r   _parameter_constraintsrz   r
   r/   r   rr   r;   r@   rE   rB   propertyr   r   r   r   __classcell__r   s   @r7   r#   r#      s       j jZ !j%))*T";  -1!     
 \&+  @ @	 @D \//-0011\&+  N N N	  21
N`$F $F $FL \///2233% % 43%N \//"56677  87: F F XF " " X"          r9   r#   c           	      ~   t          j        ||k    ||k              }||         }t          j        |j        t                    }d|||k    <   d|||k    <   t          j        t          |                    |         }t          |||          }	t          | t          | |d|          d         ||	||g          |fS )z+Fit a single binary estimator (one-vs-one).r   r   paramsr   N)r   r   )
r(   
logical_orr   r   r   aranger    r   r8   r   )
r0   r1   r2   r   jr3   condy_binaryindcondfit_params_subsets
             r7   _fit_ovo_binaryr  {  s    =aa((D	$Ax%%HHQ!VHQ!ViQ((.G,Qz7SSS	1dG<<<Q?(F	
 	
 	
 		 	r9   c                    t          j        ||k    ||k              }||         }t          |          dk    rHt          j        |          }d|||k    <   t	          |||          }t          | ||         ||          S | S )z4Partially fit a single binary estimator(one-vs-one).r   r   r   r   )r(   r   r*   
zeros_liker   r>   )	r0   r1   r2   r   r   r=   r   r  partial_fit_params_subsets	            r7   _partial_fit_ovo_binaryr    s     =aa((D	$A
1vv{{=##a$8($%
 %
 %
! #qw=V
 
 
 	
 r9   c                       e Zd ZU dZ edg          gedgdZeed<   dddZ	 e
d	          d
             Z e ed                     e
d	          dd                        Zd Zd Zed             Z fdZd Z xZ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
        A regressor or a classifier that implements :term:`fit`.
        When a classifier is passed, :term:`decision_function` will be used
        in priority and it will fallback to :term:`predict_proba` if it is not
        available.
        When a regressor is passed, :term:`predict` is used.

    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.

    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.
    OutputCodeClassifier : (Error-Correcting) Output-Code 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])
    r/   Nr0   rv   r   r   c                "    || _         || _        d S ry   r
  )rW   r0   rv   s      r7   rz   zOneVsOneClassifier.__init__  s    "r9   Fr{   c                 X    t          | d           t           dfi |t           ddgd          \  t                     t	          j                   _        t           j                  dk    rt          d           j        j	        d         t          t           t           j        	           fd
t                    D                                  }|d          _                                         j        j        }|r|d         nd _         S )a  Fit underlying estimators.

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

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

        **fit_params : dict
            Parameters passed to the ``estimator.fit`` method of each
            sub-estimator.

            .. versionadded:: 1.4
                Only available if `enable_metadata_routing=True`. See
                :ref:`Metadata Routing User Guide <metadata_routing>` for more
                details.

        Returns
        -------
        self : object
            The fitted underlying estimator.
        r/   csrcscF)rR   rO   r   zAOneVsOneClassifier can not be fit when only one class is present.r   r   c           
   3      K   | ]b}t          |d z             D ]L} t          t                    j        j        |         j        |         j        j                  V  McdS )r   r3   N)r   r   r  r0   r   r/   )r   r   r   r1   	n_classesr   rW   r2   s      r7   r   z)OneVsOneClassifier.fit.<locals>.<genexpr>-  s       1 1 !&q1ui!8!81 1  100 N M!, M!,'4'>'B  1 1 1 1 1 1 1r9   N)r   r   r"   r   r(   r)   r   r*   r   r   listr   r   rv   r   rn   r   r   r   pairwise_indices_)rW   r1   r2   r3   estimators_indicesr   r  r   s   ```   @@r7   r/   zOneVsOneClassifier.fit  s}   : 	*dE222'
 
 
 
 !Quen
 
 
1 	%Q'''	!t}""S   M'*	!0HDK000 1 1 1 1 1 1 1 1 "'y!1!11 1 1  
 
& .a0((**5>:B!L!3A!6!6r9   r;   c                 4    t          | d           t           dfi |t           |          }|r3 fdt           j         j        dz
  z  dz            D              _        t          t          j         j	                            r:t          d                    t          j                   j	                            t           ddgd|	          \  t                     t          j        t           j                  d          } t#           j        
           f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 : {array-like, sparse matrix) 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.

        **partial_fit_params : dict
            Parameters passed to the ``estimator.partial_fit`` method of each
            sub-estimator.

            .. versionadded:: 1.4
                Only available if `enable_metadata_routing=True`. See
                :ref:`Metadata Routing User Guide <metadata_routing>` for more
                details.

        Returns
        -------
        self : object
            The partially fitted underlying estimator.
        r;   c                 8    g | ]}t          j                  S rk   r   r   s     r7   r   z2OneVsOneClassifier.partial_fit.<locals>.<listcomp>w  s3           dn%%     r9   r      z6Mini-batch contains {0} while it must be subset of {1}r  r  FrR   rO   rS   r   c           	   3      K   | ]M\  }\  }} t          t                    |j        |         j        |         j        j                   V  NdS r   )r   r  r   r0   r;   )r   r0   r   r   r1   r   rW   r2   s       r7   r   z1OneVsOneClassifier.partial_fit.<locals>.<genexpr>  s       
8
 
8
 "	6Aq -G+,,a a #0#:#F  
8
 
8
 
8
 
8
 
8
 
8
r9   Nr   r   )r   r   r   r   r   rn   r*   r(   r   r   r   r   r)   r"   r   	itertoolscombinationsr   rv   r   r  rK   r   )rW   r1   r2   r4   r=   
first_callr  r   s   ```    @r7   r;   zOneVsOneClassifier.partial_fitD  s   R 	,dMBBB'
 
 !
 
 34AA
 	       t$/A2EF!KLL     D
 r|At}--.. 	HOOIaLL$-     %.#
 
 
1 	%Q''' -eDO.D.DaHH784;777 
8
 
8
 
8
 
8
 
8
 
8
 
8
 &))9L%J%J
8
 
8
 
8
 

 

 "&4#A&(899 	E"&"21"5"DDr9   c                 
   |                      |          }| j        dk    rCt          | j        d                   }| j        ||k                        t                             S | j        |                    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 : {array-like, sparse matrix} of shape (n_samples, n_features)
            Data.

        Returns
        -------
        y : numpy array of shape [n_samples]
            Predicted multi-class targets.
        r  r   r   rb   )rB   r   rL   rn   r   rd   r   argmax)rW   r1   r   r   s       r7   r@   zOneVsOneClassifier.predict  ss    " ""1%%?a243CA3FGGF=!f*!4!4S!9!9::}QXX1X--..r9   c                    t          |            t          | ddd          | j        }|gt          | j                  z  }nfd|D             }t          j        d t          | j        |          D                       j        }t          j        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.
        TFr  Nc                 (    g | ]}d d |f         S ry   rk   )r   idxr1   s     r7   r   z8OneVsOneClassifier.decision_function.<locals>.<listcomp>  s%    ///!AAAsF)///r9   c                 >    g | ]\  }}|                     |          S rk   )r@   r   r   Xis      r7   r   z8OneVsOneClassifier.decision_function.<locals>.<listcomp>  s&    FFFbS[[__FFFr9   c                 4    g | ]\  }}t          ||          S rk   rG   r#  s      r7   r   z8OneVsOneClassifier.decision_function.<locals>.<listcomp>  s&    OOO'#r_S"%%OOOr9   r  r   )r!   r"   r  r*   rn   r(   vstackr   r   r   r   r   )rW   r1   r   Xspredictionsconfidencesr   s    `     r7   rB   z$OneVsOneClassifier.decision_function  s#   , 	#
 
 
 (?s4+,,,BB////w///BiFFC0@",E,EFFF
 

 	 iOOS9I25N5NOOO
 

 	 #;S=O=OPP?aQQQT7Nr9   c                 *    t          | j                  S r   r   r   s    r7   r   zOneVsOneClassifier.n_classes_  r   r9   c                     t                                                      }t          | j                  j        j        |j        _        t          | j                  j        j        |j        _        |S r   r   r   s     r7   r   z#OneVsOneClassifier.__sklearn_tags__  r   r9   c                     t          | j        j                                      |                               | j        t                                          dd                              dd                    }|S r   r   r   s     r7   r   z'OneVsOneClassifier.get_metadata_routing  r   r9   ry   )rg   rh   ri   rj   r   r   r   rU   __annotations__rz   r
   r/   r   rr   r;   r@   rB   r   r   r   r   r   r   s   @r7   r$   r$     sy        K K\ !j%))*T"$ $D   
 -1      \&+  E E	 EN \//-0011\&+  U U U	  21
Un/ / /.. . .` " " X"          r9   r$   c                        e Zd ZU dZ eddg           eddg          g eeddd          gd	gedgd
Ze	e
d<   dddddZ ed          d             Zd Zd Z fdZ xZ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, `len(estimators_)`)
        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])
    r/   rB   rE   rI   Nneither)closedrandom_stater0   	code_sizer2  rv   r   g      ?)r4  r2  rv   c                >    || _         || _        || _        || _        d S ry   r3  )rW   r0   r4  r2  rv   s        r7   rz   zOutputCodeClassifier.__init__}  s#    ""(r9   Fr{   c                 ^   	 t          | d           t           dfi |	t           d          t           j                  }t                     t          j                   _         j        j	        d         }|dk    rt          d          t          | j        z            }|                    ||f           _        d j         j        dk    <   t           j        d	          rd
 j         j        dk    <   nd j         j        dk    <   d t#           j                  D             t          j         fdt'          t)                              D             t                     t+           j                  	 fdt'          j	        d                   D                        _        t           j        d         d          r j        d         j         _        t           j        d         d          r j        d         j         _         S )a  Fit underlying estimators.

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

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

        **fit_params : dict
            Parameters passed to the ``estimator.fit`` method of each
            sub-estimator.

            .. versionadded:: 1.4
                Only available if `enable_metadata_routing=True`. See
                :ref:`Metadata Routing User Guide <metadata_routing>` for more
                details.

        Returns
        -------
        self : object
            Returns a fitted instance of self.
        r/   no_validation)r1   r2   r   z=OutputCodeClassifier can not be fit when no class is present.)sizeg      ?rJ   rB   g      r   rI   c                     i | ]\  }}||	S rk   rk   )r   r   r6   s      r7   
<dictcomp>z,OutputCodeClassifier.fit.<locals>.<dictcomp>  s    CCC$!QACCCr9   c                 B    g | ]}j         |                           S rk   )
code_book_)r   r   classes_indexrW   r2   s     r7   r   z,OutputCodeClassifier.fit.<locals>.<listcomp>  s)    RRRaT_]1Q401RRRr9   r   r   c              3      K   | ]>} t          t                    j        d d |f         j        j                  V  ?d S )Nr  )r   r8   r0   r/   )r   r   r1   r   r   rW   s     r7   r   z+OutputCodeClassifier.fit.<locals>.<genexpr>  so       8
 8
  !GK  1QQQT7}7N7R  8
 8
 8
 8
 8
 8
r9   r   r   )r   r   r"   r   r2  r   r(   r)   r   r   r   r   r4  uniformr<  rK   r0   r   r<   r   r    r   rv   rn   r   r   )
rW   r1   r2   r3   r2  r  n_estimatorsr   r=  r   s
   ```    @@@r7   r/   zOutputCodeClassifier.fit  sd   : 	*dE222'
 
 
 
 $/Q777)$*;<<$Q'''	!M'*	>>O   9t~566 '..Y4M.NN14#-.4>#677 	848DODOq01147DODOq01CC)DM*B*BCCCHRRRRRR5a;Q;QRRR
 
 

 884;777 8
 8
 8
 8
 8
 8
 8
 171:&&	8
 8
 8
 
 
 4#A&(899 	E"&"21"5"DD4#A&(;<< 	K%)%5a%8%JD"r9   c                     t          |            t          j        fd| j        D             dt          j                  j        }t          || j        d          }| j        |         S )a9  Predict multi-class targets using underlying estimators.

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

        Returns
        -------
        y : ndarray of shape (n_samples,)
            Predicted multi-class targets.
        c                 0    g | ]}t          |          S rk   r&  r   s     r7   r   z0OutputCodeClassifier.predict.<locals>.<listcomp>  s#    ===q_Q""===r9   F)orderrP   	euclidean)metric)	r!   r(   r<   rn   re   r   r   r<  r   )rW   r1   r   r   s    `  r7   r@   zOutputCodeClassifier.predict  sz     	 H====D,<===*
 
 
 	 	

 )DOKPPP}T""r9   c                     t          | j        j                                      | j        t                                          dd                    }|S )r   r   r/   r   r   )r   r   rg   r   r0   r   r   s     r7   r   z)OutputCodeClassifier.get_metadata_routing  sU      dn&=>>>BBn(??..eE.JJ C 
 
 r9   c                     t                                                      }t          | j                  j        j        |j        _        |S ry   )r   r   r   r0   r   r   r   s     r7   r   z%OutputCodeClassifier.__sklearn_tags__  s7    ww''))!)$.!9!9!D!Kr9   )rg   rh   ri   rj   r   r   r   r   r   rU   r.  rz   r
   r/   r@   r   r   r   r   s   @r7   r%   r%     s0        a aJ J2344J/00
 htS$yAAAB'(T"$ $D    03d      \&+  K K	 KZ# # #2  *        r9   r%   ry   )@rj   r<   r  r+   numbersr   r   numpyr(   scipy.sparser   r   baser   r   r   r	   r
   r   r   r   metrics.pairwiser   preprocessingr   utilsr   utils._param_validationr   r   utils._tagsr   utils.metadata_routingr   r   r   r   utils.metaestimatorsr   r   utils.multiclassr   r   r   utils.parallelr   r   utils.validationr   r    r!   r"   __all__r8   r>   rG   rL   r.   rr   r#   r  r  r$   r%   rk   r9   r7   <module>rX     ss   <       " " " " " " " "          	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 8 7 7 7 7 7 ) ) ) ) ) ) % % % % % % 9 9 9 9 9 9 9 9 ! ! ! ! ! !            < ; ; ; ; ; ; ;         
 . - - - - - - -                &  	 	 	  5M 5M 5M 5M 5M 5M 5M 5Mp  &n n n n n	n n nb  ,  "j j j j j+_m j j jZv v v v v- v v v v vr9   