`L i3dZddlZddlZddlZddlmZmZddlZddl m Z ddl m Z mZmZmZmZmZmZmZddlmZddlmZddlmZdd lmZmZdd lmZdd l m!Z!m"Z"m#Z#m$Z$dd l%m&Z&m'Z'dd l(m)Z)m*Z*m+Z+ddl,m-Z-m.Z.ddl/m0Z0m1Z1m2Z2m3Z3gdZ4d dZ5dZ6dZ7dZ8Gdde Z9dZ:Gddeeee Z;dZGddeee Z?y)!aMulticlass 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)IntegralReal) BaseEstimatorClassifierMixinMetaEstimatorMixinMultiOutputMixin _fit_contextclone is_classifier is_regressor)pairwise_distances_argmin)LabelBinarizer)check_random_state) HasMethodsInterval)get_tags)MetadataRouter MethodMapping_raise_for_paramsprocess_routing) _safe_split available_if)_check_partial_fit_first_call_ovr_decision_functioncheck_classification_targets)Paralleldelayed)_check_method_params _num_samplescheck_is_fitted validate_data)OneVsOneClassifierOneVsRestClassifierOutputCodeClassifierc.tj|}t|dk(rR|4|ddk(rd}n|d}tjdt ||zt j||}|St|}|j||fi||S)zFit a single binary estimator.rrz-Label %s is present in all training examples.) npuniquelenwarningswarnstr_ConstantPredictorfitr ) estimatorXy fit_paramsclassesunique_ycs X/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/multiclass.py _fit_binaryr8Qsyy|H 8}  trzaD MM?#gaj/Q '(,,Q9  )$  a)j) cX|j||fdtjdi||S)z(Partially fit a single binary estimator.r4)rr) partial_fitr(array)r0r1r2partial_fit_paramss r7_partial_fit_binaryr>ds.I!QO(8O#45PT   !Qd|8T  r9c t|t||dddddtj|jt |SNFTrOrPrRrQrSr!r"r(repeatrVr rWr1s r7r@z_ConstantPredictor.predictB  # yy,q/22r9c t|t||dddddtj|jt |SrZr\r^s r7rBz$_ConstantPredictor.decision_functionr_r9c t|t||ddddd|jjtj }t j t jd|z |ggt|dS)NFTr[rraxis) r!r"rVastyper(float64r]hstackr )rWr1rVs r7rEz _ConstantPredictor.predict_probasj  # WW^^BJJ 'yy"))QVRL12LO!LLr9N)__name__ __module__ __qualname____doc__r/r@rBrEr9r7r.r.sE 3 3 Mr9r.cfd}|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|drt|jdyt|jy)N estimators_rT)rKgetattrrnr0)rWattrs r7checkz_estimators_has..checks: 4 ' D$$Q' . DNND )r9rk)rprqs` r7_estimators_hasrrs Lr9c.eZdZdZedggedgdgdZddddZed d Z e e d ed dd Z dZ e e ddZe e ddZedZedZfdZdZxZS)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 `. 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 ` 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/Nverboser0n_jobsrtrrvrtc.||_||_||_yNru)rWr0rvrts r7__init__zOneVsRestClassifier.__init__Bs"  r9Fprefer_skip_nested_validationc pt|dtdfi|td_jj |}|j }jj _d|jD}tjjfdt|D_ tjddrjdj_tjdd rjdj_S) aFit 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 ` for more details. Returns ------- self : object Instance of fitted estimator. r/T sparse_outputc3XK|]"}|jj$ywrytoarrayrA.0cols r7 z*OneVsRestClassifier.fit..t8S3;;=&&(8(*rwc 3K|]r\}}ttj|jjdjj |zjj |gtyw)znot %sr3r4N)rr8r0r/label_binarizer_classes_)ricolumnr1 routed_paramsrWs r7rz*OneVsRestClassifier.fit..xs N 6 !GK (2266t44==a@@))2215   N sA8A;rn_features_in_feature_names_in_)rrrr fit_transformtocscrTrrvrt enumeraternrKrr)rWr1r2r3Ycolumnsrs`` @r7r/zOneVsRestClassifier.fitGs< *dE2'    !/T B  ! ! / / 2 GGI--66 8ACC8N84;; M N 'w/ N   4##A&(8 9"&"2"21"5"D"DD  4##A&(; <%)%5%5a%8%J%JD " r9r;c lt||dt|dfi|t||rqt|jDcgc]}t |j c}|_td|_ |jj|jttj||jr8tdj!tj"||j|jj%|}|j'}d|j(D}t+|j,fdt/|j|D|_t1|jdd r|jdj2|_|Scc}w) aPartially 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 ` 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}c3XK|]"}|jj$ywryrrs r7rz2OneVsRestClassifier.partial_fit..rrrvc3~K|]4\}}tt||jj6ywr=N)rr>r0r;)rr0rr1rs r7rz2OneVsRestClassifier.partial_fit..sI8 " 6 )G' (#0#:#:#F#F   8 s:=rr)rrrrange n_classes_r r0rnrrr/rr*r( setdiff1d ValueErrorformatr) transformrrrrvziprKr) rWr1r2r4r=_rrrs ` @r7r;zOneVsRestClassifier.partial_fitsfR ,dMB'   ! )w 7?DT__?UV!dnn 5VD  %3$FD !  ! ! % %dmm 4 r||At}}- .V&1t}}5   ! ! + +A . GGI8ACC8784;;78 &))9)97%C8   4##A&(8 9"&"2"21"5"D"DD  C WsF1c t|t|}|jjdk(rt j |t }|jtj t j|t}t|jD]1\}}t||}t j|||||||k(<3|j|St!|jd}t#j"d} t#j"ddg} |jD]P}| j%t j&t|||kDd| j)t+| Rt j,t+| t} t/j0| | | f|t+|jf} |jj3| S)agPredict 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. multiclassrP)outrr)shape)r!r ry_type_r(emptyfloatfillinfzerosintrrnrGmaximumrrLr<extendwhereappendr*onessp csc_matrixinverse_transform) rWr1 n_samplesmaxima argmaximarepredthreshindicesindptrdata indicators r7r@zOneVsRestClassifier.predicts  O  ( (L 8XXiu5F KK #6I!$"2"23 .1&q!, 64V4,- &D.) .==+ +243C3CA3FGFkk#&G[[qc*F%% ,rxx1(=(FGJK c'l+ ,773wJsC#rBc6t|t|jdk(r|jdj|St j |jDcgc]!}|j|j #c}jScc}w)aDecision 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. rr)r!r*rnrBr(r<rAr)rWr1ests r7rBz%OneVsRestClassifier.decision_function2s|.  t A %##A&88; ;xx9=9I9I J#S " "1 % + + - J ! Js&BcL|jjjdS)z(Whether this is a multilabel classifier. multilabel)rr startswithrWs r7rzOneVsRestClassifier.multilabel_Ps!$$,,77 EEr9c,t|jSzNumber of classes.r*rrs r7rzOneVsRestClassifier.n_classes_U4==!!r9ct|}t|jjj |j_t|jjj |j_|Sz@Indicate if wrapped estimator is using a precomputed Gram matrixsuper__sklearn_tags__rr0 input_tagspairwisesparserWtags __class__s r7rz$OneVsRestClassifier.__sklearn_tags__ZWw')#+DNN#;#F#F#O#O !)$..!9!D!D!K!K r9ct|jjj|j |j t j ddj dd}|SjGet metadata routing of this object. Please check :ref:`User Guide ` on how the routing mechanism works. .. versionadded:: 1.4 Returns ------- routing : MetadataRouter A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating routing information. ownerr/callercalleer;r0method_mappingrrrgadd_self_requestaddr0rrWrouters r7get_metadata_routingz(OneVsRestClassifier.get_metadata_routingad !8!8 9  d # S..,E%0M-@   r9ry)rgrhrirjrr_parameter_constraintsrzr r/rrrr;r@rErBpropertyrrrr __classcell__rs@r7r$r$s jZ!%)*T"; -1! &+@ @D/-01&+N 2 N`$FL//23'4'R/"567 8 :FF""r9r$c Rtj||k(||k(}||}tj|jt}d|||k(<d|||k(<tj t ||}t|||} t|t||d|d|| ||g|fS)z+Fit a single binary estimator (one-vs-one).rrparamsrN)rr) r( logical_orrrraranger rr8r) r0r1r2rjr3condy_binaryindcondfit_params_subsets r7_fit_ovo_binaryr}s ==aa (D $Axx%HHQ!VHQ!Vii Q(.G,Qz7S   1dG ) r0r1r2rrr=rrpartial_fit_params_subsets r7_partial_fit_ovo_binaryrs ==aa (D $A 1v{==#a$8 ($% !# qw=V   r9ceZdZUdZedggedgdZeed<dddZ e d d Z e e d e d dd Zd ZdZedZfdZdZxZS)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 `. 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 ` 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/Nr0rvrrc ||_||_yryr)rWr0rvs r7rzzOneVsOneClassifier.__init__s" r9Fr{c 8t|dtdfi|tddgd\tt j _tj dk(r tdj jdtttj fd tD}|d_j!j"j$}|r |d_Sd _S) aFit 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 ` for more details. Returns ------- self : object The fitted underlying estimator. r/csrcscF)rRrOrzAOneVsOneClassifier can not be fit when only one class is present.rrc 3K|]k}t|dzD]W}ttjj|j|jj Ymyw)rr3N)rrrr0rr/)rrrr1 n_classesrrWr2s r7rz)OneVsOneClassifier.fit../s 1!&q1ui!8 110 NN MM!, MM!,'4'>'>'B'B  1 1sA1A4N)rrr"rr(r)rr*rrlistrrrvrrnrrrpairwise_indices_)rWr1r2r3estimators_indicesrr rs``` @@r7r/zOneVsOneClassifier.fits#: *dE2'     !Quen 1 %Q' !  t}}  "S MM''* ! 0HDKK0 1"'y!1 1   &.a0((*55>>:B!3A!6 IM r9r;c Xt|dtdfi|t|}|rNtjjdz zdzDcgc]}t j c}_ttjjr8tdjtjjtddgd|\t!t#j$tjd}t'j( fd t+j|D_d _t/jd d rjd j0_Scc}w)aPartially 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 ` for more details. Returns ------- self : object The partially fitted underlying estimator. r;rz6Mini-batch contains {0} while it must be subset of {1}r r FrRrOrSrc 3K|]S\}\}}tt|j|j|jjUywr)rrrr0r;)rr0rrr1rrWr2s r7rz1OneVsOneClassifier.partial_fit..se 8 " 6Aq -G+ , a  a #0#:#:#F#F    8 sAANrr)rrrrrr r0rnr*r(rrrrr)r"r itertools combinationsrrvrrrKr) rWr1r2r4r= first_callrrrs ``` @r7r;zOneVsOneClassifier.partial_fitFsR ,dMB'   ! 34A t$//A2EF!KL dnn% D  r||At}}- .HOOIIaL$--     %.#  1 %Q' --eDOO.DaH 784;;7 8 &))9)9L%J 8  "& 4##A&(8 9"&"2"21"5"D"DD  O sF'c|j|}|jdk(r=t|jd}|j||kDj t S|j|jdS)aEstimate 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. rrrrb)rBrrLrnrrdrargmax)rWr1rrs r7r@zOneVsOneClassifier.predictsm"  " "1 % ??a 243C3CA3FGF==!f*!4!4S!9: :}}QXX1X-..r9c t|t||ddd}|j}||gt|jz}n|Dcgc] }|dd|f }}t j t|j|Dcgc]\}}|j|c}}j}t j t|j|Dcgc]\}}t||c}}j}t||t|j} |jdk(r | dddfS| Scc}wcc}}wcc}}w)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. TFrNrr)r!r"rr*rnr(vstackrr@rrGrrr) rWr1rXsidxrXi predictions confidencesrs r7rBz$OneVsOneClassifier.decision_functions,,    #  (( ?s4++,,B'./!AsF)/B/ii,/0@0@",E FbS[[_ F ! ii589I9I25N O'#r_S" % O !  #; S=O P ??a QT7N0 G PsD9D> E c,t|jSrrrs r7rzOneVsOneClassifier.n_classes_rr9ct|}t|jjj |j_t|jjj |j_|Srrrs r7rz#OneVsOneClassifier.__sklearn_tags__rr9ct|jjj|j |j t j ddj dd}|Srrrs r7rz'OneVsOneClassifier.get_metadata_routingrr9ry)rgrhrirjrrrrU__annotations__rzr r/rrrr;r@rBrrrrrrs@r7r#r#sK\!%)*T"$D -1&+E EN/-01&+U 2 Un/..`""r9r#ceZdZUdZeddgeddggeedddgd gedgd Ze e d <d ddd dZ e ddZ dZdZfdZxZS)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 `. 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 `. 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 ` 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/rBrErINneither)closed random_stater0 code_sizer(rvrg?)r*r(rvc<||_||_||_||_yryr))rWr0r*r(rvs r7rzzOutputCodeClassifier.__init__s""( r9Fr{c  t|dtdfi| td|}tj}t |t j|_jjd}|dk(r tdt|jz}|j||f_djjdkD<tj d rd jjd k7<nd jjd k7<t#jDcic]\}}|| } }}t j$t't)|Dcgc]}j| ||c}t  t+j, fdt' jd D_tj.ddrj.dj0_tj.ddrj.dj2_Scc}}wcc}w)aFit 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 ` for more details. Returns ------- self : object Returns a fitted instance of self. r/ no_validation)r1r2rz=OutputCodeClassifier can not be fit when no class is present.)sizeg?rJrBgrrIrrc3K|]B}ttjdd|fjjDyw)Nr )rr8r0r/)rrr1rrrWs r7rz+OutputCodeClassifier.fit..sM8  !GK 1QT7}7N7N7R7R  8 sAA rr)rrr"rr(rr(r)rrrrr*uniform code_book_rKr0rr<rr rrvrnrr) rWr1r2r3r(r  n_estimatorsrr6 classes_indexrrs `` @@r7r/zOutputCodeClassifier.fits: *dE2'    $/Q 7)$*;*;< $Q' !  MM''* >O 9t~~56 '..Y 4M.N14#-. 4>>#6 748DOODOOq0 147DOODOOq0 1*3DMM*BC$!QAC C HH;@a;Q RaT__]1Q40 1 R  884;;78 1771:& 8   4##A&(8 9"&"2"21"5"D"DD  4##A&(; <%)%5%5a%8%J%JD " 'D Ss  I9Ic t|tj|jDcgc]}t ||c}dtj j }t||jd}|j|Scc}w)a9Predict 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)orderrP euclidean)metric) r!r(r<rnrGrerrr1r)rWr1rrrs r7r@zOutputCodeClassifier.predictss  HH,0,<,< =q_Q " =**  ! )DOOKP}}T"" >sBct|jjj|jt jdd}|S)rrr/rr)rrrgrr0rrs r7rz)OutputCodeClassifier.get_metadata_routingsL dnn&=&=>BBnn(?..eE.JC  r9ct|}t|jjj |j_|Sry)rrrr0rrrs r7rz%OutputCodeClassifier.__sklearn_tags__s6w')!)$..!9!D!D!K!K r9)rgrhrirjrrrrrrUr$rzr r/r@rrrrs@r7r%r%saJ 23 4 / 0 tS$yAB'(T"$D03d &+K KZ#2*r9r%ry)@rjr<rr+numbersrrnumpyr( scipy.sparserrbaserrrr r r r r metrics.pairwiser preprocessingrutilsrutils._param_validationrr utils._tagsrutils.metadata_routingrrrrutils.metaestimatorsrrutils.multiclassrrrutils.parallelrrutils.validationrr r!r"__all__r8r>rGrLr.rrr$rrr#r%rkr9r7rJs< "   8)%9! < . & 5M5Mp&p pf ,"j+_mjZ v- vr9