
    -i3                        S r SSKrSSKrSSKrSSKJrJr  SSKrSSK	J
r  SSKJrJrJrJrJrJrJrJr  SSKJr  SSKJr  SSKJr  SS	KJrJr  SS
KJr  SSK J!r!J"r"J#r#J$r$  SSK%J&r&J'r'  SSK(J)r)J*r*J+r+  SSK,J-r-J.r.  SSK/J0r0J1r1J2r2J3r3  / SQr4S S jr5S r6S r7S r8 " S S\5      r9S r: " S S\\\\5      r;S r<S r= " S S\\\5      r> " S S\\\5      r?g)!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)OneVsOneClassifierOneVsRestClassifierOutputCodeClassifierc                 2   [         R                  " U5      n[        U5      S:X  aS  Ub5  US   S:X  a  SnOUS   n[        R                  " S[        XF   5      -  5        [        5       R                  X5      n U $ [        U 5      n U R                  " X40 UD6  U $ )zFit a single binary estimator.r   r   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          E/var/www/html/venv/lib/python3.13/site-packages/sklearn/multiclass.py_fit_binaryr8   Q   s    yy|H
8}trzaDMM?#gj/Q '(,,Q9	  )$	a)j)    c                 X    U R                   " X4S[        R                  " S5      0UD6  U $ )z(Partially fit a single binary estimator.r4   )r   r   )partial_fitr(   array)r0   r1   r2   partial_fit_paramss       r7   _partial_fit_binaryr>   d   s*    !O(8O<NOr9   c                     [        U 5      (       a  U R                  U5      $  [        R                  " U R	                  U5      5      nU$ ! [
        [        4 a    U R                  U5      SS2S4   n U$ f = f)z1Make predictions using a single binary estimator.Nr   )r   predictr(   raveldecision_functionAttributeErrorNotImplementedErrorpredict_proba)r0   r1   scores      r7   _predict_binaryrG   j   sx    I  ##144Q78 L /0 1''*1a40L1s   %A
 
