OneVsOneClassifier#

classsklearn.multiclass.OneVsOneClassifier(estimator,*,n_jobs=None)[source]#

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 fitn_classes*(n_classes-1)/2 classifiers,this method is usually slower than one-vs-the-rest, due to itsO(n_classes^2) complexity. However, this method may be advantageous foralgorithms such as kernel algorithms which don’t scale well withn_samples. This is because each individual learning problem only involvesa small subset of the data whereas, with one-vs-the-rest, the completedataset is usedn_classes times.

Read more in theUser Guide.

Parameters:
estimatorestimator object

A regressor or a classifier that implementsfit.When a classifier is passed,decision_function will be usedin priority and it will fallback topredict_proba if it is notavailable.When a regressor is passed,predict is used.

n_jobsint, default=None

The number of jobs to use for the computation: then_classes*(n_classes-1)/2 OVO problems are computed in parallel.

None means 1 unless in ajoblib.parallel_backend context.-1 means using all processors. SeeGlossaryfor more details.

Attributes:
estimators_list ofn_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_), orNone

Indices of samples used when training the estimators.None whenestimator’spairwise tag is False.

n_features_in_int

Number of features seen duringfit.

Added in version 0.24.

feature_names_in_ndarray of shape (n_features_in_,)

Names of features seen duringfit. Defined only whenXhas feature names that are all strings.

Added in version 1.0.

See also

OneVsRestClassifier

One-vs-all multiclass strategy.

OutputCodeClassifier

(Error-Correcting) Output-Code multiclass strategy.

Examples

>>>fromsklearn.datasetsimportload_iris>>>fromsklearn.model_selectionimporttrain_test_split>>>fromsklearn.multiclassimportOneVsOneClassifier>>>fromsklearn.svmimportLinearSVC>>>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])
decision_function(X)[source]#

Decision function for the OneVsOneClassifier.

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

Parameters:
Xarray-like of shape (n_samples, n_features)

Input data.

Returns:
Yarray-like of shape (n_samples, n_classes) or (n_samples,)

Result of callingdecision_function on the final estimator.

Changed in version 0.19:output shape changed to(n_samples,) to conform toscikit-learn conventions for binary classification.

fit(X,y,**fit_params)[source]#

Fit underlying estimators.

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

Data.

yarray-like of shape (n_samples,)

Multi-class targets.

**fit_paramsdict

Parameters passed to theestimator.fit method of eachsub-estimator.

Added in version 1.4:Only available ifenable_metadata_routing=True. SeeMetadata Routing User Guide for moredetails.

Returns:
selfobject

The fitted underlying estimator.

get_metadata_routing()[source]#

Get metadata routing of this object.

Please checkUser Guide on how the routingmechanism works.

Added in version 1.4.

Returns:
routingMetadataRouter

AMetadataRouter encapsulatingrouting information.

get_params(deep=True)[source]#

Get parameters for this estimator.

Parameters:
deepbool, default=True

If True, will return the parameters for this estimator andcontained subobjects that are estimators.

Returns:
paramsdict

Parameter names mapped to their values.

partial_fit(X,y,classes=None,**partial_fit_params)[source]#

Partially fit underlying estimators.

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

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

Data.

yarray-like of shape (n_samples,)

Multi-class targets.

classesarray, shape (n_classes, )

Classes across all calls to partial_fit.Can be obtained vianp.unique(y_all), where y_all is thetarget vector of the entire dataset.This argument is only required in the first call of partial_fitand can be omitted in the subsequent calls.

**partial_fit_paramsdict

Parameters passed to theestimator.partial_fit method of eachsub-estimator.

Added in version 1.4:Only available ifenable_metadata_routing=True. SeeMetadata Routing User Guide for moredetails.

Returns:
selfobject

The partially fitted underlying estimator.

predict(X)[source]#

Estimate the best class label for each sample in X.

This is implemented asargmax(decision_function(X),axis=1) whichwill return the label of the class with most votes by estimatorspredicting the outcome of a decision for each possible class pair.

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

Data.

Returns:
ynumpy array of shape [n_samples]

Predicted multi-class targets.

score(X,y,sample_weight=None)[source]#

Returnaccuracy on provided data and labels.

In multi-label classification, this is the subset accuracywhich is a harsh metric since you require for each sample thateach label set be correctly predicted.

Parameters:
Xarray-like of shape (n_samples, n_features)

Test samples.

yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True labels forX.

sample_weightarray-like of shape (n_samples,), default=None

Sample weights.

Returns:
scorefloat

Mean accuracy ofself.predict(X) w.r.t.y.

set_params(**params)[source]#

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects(such asPipeline). The latter haveparameters of the form<component>__<parameter> so that it’spossible to update each component of a nested object.

Parameters:
**paramsdict

Estimator parameters.

Returns:
selfestimator instance

Estimator instance.

set_partial_fit_request(*,classes:bool|None|str='$UNCHANGED$')OneVsOneClassifier[source]#

Configure whether metadata should be requested to be passed to thepartial_fit method.

Note that this method is only relevant when this estimator is used as asub-estimator within ameta-estimator and metadata routing is enabledwithenable_metadata_routing=True (seesklearn.set_config).Please check theUser Guide on how the routingmechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed topartial_fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it topartial_fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains theexisting request. This allows you to change the request for someparameters and not others.

Added in version 1.3.

Parameters:
classesstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing forclasses parameter inpartial_fit.

Returns:
selfobject

The updated object.

set_score_request(*,sample_weight:bool|None|str='$UNCHANGED$')OneVsOneClassifier[source]#

Configure whether metadata should be requested to be passed to thescore method.

Note that this method is only relevant when this estimator is used as asub-estimator within ameta-estimator and metadata routing is enabledwithenable_metadata_routing=True (seesklearn.set_config).Please check theUser Guide on how the routingmechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed toscore if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it toscore.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains theexisting request. This allows you to change the request for someparameters and not others.

Added in version 1.3.

Parameters:
sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing forsample_weight parameter inscore.

Returns:
selfobject

The updated object.

Gallery examples#

Overview of multiclass training meta-estimators

Overview of multiclass training meta-estimators