multiclass.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. """
  2. Multiclass classification strategies
  3. ====================================
  4. This module implements multiclass learning algorithms:
  5. - one-vs-the-rest / one-vs-all
  6. - one-vs-one
  7. - error correcting output codes
  8. The estimators provided in this module are meta-estimators: they require a base
  9. estimator to be provided in their constructor. For example, it is possible to
  10. use these estimators to turn a binary classifier or a regressor into a
  11. multiclass classifier. It is also possible to use these estimators with
  12. multiclass estimators in the hope that their accuracy or runtime performance
  13. improves.
  14. All classifiers in scikit-learn implement multiclass classification; you
  15. only need to use this module if you want to experiment with custom multiclass
  16. strategies.
  17. The one-vs-the-rest meta-classifier also implements a `predict_proba` method,
  18. so long as such a method is implemented by the base classifier. This method
  19. returns probabilities of class membership in both the single label and
  20. multilabel case. Note that in the multilabel case, probabilities are the
  21. marginal probability that a given sample falls in the given class. As such, in
  22. the multilabel case the sum of these probabilities over all possible labels
  23. for a given sample *will not* sum to unity, as they do in the single label
  24. case.
  25. """
  26. # Author: Mathieu Blondel <mathieu@mblondel.org>
  27. # Author: Hamzeh Alsalhi <93hamsal@gmail.com>
  28. #
  29. # License: BSD 3 clause
  30. import array
  31. import itertools
  32. import warnings
  33. from numbers import Integral, Real
  34. import numpy as np
  35. import scipy.sparse as sp
  36. from .base import (
  37. BaseEstimator,
  38. ClassifierMixin,
  39. MetaEstimatorMixin,
  40. MultiOutputMixin,
  41. _fit_context,
  42. clone,
  43. is_classifier,
  44. is_regressor,
  45. )
  46. from .metrics.pairwise import pairwise_distances_argmin
  47. from .preprocessing import LabelBinarizer
  48. from .utils import check_random_state
  49. from .utils._param_validation import HasMethods, Interval
  50. from .utils._tags import _safe_tags
  51. from .utils.metaestimators import _safe_split, available_if
  52. from .utils.multiclass import (
  53. _check_partial_fit_first_call,
  54. _ovr_decision_function,
  55. check_classification_targets,
  56. )
  57. from .utils.parallel import Parallel, delayed
  58. from .utils.validation import _num_samples, check_is_fitted
  59. __all__ = [
  60. "OneVsRestClassifier",
  61. "OneVsOneClassifier",
  62. "OutputCodeClassifier",
  63. ]
  64. def _fit_binary(estimator, X, y, classes=None):
  65. """Fit a single binary estimator."""
  66. unique_y = np.unique(y)
  67. if len(unique_y) == 1:
  68. if classes is not None:
  69. if y[0] == -1:
  70. c = 0
  71. else:
  72. c = y[0]
  73. warnings.warn(
  74. "Label %s is present in all training examples." % str(classes[c])
  75. )
  76. estimator = _ConstantPredictor().fit(X, unique_y)
  77. else:
  78. estimator = clone(estimator)
  79. estimator.fit(X, y)
  80. return estimator
  81. def _partial_fit_binary(estimator, X, y):
  82. """Partially fit a single binary estimator."""
  83. estimator.partial_fit(X, y, np.array((0, 1)))
  84. return estimator
  85. def _predict_binary(estimator, X):
  86. """Make predictions using a single binary estimator."""
  87. if is_regressor(estimator):
  88. return estimator.predict(X)
  89. try:
  90. score = np.ravel(estimator.decision_function(X))
  91. except (AttributeError, NotImplementedError):
  92. # probabilities of the positive class
  93. score = estimator.predict_proba(X)[:, 1]
  94. return score
  95. def _threshold_for_binary_predict(estimator):
  96. """Threshold for predictions from binary estimator."""
  97. if hasattr(estimator, "decision_function") and is_classifier(estimator):
  98. return 0.0
  99. else:
  100. # predict_proba threshold
  101. return 0.5
  102. class _ConstantPredictor(BaseEstimator):
  103. def fit(self, X, y):
  104. check_params = dict(
  105. force_all_finite=False, dtype=None, ensure_2d=False, accept_sparse=True
  106. )
  107. self._validate_data(
  108. X, y, reset=True, validate_separately=(check_params, check_params)
  109. )
  110. self.y_ = y
  111. return self
  112. def predict(self, X):
  113. check_is_fitted(self)
  114. self._validate_data(
  115. X,
  116. force_all_finite=False,
  117. dtype=None,
  118. accept_sparse=True,
  119. ensure_2d=False,
  120. reset=False,
  121. )
  122. return np.repeat(self.y_, _num_samples(X))
  123. def decision_function(self, X):
  124. check_is_fitted(self)
  125. self._validate_data(
  126. X,
  127. force_all_finite=False,
  128. dtype=None,
  129. accept_sparse=True,
  130. ensure_2d=False,
  131. reset=False,
  132. )
  133. return np.repeat(self.y_, _num_samples(X))
  134. def predict_proba(self, X):
  135. check_is_fitted(self)
  136. self._validate_data(
  137. X,
  138. force_all_finite=False,
  139. dtype=None,
  140. accept_sparse=True,
  141. ensure_2d=False,
  142. reset=False,
  143. )
  144. y_ = self.y_.astype(np.float64)
  145. return np.repeat([np.hstack([1 - y_, y_])], _num_samples(X), axis=0)
  146. def _estimators_has(attr):
  147. """Check if self.estimator or self.estimators_[0] has attr.
  148. If `self.estimators_[0]` has the attr, then its safe to assume that other
  149. values has it too. This function is used together with `avaliable_if`.
  150. """
  151. return lambda self: (
  152. hasattr(self.estimator, attr)
  153. or (hasattr(self, "estimators_") and hasattr(self.estimators_[0], attr))
  154. )
  155. class OneVsRestClassifier(
  156. MultiOutputMixin, ClassifierMixin, MetaEstimatorMixin, BaseEstimator
  157. ):
  158. """One-vs-the-rest (OvR) multiclass strategy.
  159. Also known as one-vs-all, this strategy consists in fitting one classifier
  160. per class. For each classifier, the class is fitted against all the other
  161. classes. In addition to its computational efficiency (only `n_classes`
  162. classifiers are needed), one advantage of this approach is its
  163. interpretability. Since each class is represented by one and one classifier
  164. only, it is possible to gain knowledge about the class by inspecting its
  165. corresponding classifier. This is the most commonly used strategy for
  166. multiclass classification and is a fair default choice.
  167. OneVsRestClassifier can also be used for multilabel classification. To use
  168. this feature, provide an indicator matrix for the target `y` when calling
  169. `.fit`. In other words, the target labels should be formatted as a 2D
  170. binary (0/1) matrix, where [i, j] == 1 indicates the presence of label j
  171. in sample i. This estimator uses the binary relevance method to perform
  172. multilabel classification, which involves training one binary classifier
  173. independently for each label.
  174. Read more in the :ref:`User Guide <ovr_classification>`.
  175. Parameters
  176. ----------
  177. estimator : estimator object
  178. A regressor or a classifier that implements :term:`fit`.
  179. When a classifier is passed, :term:`decision_function` will be used
  180. in priority and it will fallback to :term:`predict_proba` if it is not
  181. available.
  182. When a regressor is passed, :term:`predict` is used.
  183. n_jobs : int, default=None
  184. The number of jobs to use for the computation: the `n_classes`
  185. one-vs-rest problems are computed in parallel.
  186. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  187. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  188. for more details.
  189. .. versionchanged:: 0.20
  190. `n_jobs` default changed from 1 to None
  191. verbose : int, default=0
  192. The verbosity level, if non zero, progress messages are printed.
  193. Below 50, the output is sent to stderr. Otherwise, the output is sent
  194. to stdout. The frequency of the messages increases with the verbosity
  195. level, reporting all iterations at 10. See :class:`joblib.Parallel` for
  196. more details.
  197. .. versionadded:: 1.1
  198. Attributes
  199. ----------
  200. estimators_ : list of `n_classes` estimators
  201. Estimators used for predictions.
  202. classes_ : array, shape = [`n_classes`]
  203. Class labels.
  204. n_classes_ : int
  205. Number of classes.
  206. label_binarizer_ : LabelBinarizer object
  207. Object used to transform multiclass labels to binary labels and
  208. vice-versa.
  209. multilabel_ : boolean
  210. Whether a OneVsRestClassifier is a multilabel classifier.
  211. n_features_in_ : int
  212. Number of features seen during :term:`fit`. Only defined if the
  213. underlying estimator exposes such an attribute when fit.
  214. .. versionadded:: 0.24
  215. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  216. Names of features seen during :term:`fit`. Only defined if the
  217. underlying estimator exposes such an attribute when fit.
  218. .. versionadded:: 1.0
  219. See Also
  220. --------
  221. OneVsOneClassifier : One-vs-one multiclass strategy.
  222. OutputCodeClassifier : (Error-Correcting) Output-Code multiclass strategy.
  223. sklearn.multioutput.MultiOutputClassifier : Alternate way of extending an
  224. estimator for multilabel classification.
  225. sklearn.preprocessing.MultiLabelBinarizer : Transform iterable of iterables
  226. to binary indicator matrix.
  227. Examples
  228. --------
  229. >>> import numpy as np
  230. >>> from sklearn.multiclass import OneVsRestClassifier
  231. >>> from sklearn.svm import SVC
  232. >>> X = np.array([
  233. ... [10, 10],
  234. ... [8, 10],
  235. ... [-5, 5.5],
  236. ... [-5.4, 5.5],
  237. ... [-20, -20],
  238. ... [-15, -20]
  239. ... ])
  240. >>> y = np.array([0, 0, 1, 1, 2, 2])
  241. >>> clf = OneVsRestClassifier(SVC()).fit(X, y)
  242. >>> clf.predict([[-19, -20], [9, 9], [-5, 5]])
  243. array([2, 0, 1])
  244. """
  245. _parameter_constraints = {
  246. "estimator": [HasMethods(["fit"])],
  247. "n_jobs": [Integral, None],
  248. "verbose": ["verbose"],
  249. }
  250. def __init__(self, estimator, *, n_jobs=None, verbose=0):
  251. self.estimator = estimator
  252. self.n_jobs = n_jobs
  253. self.verbose = verbose
  254. @_fit_context(
  255. # OneVsRestClassifier.estimator is not validated yet
  256. prefer_skip_nested_validation=False
  257. )
  258. def fit(self, X, y):
  259. """Fit underlying estimators.
  260. Parameters
  261. ----------
  262. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  263. Data.
  264. y : {array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_classes)
  265. Multi-class targets. An indicator matrix turns on multilabel
  266. classification.
  267. Returns
  268. -------
  269. self : object
  270. Instance of fitted estimator.
  271. """
  272. # A sparse LabelBinarizer, with sparse_output=True, has been shown to
  273. # outperform or match a dense label binarizer in all cases and has also
  274. # resulted in less or equal memory consumption in the fit_ovr function
  275. # overall.
  276. self.label_binarizer_ = LabelBinarizer(sparse_output=True)
  277. Y = self.label_binarizer_.fit_transform(y)
  278. Y = Y.tocsc()
  279. self.classes_ = self.label_binarizer_.classes_
  280. columns = (col.toarray().ravel() for col in Y.T)
  281. # In cases where individual estimators are very fast to train setting
  282. # n_jobs > 1 in can results in slower performance due to the overhead
  283. # of spawning threads. See joblib issue #112.
  284. self.estimators_ = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)(
  285. delayed(_fit_binary)(
  286. self.estimator,
  287. X,
  288. column,
  289. classes=[
  290. "not %s" % self.label_binarizer_.classes_[i],
  291. self.label_binarizer_.classes_[i],
  292. ],
  293. )
  294. for i, column in enumerate(columns)
  295. )
  296. if hasattr(self.estimators_[0], "n_features_in_"):
  297. self.n_features_in_ = self.estimators_[0].n_features_in_
  298. if hasattr(self.estimators_[0], "feature_names_in_"):
  299. self.feature_names_in_ = self.estimators_[0].feature_names_in_
  300. return self
  301. @available_if(_estimators_has("partial_fit"))
  302. @_fit_context(
  303. # OneVsRestClassifier.estimator is not validated yet
  304. prefer_skip_nested_validation=False
  305. )
  306. def partial_fit(self, X, y, classes=None):
  307. """Partially fit underlying estimators.
  308. Should be used when memory is inefficient to train all data.
  309. Chunks of data can be passed in several iteration.
  310. Parameters
  311. ----------
  312. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  313. Data.
  314. y : {array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_classes)
  315. Multi-class targets. An indicator matrix turns on multilabel
  316. classification.
  317. classes : array, shape (n_classes, )
  318. Classes across all calls to partial_fit.
  319. Can be obtained via `np.unique(y_all)`, where y_all is the
  320. target vector of the entire dataset.
  321. This argument is only required in the first call of partial_fit
  322. and can be omitted in the subsequent calls.
  323. Returns
  324. -------
  325. self : object
  326. Instance of partially fitted estimator.
  327. """
  328. if _check_partial_fit_first_call(self, classes):
  329. if not hasattr(self.estimator, "partial_fit"):
  330. raise ValueError(
  331. ("Base estimator {0}, doesn't have partial_fit method").format(
  332. self.estimator
  333. )
  334. )
  335. self.estimators_ = [clone(self.estimator) for _ in range(self.n_classes_)]
  336. # A sparse LabelBinarizer, with sparse_output=True, has been
  337. # shown to outperform or match a dense label binarizer in all
  338. # cases and has also resulted in less or equal memory consumption
  339. # in the fit_ovr function overall.
  340. self.label_binarizer_ = LabelBinarizer(sparse_output=True)
  341. self.label_binarizer_.fit(self.classes_)
  342. if len(np.setdiff1d(y, self.classes_)):
  343. raise ValueError(
  344. (
  345. "Mini-batch contains {0} while classes " + "must be subset of {1}"
  346. ).format(np.unique(y), self.classes_)
  347. )
  348. Y = self.label_binarizer_.transform(y)
  349. Y = Y.tocsc()
  350. columns = (col.toarray().ravel() for col in Y.T)
  351. self.estimators_ = Parallel(n_jobs=self.n_jobs)(
  352. delayed(_partial_fit_binary)(estimator, X, column)
  353. for estimator, column in zip(self.estimators_, columns)
  354. )
  355. if hasattr(self.estimators_[0], "n_features_in_"):
  356. self.n_features_in_ = self.estimators_[0].n_features_in_
  357. return self
  358. def predict(self, X):
  359. """Predict multi-class targets using underlying estimators.
  360. Parameters
  361. ----------
  362. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  363. Data.
  364. Returns
  365. -------
  366. y : {array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_classes)
  367. Predicted multi-class targets.
  368. """
  369. check_is_fitted(self)
  370. n_samples = _num_samples(X)
  371. if self.label_binarizer_.y_type_ == "multiclass":
  372. maxima = np.empty(n_samples, dtype=float)
  373. maxima.fill(-np.inf)
  374. argmaxima = np.zeros(n_samples, dtype=int)
  375. for i, e in enumerate(self.estimators_):
  376. pred = _predict_binary(e, X)
  377. np.maximum(maxima, pred, out=maxima)
  378. argmaxima[maxima == pred] = i
  379. return self.classes_[argmaxima]
  380. else:
  381. thresh = _threshold_for_binary_predict(self.estimators_[0])
  382. indices = array.array("i")
  383. indptr = array.array("i", [0])
  384. for e in self.estimators_:
  385. indices.extend(np.where(_predict_binary(e, X) > thresh)[0])
  386. indptr.append(len(indices))
  387. data = np.ones(len(indices), dtype=int)
  388. indicator = sp.csc_matrix(
  389. (data, indices, indptr), shape=(n_samples, len(self.estimators_))
  390. )
  391. return self.label_binarizer_.inverse_transform(indicator)
  392. @available_if(_estimators_has("predict_proba"))
  393. def predict_proba(self, X):
  394. """Probability estimates.
  395. The returned estimates for all classes are ordered by label of classes.
  396. Note that in the multilabel case, each sample can have any number of
  397. labels. This returns the marginal probability that the given sample has
  398. the label in question. For example, it is entirely consistent that two
  399. labels both have a 90% probability of applying to a given sample.
  400. In the single label multiclass case, the rows of the returned matrix
  401. sum to 1.
  402. Parameters
  403. ----------
  404. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  405. Input data.
  406. Returns
  407. -------
  408. T : array-like of shape (n_samples, n_classes)
  409. Returns the probability of the sample for each class in the model,
  410. where classes are ordered as they are in `self.classes_`.
  411. """
  412. check_is_fitted(self)
  413. # Y[i, j] gives the probability that sample i has the label j.
  414. # In the multi-label case, these are not disjoint.
  415. Y = np.array([e.predict_proba(X)[:, 1] for e in self.estimators_]).T
  416. if len(self.estimators_) == 1:
  417. # Only one estimator, but we still want to return probabilities
  418. # for two classes.
  419. Y = np.concatenate(((1 - Y), Y), axis=1)
  420. if not self.multilabel_:
  421. # Then, probabilities should be normalized to 1.
  422. Y /= np.sum(Y, axis=1)[:, np.newaxis]
  423. return Y
  424. @available_if(_estimators_has("decision_function"))
  425. def decision_function(self, X):
  426. """Decision function for the OneVsRestClassifier.
  427. Return the distance of each sample from the decision boundary for each
  428. class. This can only be used with estimators which implement the
  429. `decision_function` method.
  430. Parameters
  431. ----------
  432. X : array-like of shape (n_samples, n_features)
  433. Input data.
  434. Returns
  435. -------
  436. T : array-like of shape (n_samples, n_classes) or (n_samples,) for \
  437. binary classification.
  438. Result of calling `decision_function` on the final estimator.
  439. .. versionchanged:: 0.19
  440. output shape changed to ``(n_samples,)`` to conform to
  441. scikit-learn conventions for binary classification.
  442. """
  443. check_is_fitted(self)
  444. if len(self.estimators_) == 1:
  445. return self.estimators_[0].decision_function(X)
  446. return np.array(
  447. [est.decision_function(X).ravel() for est in self.estimators_]
  448. ).T
  449. @property
  450. def multilabel_(self):
  451. """Whether this is a multilabel classifier."""
  452. return self.label_binarizer_.y_type_.startswith("multilabel")
  453. @property
  454. def n_classes_(self):
  455. """Number of classes."""
  456. return len(self.classes_)
  457. def _more_tags(self):
  458. """Indicate if wrapped estimator is using a precomputed Gram matrix"""
  459. return {"pairwise": _safe_tags(self.estimator, key="pairwise")}
  460. def _fit_ovo_binary(estimator, X, y, i, j):
  461. """Fit a single binary estimator (one-vs-one)."""
  462. cond = np.logical_or(y == i, y == j)
  463. y = y[cond]
  464. y_binary = np.empty(y.shape, int)
  465. y_binary[y == i] = 0
  466. y_binary[y == j] = 1
  467. indcond = np.arange(_num_samples(X))[cond]
  468. return (
  469. _fit_binary(
  470. estimator,
  471. _safe_split(estimator, X, None, indices=indcond)[0],
  472. y_binary,
  473. classes=[i, j],
  474. ),
  475. indcond,
  476. )
  477. def _partial_fit_ovo_binary(estimator, X, y, i, j):
  478. """Partially fit a single binary estimator(one-vs-one)."""
  479. cond = np.logical_or(y == i, y == j)
  480. y = y[cond]
  481. if len(y) != 0:
  482. y_binary = np.zeros_like(y)
  483. y_binary[y == j] = 1
  484. return _partial_fit_binary(estimator, X[cond], y_binary)
  485. return estimator
  486. class OneVsOneClassifier(MetaEstimatorMixin, ClassifierMixin, BaseEstimator):
  487. """One-vs-one multiclass strategy.
  488. This strategy consists in fitting one classifier per class pair.
  489. At prediction time, the class which received the most votes is selected.
  490. Since it requires to fit `n_classes * (n_classes - 1) / 2` classifiers,
  491. this method is usually slower than one-vs-the-rest, due to its
  492. O(n_classes^2) complexity. However, this method may be advantageous for
  493. algorithms such as kernel algorithms which don't scale well with
  494. `n_samples`. This is because each individual learning problem only involves
  495. a small subset of the data whereas, with one-vs-the-rest, the complete
  496. dataset is used `n_classes` times.
  497. Read more in the :ref:`User Guide <ovo_classification>`.
  498. Parameters
  499. ----------
  500. estimator : estimator object
  501. A regressor or a classifier that implements :term:`fit`.
  502. When a classifier is passed, :term:`decision_function` will be used
  503. in priority and it will fallback to :term:`predict_proba` if it is not
  504. available.
  505. When a regressor is passed, :term:`predict` is used.
  506. n_jobs : int, default=None
  507. The number of jobs to use for the computation: the `n_classes * (
  508. n_classes - 1) / 2` OVO problems are computed in parallel.
  509. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  510. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  511. for more details.
  512. Attributes
  513. ----------
  514. estimators_ : list of ``n_classes * (n_classes - 1) / 2`` estimators
  515. Estimators used for predictions.
  516. classes_ : numpy array of shape [n_classes]
  517. Array containing labels.
  518. n_classes_ : int
  519. Number of classes.
  520. pairwise_indices_ : list, length = ``len(estimators_)``, or ``None``
  521. Indices of samples used when training the estimators.
  522. ``None`` when ``estimator``'s `pairwise` tag is False.
  523. n_features_in_ : int
  524. Number of features seen during :term:`fit`.
  525. .. versionadded:: 0.24
  526. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  527. Names of features seen during :term:`fit`. Defined only when `X`
  528. has feature names that are all strings.
  529. .. versionadded:: 1.0
  530. See Also
  531. --------
  532. OneVsRestClassifier : One-vs-all multiclass strategy.
  533. OutputCodeClassifier : (Error-Correcting) Output-Code multiclass strategy.
  534. Examples
  535. --------
  536. >>> from sklearn.datasets import load_iris
  537. >>> from sklearn.model_selection import train_test_split
  538. >>> from sklearn.multiclass import OneVsOneClassifier
  539. >>> from sklearn.svm import LinearSVC
  540. >>> X, y = load_iris(return_X_y=True)
  541. >>> X_train, X_test, y_train, y_test = train_test_split(
  542. ... X, y, test_size=0.33, shuffle=True, random_state=0)
  543. >>> clf = OneVsOneClassifier(
  544. ... LinearSVC(dual="auto", random_state=0)).fit(X_train, y_train)
  545. >>> clf.predict(X_test[:10])
  546. array([2, 1, 0, 2, 0, 2, 0, 1, 1, 1])
  547. """
  548. _parameter_constraints: dict = {
  549. "estimator": [HasMethods(["fit"])],
  550. "n_jobs": [Integral, None],
  551. }
  552. def __init__(self, estimator, *, n_jobs=None):
  553. self.estimator = estimator
  554. self.n_jobs = n_jobs
  555. @_fit_context(
  556. # OneVsOneClassifier.estimator is not validated yet
  557. prefer_skip_nested_validation=False
  558. )
  559. def fit(self, X, y):
  560. """Fit underlying estimators.
  561. Parameters
  562. ----------
  563. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  564. Data.
  565. y : array-like of shape (n_samples,)
  566. Multi-class targets.
  567. Returns
  568. -------
  569. self : object
  570. The fitted underlying estimator.
  571. """
  572. # We need to validate the data because we do a safe_indexing later.
  573. X, y = self._validate_data(
  574. X, y, accept_sparse=["csr", "csc"], force_all_finite=False
  575. )
  576. check_classification_targets(y)
  577. self.classes_ = np.unique(y)
  578. if len(self.classes_) == 1:
  579. raise ValueError(
  580. "OneVsOneClassifier can not be fit when only one class is present."
  581. )
  582. n_classes = self.classes_.shape[0]
  583. estimators_indices = list(
  584. zip(
  585. *(
  586. Parallel(n_jobs=self.n_jobs)(
  587. delayed(_fit_ovo_binary)(
  588. self.estimator, X, y, self.classes_[i], self.classes_[j]
  589. )
  590. for i in range(n_classes)
  591. for j in range(i + 1, n_classes)
  592. )
  593. )
  594. )
  595. )
  596. self.estimators_ = estimators_indices[0]
  597. pairwise = self._get_tags()["pairwise"]
  598. self.pairwise_indices_ = estimators_indices[1] if pairwise else None
  599. return self
  600. @available_if(_estimators_has("partial_fit"))
  601. @_fit_context(
  602. # OneVsOneClassifier.estimator is not validated yet
  603. prefer_skip_nested_validation=False
  604. )
  605. def partial_fit(self, X, y, classes=None):
  606. """Partially fit underlying estimators.
  607. Should be used when memory is inefficient to train all data. Chunks
  608. of data can be passed in several iteration, where the first call
  609. should have an array of all target variables.
  610. Parameters
  611. ----------
  612. X : {array-like, sparse matrix) of shape (n_samples, n_features)
  613. Data.
  614. y : array-like of shape (n_samples,)
  615. Multi-class targets.
  616. classes : array, shape (n_classes, )
  617. Classes across all calls to partial_fit.
  618. Can be obtained via `np.unique(y_all)`, where y_all is the
  619. target vector of the entire dataset.
  620. This argument is only required in the first call of partial_fit
  621. and can be omitted in the subsequent calls.
  622. Returns
  623. -------
  624. self : object
  625. The partially fitted underlying estimator.
  626. """
  627. first_call = _check_partial_fit_first_call(self, classes)
  628. if first_call:
  629. self.estimators_ = [
  630. clone(self.estimator)
  631. for _ in range(self.n_classes_ * (self.n_classes_ - 1) // 2)
  632. ]
  633. if len(np.setdiff1d(y, self.classes_)):
  634. raise ValueError(
  635. "Mini-batch contains {0} while it must be subset of {1}".format(
  636. np.unique(y), self.classes_
  637. )
  638. )
  639. X, y = self._validate_data(
  640. X,
  641. y,
  642. accept_sparse=["csr", "csc"],
  643. force_all_finite=False,
  644. reset=first_call,
  645. )
  646. check_classification_targets(y)
  647. combinations = itertools.combinations(range(self.n_classes_), 2)
  648. self.estimators_ = Parallel(n_jobs=self.n_jobs)(
  649. delayed(_partial_fit_ovo_binary)(
  650. estimator, X, y, self.classes_[i], self.classes_[j]
  651. )
  652. for estimator, (i, j) in zip(self.estimators_, (combinations))
  653. )
  654. self.pairwise_indices_ = None
  655. if hasattr(self.estimators_[0], "n_features_in_"):
  656. self.n_features_in_ = self.estimators_[0].n_features_in_
  657. return self
  658. def predict(self, X):
  659. """Estimate the best class label for each sample in X.
  660. This is implemented as ``argmax(decision_function(X), axis=1)`` which
  661. will return the label of the class with most votes by estimators
  662. predicting the outcome of a decision for each possible class pair.
  663. Parameters
  664. ----------
  665. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  666. Data.
  667. Returns
  668. -------
  669. y : numpy array of shape [n_samples]
  670. Predicted multi-class targets.
  671. """
  672. Y = self.decision_function(X)
  673. if self.n_classes_ == 2:
  674. thresh = _threshold_for_binary_predict(self.estimators_[0])
  675. return self.classes_[(Y > thresh).astype(int)]
  676. return self.classes_[Y.argmax(axis=1)]
  677. def decision_function(self, X):
  678. """Decision function for the OneVsOneClassifier.
  679. The decision values for the samples are computed by adding the
  680. normalized sum of pair-wise classification confidence levels to the
  681. votes in order to disambiguate between the decision values when the
  682. votes for all the classes are equal leading to a tie.
  683. Parameters
  684. ----------
  685. X : array-like of shape (n_samples, n_features)
  686. Input data.
  687. Returns
  688. -------
  689. Y : array-like of shape (n_samples, n_classes) or (n_samples,)
  690. Result of calling `decision_function` on the final estimator.
  691. .. versionchanged:: 0.19
  692. output shape changed to ``(n_samples,)`` to conform to
  693. scikit-learn conventions for binary classification.
  694. """
  695. check_is_fitted(self)
  696. X = self._validate_data(
  697. X,
  698. accept_sparse=True,
  699. force_all_finite=False,
  700. reset=False,
  701. )
  702. indices = self.pairwise_indices_
  703. if indices is None:
  704. Xs = [X] * len(self.estimators_)
  705. else:
  706. Xs = [X[:, idx] for idx in indices]
  707. predictions = np.vstack(
  708. [est.predict(Xi) for est, Xi in zip(self.estimators_, Xs)]
  709. ).T
  710. confidences = np.vstack(
  711. [_predict_binary(est, Xi) for est, Xi in zip(self.estimators_, Xs)]
  712. ).T
  713. Y = _ovr_decision_function(predictions, confidences, len(self.classes_))
  714. if self.n_classes_ == 2:
  715. return Y[:, 1]
  716. return Y
  717. @property
  718. def n_classes_(self):
  719. """Number of classes."""
  720. return len(self.classes_)
  721. def _more_tags(self):
  722. """Indicate if wrapped estimator is using a precomputed Gram matrix"""
  723. return {"pairwise": _safe_tags(self.estimator, key="pairwise")}
  724. class OutputCodeClassifier(MetaEstimatorMixin, ClassifierMixin, BaseEstimator):
  725. """(Error-Correcting) Output-Code multiclass strategy.
  726. Output-code based strategies consist in representing each class with a
  727. binary code (an array of 0s and 1s). At fitting time, one binary
  728. classifier per bit in the code book is fitted. At prediction time, the
  729. classifiers are used to project new points in the class space and the class
  730. closest to the points is chosen. The main advantage of these strategies is
  731. that the number of classifiers used can be controlled by the user, either
  732. for compressing the model (0 < `code_size` < 1) or for making the model more
  733. robust to errors (`code_size` > 1). See the documentation for more details.
  734. Read more in the :ref:`User Guide <ecoc>`.
  735. Parameters
  736. ----------
  737. estimator : estimator object
  738. An estimator object implementing :term:`fit` and one of
  739. :term:`decision_function` or :term:`predict_proba`.
  740. code_size : float, default=1.5
  741. Percentage of the number of classes to be used to create the code book.
  742. A number between 0 and 1 will require fewer classifiers than
  743. one-vs-the-rest. A number greater than 1 will require more classifiers
  744. than one-vs-the-rest.
  745. random_state : int, RandomState instance, default=None
  746. The generator used to initialize the codebook.
  747. Pass an int for reproducible output across multiple function calls.
  748. See :term:`Glossary <random_state>`.
  749. n_jobs : int, default=None
  750. The number of jobs to use for the computation: the multiclass problems
  751. are computed in parallel.
  752. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  753. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  754. for more details.
  755. Attributes
  756. ----------
  757. estimators_ : list of `int(n_classes * code_size)` estimators
  758. Estimators used for predictions.
  759. classes_ : ndarray of shape (n_classes,)
  760. Array containing labels.
  761. code_book_ : ndarray of shape (n_classes, code_size)
  762. Binary array containing the code of each class.
  763. n_features_in_ : int
  764. Number of features seen during :term:`fit`. Only defined if the
  765. underlying estimator exposes such an attribute when fit.
  766. .. versionadded:: 0.24
  767. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  768. Names of features seen during :term:`fit`. Only defined if the
  769. underlying estimator exposes such an attribute when fit.
  770. .. versionadded:: 1.0
  771. See Also
  772. --------
  773. OneVsRestClassifier : One-vs-all multiclass strategy.
  774. OneVsOneClassifier : One-vs-one multiclass strategy.
  775. References
  776. ----------
  777. .. [1] "Solving multiclass learning problems via error-correcting output
  778. codes",
  779. Dietterich T., Bakiri G.,
  780. Journal of Artificial Intelligence Research 2,
  781. 1995.
  782. .. [2] "The error coding method and PICTs",
  783. James G., Hastie T.,
  784. Journal of Computational and Graphical statistics 7,
  785. 1998.
  786. .. [3] "The Elements of Statistical Learning",
  787. Hastie T., Tibshirani R., Friedman J., page 606 (second-edition)
  788. 2008.
  789. Examples
  790. --------
  791. >>> from sklearn.multiclass import OutputCodeClassifier
  792. >>> from sklearn.ensemble import RandomForestClassifier
  793. >>> from sklearn.datasets import make_classification
  794. >>> X, y = make_classification(n_samples=100, n_features=4,
  795. ... n_informative=2, n_redundant=0,
  796. ... random_state=0, shuffle=False)
  797. >>> clf = OutputCodeClassifier(
  798. ... estimator=RandomForestClassifier(random_state=0),
  799. ... random_state=0).fit(X, y)
  800. >>> clf.predict([[0, 0, 0, 0]])
  801. array([1])
  802. """
  803. _parameter_constraints: dict = {
  804. "estimator": [
  805. HasMethods(["fit", "decision_function"]),
  806. HasMethods(["fit", "predict_proba"]),
  807. ],
  808. "code_size": [Interval(Real, 0.0, None, closed="neither")],
  809. "random_state": ["random_state"],
  810. "n_jobs": [Integral, None],
  811. }
  812. def __init__(self, estimator, *, code_size=1.5, random_state=None, n_jobs=None):
  813. self.estimator = estimator
  814. self.code_size = code_size
  815. self.random_state = random_state
  816. self.n_jobs = n_jobs
  817. @_fit_context(
  818. # OutputCodeClassifier.estimator is not validated yet
  819. prefer_skip_nested_validation=False
  820. )
  821. def fit(self, X, y):
  822. """Fit underlying estimators.
  823. Parameters
  824. ----------
  825. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  826. Data.
  827. y : array-like of shape (n_samples,)
  828. Multi-class targets.
  829. Returns
  830. -------
  831. self : object
  832. Returns a fitted instance of self.
  833. """
  834. y = self._validate_data(X="no_validation", y=y)
  835. random_state = check_random_state(self.random_state)
  836. check_classification_targets(y)
  837. self.classes_ = np.unique(y)
  838. n_classes = self.classes_.shape[0]
  839. if n_classes == 0:
  840. raise ValueError(
  841. "OutputCodeClassifier can not be fit when no class is present."
  842. )
  843. code_size_ = int(n_classes * self.code_size)
  844. # FIXME: there are more elaborate methods than generating the codebook
  845. # randomly.
  846. self.code_book_ = random_state.uniform(size=(n_classes, code_size_))
  847. self.code_book_[self.code_book_ > 0.5] = 1.0
  848. if hasattr(self.estimator, "decision_function"):
  849. self.code_book_[self.code_book_ != 1] = -1.0
  850. else:
  851. self.code_book_[self.code_book_ != 1] = 0.0
  852. classes_index = {c: i for i, c in enumerate(self.classes_)}
  853. Y = np.array(
  854. [self.code_book_[classes_index[y[i]]] for i in range(_num_samples(y))],
  855. dtype=int,
  856. )
  857. self.estimators_ = Parallel(n_jobs=self.n_jobs)(
  858. delayed(_fit_binary)(self.estimator, X, Y[:, i]) for i in range(Y.shape[1])
  859. )
  860. if hasattr(self.estimators_[0], "n_features_in_"):
  861. self.n_features_in_ = self.estimators_[0].n_features_in_
  862. if hasattr(self.estimators_[0], "feature_names_in_"):
  863. self.feature_names_in_ = self.estimators_[0].feature_names_in_
  864. return self
  865. def predict(self, X):
  866. """Predict multi-class targets using underlying estimators.
  867. Parameters
  868. ----------
  869. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  870. Data.
  871. Returns
  872. -------
  873. y : ndarray of shape (n_samples,)
  874. Predicted multi-class targets.
  875. """
  876. check_is_fitted(self)
  877. # ArgKmin only accepts C-contiguous array. The aggregated predictions need to be
  878. # transposed. We therefore create a F-contiguous array to avoid a copy and have
  879. # a C-contiguous array after the transpose operation.
  880. Y = np.array(
  881. [_predict_binary(e, X) for e in self.estimators_],
  882. order="F",
  883. dtype=np.float64,
  884. ).T
  885. pred = pairwise_distances_argmin(Y, self.code_book_, metric="euclidean")
  886. return self.classes_[pred]