(A65A6c                 H    [        U S5      (       a  [        U 5      (       a  gg)z0Threshold for predictions from binary estimator.rB                 ?)hasattrr   )r0   s    r7   _threshold_for_binary_predictrL   v   s"    y-..=3K3K r9   c                   0    \ rS rSrSrS rS rS rS rSr	g)	r.      z;Helper predictor to be used when only one class is present.c                 D    [        SS SSS9n[        XUSX34S9  X l        U $ )NFT)ensure_all_finitedtype	ensure_2daccept_sparse)resetvalidate_separately)dictr"   y_)selfr1   r2   check_paramss       r7   r/   _ConstantPredictor.fit   s8    #45PT
 	Qd8T	
 r9   c           
          [        U 5        [        U USS SSSS9  [        R                  " U R                  [        U5      5      $ NFTrP   rQ   rS   rR   rT   r!   r"   r(   repeatrW   r    rX   r1   s     r7   r@   _ConstantPredictor.predict   B    #	
 yy,q/22r9   c           
          [        U 5        [        U USS SSSS9  [        R                  " U R                  [        U5      5      $ r\   r^   r`   s     r7   rB   $_ConstantPredictor.decision_function   rb   r9   c           
          [        U 5        [        U USS SSSS9  U R                  R                  [        R
                  5      n[        R                  " [        R                  " SU-
  U/5      /[        U5      SS9$ )NFTr]   r   r   axis)	r!   r"   rW   astyper(   float64r_   hstackr    )rX   r1   rW   s      r7   rE    _ConstantPredictor.predict_proba   sj    #	
 WW^^BJJ'yy"))QVRL12LO!LLr9   )rW   N)
__name__
__module____qualname____firstlineno____doc__r/   r@   rB   rE   __static_attributes__ r9   r7   r.   r.      s    E33Mr9   r.   c                    ^  U 4S jnU$ )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                    > [        U S5      (       a  [        U R                  S   T5        g[        U R                  T5        g)Nestimators_r   T)rK   getattrru   r0   )rX   attrs    r7   check_estimators_has.<locals>.check   s=    4''D$$Q'.  DNND)r9   rr   )rw   rx   s   ` r7   _estimators_hasrz      s     Lr9   c                   0  ^  \ rS rSrSr\" S/5      /\S/S/S.rSSS.S	 jr\	" S
S9S 5       r
\" \" S5      5      \	" S
S9SS j5       5       rS r\" \" S5      5      S 5       r\" \" S5      5      S 5       r\S 5       r\S 5       rU 4S jrS rSrU =r$ )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_jobsr}   r   r   r}   c                (    Xl         X l        X0l        g Nr~   )rX   r0   r   r}   s       r7   __init__OneVsRestClassifier.__init__B  s    "r9   Fprefer_skip_nested_validationc                 z  ^ ^^ [        UT S5        [        T S40 UD6m[        SS9T l        T R                  R	                  U5      nUR                  5       nT R                  R                  T l        S UR                   5       n[        T R                  T R                  S9" UUU 4S j[        U5       5       5      T l        [        T R                  S   S5      (       a  T R                  S   R                  T l        [        T R                  S   S	5      (       a  T R                  S   R                  T l        T $ )
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   \   #    U  H"  oR                  5       R                  5       v   M$     g 7fr   toarrayrA   .0cols     r7   	<genexpr>*OneVsRestClassifier.fit.<locals>.<genexpr>t        8CS;;=&&((C   *,r   c           
   3      >#    U  Ho  u  p[        [        5      " TR                  TUTR                  R                  S TR                  R
                  U   -  TR                  R
                  U   /S9v   Mq     g7f)znot %sr3   r4   N)r   r8   r0   r/   label_binarizer_classes_)r   icolumnr1   routed_paramsrX   s      r7   r   r   x  sw      N
 0	 K (2266t44==a@@))2215	 0s   A7A:r   n_features_in_feature_names_in_)r   r   r   r   fit_transformtocscr   Tr   r   r}   	enumerateru   rK   r   r   )rX   r1   r2   r3   Ycolumnsr   s   ``    @r7   r/   OneVsRestClassifier.fitG  s   < 	*dE2'
 
 !/T B!!//2GGI--668ACC8 $4;;M N
 'w/N
 
 4##A&(899"&"2"21"5"D"DD4##A&(;<<%)%5%5a%8%J%JD"r9   r;   c                   ^^ [        X@S5        [        U S40 UD6m[        X5      (       aq  [        U R                  5       Vs/ s H  n[        U R                  5      PM     snU l        [        SS9U l	        U R                  R                  U R                  5        [        [        R                  " X R                  5      5      (       a9  [        SR!                  [        R"                  " U5      U R                  5      5      eU R                  R%                  U5      nUR'                  5       nS UR(                   5       n[+        U R,                  S9" UU4S j[/        U R                  U5       5       5      U l        [1        U R                  S   S	5      (       a  U R                  S   R2                  U l        U $ s  snf )
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;   Tr   z;Mini-batch contains {0} while classes must be subset of {1}c              3   \   #    U  H"  oR                  5       R                  5       v   M$     g 7fr   r   r   s     r7   r   2OneVsRestClassifier.partial_fit.<locals>.<genexpr>  r   r   r   c              3   |   >#    U  H1  u  p[        [        5      " UTUTR                  R                  S 9v   M3     g7fr=   N)r   r>   r0   r;   )r   r0   r   r1   r   s      r7   r   r     sD      8
 &D!	 '(#0#:#:#F#F	 &Ds   9<r   r   )r   r   r   range
n_classes_r   r0   ru   r   r   r/   r   r*   r(   	setdiff1d
ValueErrorformatr)   	transformr   r   r   r   ziprK   r   )	rX   r1   r2   r4   r=   _r   r   r   s	    `      @r7   r;   OneVsRestClassifier.partial_fit  sm   R 	,MB'
 !
 )77?DT__?UV?U!dnn 5?UVD %3$FD!!!%%dmm4r||A}}-..V&1t}}5  !!++A.GGI8ACC8#4;;7 8
 &))9)97%C8
 
 4##A&(899"&"2"21"5"D"DDC  Ws   F=c           	         [        U 5        [        U5      nU R                  R                  S:X  a  [        R
                  " U[        S9nUR                  [        R                  * 5        [        R                  " U[        S9n[        U R                  5       H+  u  pV[        Xa5      n[        R                  " X7US9  XTX7:H  '   M-     U R                  U   $ [!        U R                  S   5      n["        R"                  " S5      n	["        R"                  " SS/5      n
U R                   HQ  nU	R%                  [        R&                  " [        Xa5      U:  5      S   5        U
R)                  [+        U	5      5        MS     [        R,                  " [+        U	5      [        S9n[.        R0                  " XU
4U[+        U R                  5      4S9nU R                  R3                  U5      $ )a  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rQ   )outr   r   )shape)r!   r    r   y_type_r(   emptyfloatfillinfzerosintr   ru   rG   maximumr   rL   r<   extendwhereappendr*   onessp
csc_matrixinverse_transform)rX   r1   	n_samplesmaxima	argmaximar   epredthreshindicesindptrdata	indicators                r7   r@   OneVsRestClassifier.predict  su    	 O	  ((L8XXiu5FKK #6I!$"2"23&q,

6V4,-&.) 4 ==++243C3CA3FGFkk#&G[[qc*F%%rxx(=(FGJKc'l+ & 773w<s3D'	3t?O?O;P/QI ((::9EEr9   rE   c                    [        U 5        [        R                  " U R                   Vs/ s H  o"R	                  U5      SS2S4   PM     sn5      R
                  n[        U R                  5      S:X  a  [        R                  " SU-
  U4SS9nU R                  (       dB  [        R                  " USS9SS2[        R                  4   n[        R                  " X4X4S:g  S9  U$ s  snf )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_`.
Nr   rf   r   )r   r   )r!   r(   r<   ru   rE   r   r*   concatenatemultilabel_sumnewaxisdivide)rX   r1   r   r   row_sumss        r7   rE   !OneVsRestClassifier.predict_proba  s    2 	 HH8H8HI8H1ooa(A.8HIJLLt A% Q|!4Avvaa(BJJ7HIIaqA> Js   !C$rB   c                 >   [        U 5        [        U R                  5      S:X  a  U R                  S   R                  U5      $ [        R
                  " U R                   Vs/ s H!  o"R                  U5      R                  5       PM#     sn5      R                  $ s  snf )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   )r!   r*   ru   rB   r(   r<   rA   r   )rX   r1   ests      r7   rB   %OneVsRestClassifier.decision_function2  s    . 	t A%##A&88;;xx9=9I9IJ9I#""1%++-9IJ

!	Js   !(Bc                 L    U R                   R                  R                  S5      $ )z(Whether this is a multilabel classifier.
multilabel)r   r   
startswithrX   s    r7   r   OneVsRestClassifier.multilabel_P  s!     $$,,77EEr9   c                 ,    [        U R                  5      $ zNumber of classes.r*   r   r   s    r7   r   OneVsRestClassifier.n_classes_U       4==!!r9   c                   > [         TU ]  5       n[        U R                  5      R                  R
                  UR                  l        [        U R                  5      R                  R                  UR                  l        U$ z@Indicate if wrapped estimator is using a precomputed Gram matrixsuper__sklearn_tags__r   r0   
input_tagspairwisesparserX   tags	__class__s     r7   r   $OneVsRestClassifier.__sklearn_tags__Z  W    w')#+DNN#;#F#F#O#O !)$..!9!D!D!K!Kr9   c                     [        U R                  R                  S9R                  U 5      R	                  U R
                  [        5       R	                  SSS9R	                  SSS9S9nU$ "  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   rl   add_self_requestaddr0   r   rX   routers     r7   get_metadata_routing(OneVsRestClassifier.get_metadata_routinga  d      !8!89d#S..,E%0M-@	   	 r9   )r   r0   ru   r   r   r   r   r}   r   )rl   rm   rn   ro   rp   r   r   _parameter_constraintsr   r
   r/   r   rz   r;   r@   rE   rB   propertyr   r   r   r  rq   __classcell__r   s   @r7   r$   r$      s   jZ !%)*T"; -1! 
 &+@	@D /-01&+N	 2
N`$FL //23' 4'R /"567 8: F F " " r9   r$   c           
      6   [         R                  " X#:H  X$:H  5      nX&   n[         R                  " UR                  [        5      nSXrU:H  '   SXrU:H  '   [         R
                  " [        U5      5      U   n[        XUS9n	[        U [        XSUS9S   UU	X4/S9U4$ )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    ==(D	Axx%HH!VH!ViiQ(.G,Q7S	dG<Q?(F	
 		 	r9   c                     [         R                  " X#:H  X$:H  5      nX&   n[        U5      S:w  a4  [         R                  " U5      nSXrU:H  '   [	        XUS9n[        XU   XxS9$ U $ )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    st     ==(D	A
1v{==#a$8$%
! #w
 	
 r9   c                      ^  \ rS rSr% Sr\" S/5      /\S/S.r\\	S'   SS.S jr
\" S	S
9S 5       r\" \" S5      5      \" S	S
9SS j5       5       rS rS r\S 5       rU 4S jrS rSrU =r$ )r#   i  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   r   r  r   c                    Xl         X l        g r   r  )rX   r0   r   s      r7   r   OneVsOneClassifier.__init__  s    "r9   Fr   c                 <  ^ ^^^^ [        UT S5        [        T S40 UD6m[        T TTSS/SS9u  mm[        T5        [        R
                  " T5      T l        [        T R                  5      S:X  a  [        S5      eT R                  R                  S   m[        [        [        T R                  S	9" UUUU U4S
 j[        T5       5       5      6 5      nUS   T l        T R!                  5       R"                  R$                  nU(       a  US   T l        T $ ST l        T $ )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)rS   rP   r   zAOneVsOneClassifier can not be fit when only one class is present.r   r   c              3      >#    U  Hl  n[        US -   T5        HU  n[        [        5      " TR                  TTTR                  U   TR                  U   TR                  R
                  S9v   MW     Mn     g7f)r   r3   N)r   r   r  r0   r   r/   )r   r   r  r1   	n_classesr   rX   r2   s      r7   r   )OneVsOneClassifier.fit.<locals>.<genexpr>/  st      1 "2A!&q1ui!8A  0 NN MM!, MM!,'4'>'>'B'B "9 "2s   A4A7N)r   r   r"   r   r(   r)   r   r*   r   r   listr   r   r   r   ru   r   r   r   pairwise_indices_)rX   r1   r2   r3   estimators_indicesr   r#  r   s   ```   @@r7   r/   OneVsOneClassifier.fit  s&   : 	*dE2'
 
 !Quen
1 	%Q'		!t}}"S  MM''*	!DKK0 1 1 "'y!11 
& .a0((*55>>:B!3A!6 IMr9   r;   c           	      x  ^ ^^^ [        UT S5        [        T S40 UD6m[        T U5      nU(       aQ  [        T R                  T R                  S-
  -  S-  5       Vs/ s H  n[        T R                  5      PM     snT l        [        [        R                  " TT R                  5      5      (       a9  [        SR                  [        R                  " T5      T R                  5      5      e[        T TTSS/SUS9u  mm[!        T5        ["        R$                  " [        T R                  5      S5      n['        T R(                  S	9" UUU U4S
 j[+        T R                  U5       5       5      T l        ST l        [/        T R                  S   S5      (       a  T R                  S   R0                  T l        T $ s  snf )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;   r      z6Mini-batch contains {0} while it must be subset of {1}r  r   FrS   rP   rT   r   c           
   3      >#    U  HP  u  nu  p#[        [        5      " UTTTR                  U   TR                  U   TR                  R                  S 9v   MR     g7fr   )r   r  r   r0   r;   )r   r0   r   r  r1   r   rX   r2   s       r7   r   1OneVsOneClassifier.partial_fit.<locals>.<genexpr>  s`      
8
 &K!	6A +,a a #0#:#:#F#F &Ks   AANr   r   )r   r   r   r   r   r   r0   ru   r*   r(   r   r   r   r   r)   r"   r   	itertoolscombinationsr   r   r   r&  rK   r   )	rX   r1   r2   r4   r=   
first_callr   r/  r   s	   ```     @r7   r;   OneVsOneClassifier.partial_fitF  s   R 	,dMB'
 !
 34A
 t$//A2EF!KL LA dnn%L D
 r||At}}-..HOOIIaL$--   %.#
1 	%Q' --eDOO.DaH#4;;7 
8
 &))9)9L%J
8
 

 "&4##A&(899"&"2"21"5"D"DDO s   F7c                     U R                  U5      nU R                  S:X  a<  [        U R                  S   5      nU R                  X#:  R                  [        5         $ U R                  UR                  SS9   $ )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   rf   )rB   r   rL   ru   r   rh   r   argmax)rX   r1   r   r   s       r7   r@   OneVsOneClassifier.predict  sk    " ""1%??a243C3CA3FGF==!*!4!4S!9::}}QXX1X-..r9   c           
         [        U 5        [        U USSSS9nU R                  nUc  U/[        U R                  5      -  nOU Vs/ s H  oASS2U4   PM     nn[
        R                  " [        U R                  U5       VVs/ s H  u  pVUR                  U5      PM     snn5      R                  n[
        R                  " [        U R                  U5       VVs/ s H  u  pV[        XV5      PM     snn5      R                  n[        Xx[        U R                  5      5      n	U R                  S:X  a	  U	SS2S4   $ U	$ s  snf s  snnf s  snnf )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+  Nr*  r   )r!   r"   r&  r*   ru   r(   vstackr   r@   r   rG   r   r   r   )
rX   r1   r   Xsidxr   Xipredictionsconfidencesr   s
             r7   rB   $OneVsOneClassifier.decision_function  s/   , 	#
 ((?s4++,,B'./wAsF)wB/ii,/0@0@",EF,ES[[_,EF

! 	 ii589I9I25NO5N'#_S%5NO

! 	 #;S=OP??aQT7N 0 G Ps   D>E
E	
c                 ,    [        U R                  5      $ r   r   r   s    r7   r   OneVsOneClassifier.n_classes_  r   r9   c                   > [         TU ]  5       n[        U R                  5      R                  R
                  UR                  l        [        U R                  5      R                  R                  UR                  l        U$ r   r   r   s     r7   r   #OneVsOneClassifier.__sklearn_tags__  r   r9   c                     [        U R                  R                  S9R                  U 5      R	                  U R
                  [        5       R	                  SSS9R	                  SSS9S9nU$ r   r   r  s     r7   r  'OneVsOneClassifier.get_metadata_routing  r  r9   )r   r0   ru   r   r   r&  r   )rl   rm   rn   ro   rp   r   r   r  rV   __annotations__r   r
   r/   r   rz   r;   r@   rB   r  r   r   r  rq   r	  r
  s   @r7   r#   r#     s    K\ !%)*T"$D 
 -1  &+E	EN /-01&+U	 2
Un/..` " " r9   r#   c                      ^  \ rS rSr% Sr\" SS/5      \" SS/5      /\" \SSSS	9/S
/\S/S.r	\
\S'   SSSS.S jr\" SS9S 5       rS rS rU 4S jrSrU =r$ )r%   i  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_sizerG  r   r  g      ?)rI  rG  r   c                4    Xl         X l        X0l        X@l        g r   rH  )rX   r0   rI  rG  r   s        r7   r   OutputCodeClassifier.__init__  s    ""(r9   Fr   c           	        ^ ^^
^ [        UT S5        [        T S40 UD6m[        T SUS9n[        T R                  5      n[        U5        [        R                  " U5      T l        T R                  R                  S   nUS:X  a  [        S5      e[        UT R                  -  5      nUR                  XV4S9T l        ST R                  T R                  S:  '   [        T R                   S	5      (       a  S
T R                  T R                  S:g  '   OST R                  T R                  S:g  '   [#        T R                  5       VVs0 s H  u  pxX_M	     n	nn[        R$                  " ['        [)        U5      5       Vs/ s H  nT R                  XU         PM     sn[        S9m
[+        T R,                  S9" UU
UU 4S j['        T
R                  S   5       5       5      T l        [        T R.                  S   S5      (       a  T R.                  S   R0                  T l        [        T R.                  S   S5      (       a  T R.                  S   R2                  T l        T $ s  snnf s  snf )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   r   r   c              3      >#    U  H@  n[        [        5      " TR                  TTS S 2U4   TR                  R                  S9v   MB     g 7f)Nr"  )r   r8   r0   r/   )r   r   r1   r   r   rX   s     r7   r   +OutputCodeClassifier.fit.<locals>.<genexpr>  sG      8
 ' K 1QT7}7N7N7R7R 's   AAr   r   )r   r   r"   r   rG  r   r(   r)   r   r   r   r   rI  uniform
code_book_rK   r0   r   r<   r   r    r   r   ru   r   r   )rX   r1   r2   r3   rG  r#  n_estimatorsr   r6   classes_indexr   r   s   ``        @@r7   r/   OutputCodeClassifier.fit  s   : 	*dE2'
 
 $/Q7)$*;*;<$Q'		!MM''*	>O  9t~~56 '..Y4M.N14#-.4>>#67748DOODOOq0147DOODOOq01*3DMM*BC*B$!*BCHH;@a;QR;QaT__]Q401;QR

 $4;;7 8
 1771:&	8
 
 4##A&(899"&"2"21"5"D"DD4##A&(;<<%)%5%5a%8%J%JD"' D Ss   I;I$c           	         [        U 5        [        R                  " U R                   Vs/ s H  n[	        X!5      PM     snS[        R
                  S9R                  n[        X0R                  SS9nU R                  U   $ s  snf )zPredict 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.
F)orderrQ   	euclidean)metric)
r!   r(   r<   ru   rG   ri   r   r   rR  r   )rX   r1   r   r   r   s        r7   r@   OutputCodeClassifier.predict  su     	 HH,0,<,<=,<q_Q",<=**
 !	 	

 )OOKP}}T"" >s   Bc                     [        U R                  R                  S9R                  U R                  [        5       R                  SSS9S9nU$ )r   r   r/   r   r   )r   r   rl   r  r0   r   r  s     r7   r  )OutputCodeClassifier.get_metadata_routing  sL      dnn&=&=>BBnn(?..eE.J C 
 r9   c                    > [         TU ]  5       n[        U R                  5      R                  R
                  UR                  l        U$ r   )r   r   r   r0   r   r   r   s     r7   r   %OutputCodeClassifier.__sklearn_tags__  s6    w')!)$..!9!D!D!K!Kr9   )	r   rR  rI  r0   ru   r   r   r   rG  )rl   rm   rn   ro   rp   r   r   r   r   r  rV   rC  r   r
   r/   r@   r  r   rq   r	  r
  s   @r7   r%   r%     s    aJ 234/0
 tS$yAB'(T"$D  03d  &+K	KZ#2* r9   r%   r   )@rp   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.   rz   r$   r  r  r#   r%   rr   r9   r7   <module>ro     s   <    "  	 	 	 8 ) % 9 !  < 
 . &	5M 5Mp&p	pf,"j+_m jZv- vr9   