You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

774 lines
28 KiB

4 years ago
  1. """
  2. Multiclass and multilabel 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 numpy as np
  32. import warnings
  33. import scipy.sparse as sp
  34. import itertools
  35. from .base import BaseEstimator, ClassifierMixin, clone, is_classifier
  36. from .base import MetaEstimatorMixin, is_regressor
  37. from .preprocessing import LabelBinarizer
  38. from .metrics.pairwise import euclidean_distances
  39. from .utils import check_random_state
  40. from .utils.validation import _num_samples
  41. from .utils.validation import check_is_fitted
  42. from .utils.validation import check_X_y, check_array
  43. from .utils.multiclass import (_check_partial_fit_first_call,
  44. check_classification_targets,
  45. _ovr_decision_function)
  46. from .utils.metaestimators import _safe_split, if_delegate_has_method
  47. from .utils import Parallel
  48. from .utils import delayed
  49. from .externals.six.moves import zip as izip
  50. __all__ = [
  51. "OneVsRestClassifier",
  52. "OneVsOneClassifier",
  53. "OutputCodeClassifier",
  54. ]
  55. def _fit_binary(estimator, X, y, classes=None):
  56. """Fit a single binary estimator."""
  57. unique_y = np.unique(y)
  58. if len(unique_y) == 1:
  59. if classes is not None:
  60. if y[0] == -1:
  61. c = 0
  62. else:
  63. c = y[0]
  64. warnings.warn("Label %s is present in all training examples." %
  65. str(classes[c]))
  66. estimator = _ConstantPredictor().fit(X, unique_y)
  67. else:
  68. estimator = clone(estimator)
  69. estimator.fit(X, y)
  70. return estimator
  71. def _partial_fit_binary(estimator, X, y):
  72. """Partially fit a single binary estimator."""
  73. estimator.partial_fit(X, y, np.array((0, 1)))
  74. return estimator
  75. def _predict_binary(estimator, X):
  76. """Make predictions using a single binary estimator."""
  77. if is_regressor(estimator):
  78. return estimator.predict(X)
  79. try:
  80. score = np.ravel(estimator.decision_function(X))
  81. except (AttributeError, NotImplementedError):
  82. # probabilities of the positive class
  83. score = estimator.predict_proba(X)[:, 1]
  84. return score
  85. def _check_estimator(estimator):
  86. """Make sure that an estimator implements the necessary methods."""
  87. if (not hasattr(estimator, "decision_function") and
  88. not hasattr(estimator, "predict_proba")):
  89. raise ValueError("The base estimator should implement "
  90. "decision_function or predict_proba!")
  91. class _ConstantPredictor(BaseEstimator):
  92. def fit(self, X, y):
  93. self.y_ = y
  94. return self
  95. def predict(self, X):
  96. check_is_fitted(self, 'y_')
  97. return np.repeat(self.y_, X.shape[0])
  98. def decision_function(self, X):
  99. check_is_fitted(self, 'y_')
  100. return np.repeat(self.y_, X.shape[0])
  101. def predict_proba(self, X):
  102. check_is_fitted(self, 'y_')
  103. return np.repeat([np.hstack([1 - self.y_, self.y_])],
  104. X.shape[0], axis=0)
  105. class OneVsRestClassifier(BaseEstimator, ClassifierMixin, MetaEstimatorMixin):
  106. """One-vs-the-rest (OvR) multiclass/multilabel strategy
  107. Also known as one-vs-all, this strategy consists in fitting one classifier
  108. per class. For each classifier, the class is fitted against all the other
  109. classes. In addition to its computational efficiency (only `n_classes`
  110. classifiers are needed), one advantage of this approach is its
  111. interpretability. Since each class is represented by one and one classifier
  112. only, it is possible to gain knowledge about the class by inspecting its
  113. corresponding classifier. This is the most commonly used strategy for
  114. multiclass classification and is a fair default choice.
  115. This strategy can also be used for multilabel learning, where a classifier
  116. is used to predict multiple labels for instance, by fitting on a 2-d matrix
  117. in which cell [i, j] is 1 if sample i has label j and 0 otherwise.
  118. In the multilabel learning literature, OvR is also known as the binary
  119. relevance method.
  120. Read more in the :ref:`User Guide <ovr_classification>`.
  121. Parameters
  122. ----------
  123. estimator : estimator object
  124. An estimator object implementing `fit` and one of `decision_function`
  125. or `predict_proba`.
  126. n_jobs : int or None, optional (default=None)
  127. The number of jobs to use for the computation.
  128. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  129. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  130. for more details.
  131. Attributes
  132. ----------
  133. estimators_ : list of `n_classes` estimators
  134. Estimators used for predictions.
  135. classes_ : array, shape = [`n_classes`]
  136. Class labels.
  137. label_binarizer_ : LabelBinarizer object
  138. Object used to transform multiclass labels to binary labels and
  139. vice-versa.
  140. multilabel_ : boolean
  141. Whether a OneVsRestClassifier is a multilabel classifier.
  142. """
  143. def __init__(self, estimator, n_jobs=None):
  144. self.estimator = estimator
  145. self.n_jobs = n_jobs
  146. def fit(self, X, y):
  147. """Fit underlying estimators.
  148. Parameters
  149. ----------
  150. X : (sparse) array-like, shape = [n_samples, n_features]
  151. Data.
  152. y : (sparse) array-like, shape = [n_samples, ], [n_samples, n_classes]
  153. Multi-class targets. An indicator matrix turns on multilabel
  154. classification.
  155. Returns
  156. -------
  157. self
  158. """
  159. # A sparse LabelBinarizer, with sparse_output=True, has been shown to
  160. # outperform or match a dense label binarizer in all cases and has also
  161. # resulted in less or equal memory consumption in the fit_ovr function
  162. # overall.
  163. self.label_binarizer_ = LabelBinarizer(sparse_output=True)
  164. Y = self.label_binarizer_.fit_transform(y)
  165. Y = Y.tocsc()
  166. self.classes_ = self.label_binarizer_.classes_
  167. columns = (col.toarray().ravel() for col in Y.T)
  168. # In cases where individual estimators are very fast to train setting
  169. # n_jobs > 1 in can results in slower performance due to the overhead
  170. # of spawning threads. See joblib issue #112.
  171. self.estimators_ = Parallel(n_jobs=self.n_jobs)(delayed(_fit_binary)(
  172. self.estimator, X, column, classes=[
  173. "not %s" % self.label_binarizer_.classes_[i],
  174. self.label_binarizer_.classes_[i]])
  175. for i, column in enumerate(columns))
  176. return self
  177. @if_delegate_has_method('estimator')
  178. def partial_fit(self, X, y, classes=None):
  179. """Partially fit underlying estimators
  180. Should be used when memory is inefficient to train all data.
  181. Chunks of data can be passed in several iteration.
  182. Parameters
  183. ----------
  184. X : (sparse) array-like, shape = [n_samples, n_features]
  185. Data.
  186. y : (sparse) array-like, shape = [n_samples, ], [n_samples, n_classes]
  187. Multi-class targets. An indicator matrix turns on multilabel
  188. classification.
  189. classes : array, shape (n_classes, )
  190. Classes across all calls to partial_fit.
  191. Can be obtained via `np.unique(y_all)`, where y_all is the
  192. target vector of the entire dataset.
  193. This argument is only required in the first call of partial_fit
  194. and can be omitted in the subsequent calls.
  195. Returns
  196. -------
  197. self
  198. """
  199. if _check_partial_fit_first_call(self, classes):
  200. if not hasattr(self.estimator, "partial_fit"):
  201. raise ValueError(("Base estimator {0}, doesn't have "
  202. "partial_fit method").format(self.estimator))
  203. self.estimators_ = [clone(self.estimator) for _ in range
  204. (self.n_classes_)]
  205. # A sparse LabelBinarizer, with sparse_output=True, has been
  206. # shown to outperform or match a dense label binarizer in all
  207. # cases and has also resulted in less or equal memory consumption
  208. # in the fit_ovr function overall.
  209. self.label_binarizer_ = LabelBinarizer(sparse_output=True)
  210. self.label_binarizer_.fit(self.classes_)
  211. if len(np.setdiff1d(y, self.classes_)):
  212. raise ValueError(("Mini-batch contains {0} while classes " +
  213. "must be subset of {1}").format(np.unique(y),
  214. self.classes_))
  215. Y = self.label_binarizer_.transform(y)
  216. Y = Y.tocsc()
  217. columns = (col.toarray().ravel() for col in Y.T)
  218. self.estimators_ = Parallel(n_jobs=self.n_jobs)(
  219. delayed(_partial_fit_binary)(estimator, X, column)
  220. for estimator, column in izip(self.estimators_, columns))
  221. return self
  222. def predict(self, X):
  223. """Predict multi-class targets using underlying estimators.
  224. Parameters
  225. ----------
  226. X : (sparse) array-like, shape = [n_samples, n_features]
  227. Data.
  228. Returns
  229. -------
  230. y : (sparse) array-like, shape = [n_samples, ], [n_samples, n_classes].
  231. Predicted multi-class targets.
  232. """
  233. check_is_fitted(self, 'estimators_')
  234. if (hasattr(self.estimators_[0], "decision_function") and
  235. is_classifier(self.estimators_[0])):
  236. thresh = 0
  237. else:
  238. thresh = .5
  239. n_samples = _num_samples(X)
  240. if self.label_binarizer_.y_type_ == "multiclass":
  241. maxima = np.empty(n_samples, dtype=float)
  242. maxima.fill(-np.inf)
  243. argmaxima = np.zeros(n_samples, dtype=int)
  244. for i, e in enumerate(self.estimators_):
  245. pred = _predict_binary(e, X)
  246. np.maximum(maxima, pred, out=maxima)
  247. argmaxima[maxima == pred] = i
  248. return self.classes_[np.array(argmaxima.T)]
  249. else:
  250. indices = array.array('i')
  251. indptr = array.array('i', [0])
  252. for e in self.estimators_:
  253. indices.extend(np.where(_predict_binary(e, X) > thresh)[0])
  254. indptr.append(len(indices))
  255. data = np.ones(len(indices), dtype=int)
  256. indicator = sp.csc_matrix((data, indices, indptr),
  257. shape=(n_samples, len(self.estimators_)))
  258. return self.label_binarizer_.inverse_transform(indicator)
  259. @if_delegate_has_method(['_first_estimator', 'estimator'])
  260. def predict_proba(self, X):
  261. """Probability estimates.
  262. The returned estimates for all classes are ordered by label of classes.
  263. Note that in the multilabel case, each sample can have any number of
  264. labels. This returns the marginal probability that the given sample has
  265. the label in question. For example, it is entirely consistent that two
  266. labels both have a 90% probability of applying to a given sample.
  267. In the single label multiclass case, the rows of the returned matrix
  268. sum to 1.
  269. Parameters
  270. ----------
  271. X : array-like, shape = [n_samples, n_features]
  272. Returns
  273. -------
  274. T : (sparse) array-like, shape = [n_samples, n_classes]
  275. Returns the probability of the sample for each class in the model,
  276. where classes are ordered as they are in `self.classes_`.
  277. """
  278. check_is_fitted(self, 'estimators_')
  279. # Y[i, j] gives the probability that sample i has the label j.
  280. # In the multi-label case, these are not disjoint.
  281. Y = np.array([e.predict_proba(X)[:, 1] for e in self.estimators_]).T
  282. if len(self.estimators_) == 1:
  283. # Only one estimator, but we still want to return probabilities
  284. # for two classes.
  285. Y = np.concatenate(((1 - Y), Y), axis=1)
  286. if not self.multilabel_:
  287. # Then, probabilities should be normalized to 1.
  288. Y /= np.sum(Y, axis=1)[:, np.newaxis]
  289. return Y
  290. @if_delegate_has_method(['_first_estimator', 'estimator'])
  291. def decision_function(self, X):
  292. """Returns the distance of each sample from the decision boundary for
  293. each class. This can only be used with estimators which implement the
  294. decision_function method.
  295. Parameters
  296. ----------
  297. X : array-like, shape = [n_samples, n_features]
  298. Returns
  299. -------
  300. T : array-like, shape = [n_samples, n_classes]
  301. """
  302. check_is_fitted(self, 'estimators_')
  303. if len(self.estimators_) == 1:
  304. return self.estimators_[0].decision_function(X)
  305. return np.array([est.decision_function(X).ravel()
  306. for est in self.estimators_]).T
  307. @property
  308. def multilabel_(self):
  309. """Whether this is a multilabel classifier"""
  310. return self.label_binarizer_.y_type_.startswith('multilabel')
  311. @property
  312. def n_classes_(self):
  313. return len(self.classes_)
  314. @property
  315. def coef_(self):
  316. check_is_fitted(self, 'estimators_')
  317. if not hasattr(self.estimators_[0], "coef_"):
  318. raise AttributeError(
  319. "Base estimator doesn't have a coef_ attribute.")
  320. coefs = [e.coef_ for e in self.estimators_]
  321. if sp.issparse(coefs[0]):
  322. return sp.vstack(coefs)
  323. return np.vstack(coefs)
  324. @property
  325. def intercept_(self):
  326. check_is_fitted(self, 'estimators_')
  327. if not hasattr(self.estimators_[0], "intercept_"):
  328. raise AttributeError(
  329. "Base estimator doesn't have an intercept_ attribute.")
  330. return np.array([e.intercept_.ravel() for e in self.estimators_])
  331. @property
  332. def _pairwise(self):
  333. """Indicate if wrapped estimator is using a precomputed Gram matrix"""
  334. return getattr(self.estimator, "_pairwise", False)
  335. @property
  336. def _first_estimator(self):
  337. return self.estimators_[0]
  338. def _fit_ovo_binary(estimator, X, y, i, j):
  339. """Fit a single binary estimator (one-vs-one)."""
  340. cond = np.logical_or(y == i, y == j)
  341. y = y[cond]
  342. y_binary = np.empty(y.shape, np.int)
  343. y_binary[y == i] = 0
  344. y_binary[y == j] = 1
  345. indcond = np.arange(X.shape[0])[cond]
  346. return _fit_binary(estimator,
  347. _safe_split(estimator, X, None, indices=indcond)[0],
  348. y_binary, classes=[i, j]), indcond
  349. def _partial_fit_ovo_binary(estimator, X, y, i, j):
  350. """Partially fit a single binary estimator(one-vs-one)."""
  351. cond = np.logical_or(y == i, y == j)
  352. y = y[cond]
  353. if len(y) != 0:
  354. y_binary = np.zeros_like(y)
  355. y_binary[y == j] = 1
  356. return _partial_fit_binary(estimator, X[cond], y_binary)
  357. return estimator
  358. class OneVsOneClassifier(BaseEstimator, ClassifierMixin, MetaEstimatorMixin):
  359. """One-vs-one multiclass strategy
  360. This strategy consists in fitting one classifier per class pair.
  361. At prediction time, the class which received the most votes is selected.
  362. Since it requires to fit `n_classes * (n_classes - 1) / 2` classifiers,
  363. this method is usually slower than one-vs-the-rest, due to its
  364. O(n_classes^2) complexity. However, this method may be advantageous for
  365. algorithms such as kernel algorithms which don't scale well with
  366. `n_samples`. This is because each individual learning problem only involves
  367. a small subset of the data whereas, with one-vs-the-rest, the complete
  368. dataset is used `n_classes` times.
  369. Read more in the :ref:`User Guide <ovo_classification>`.
  370. Parameters
  371. ----------
  372. estimator : estimator object
  373. An estimator object implementing `fit` and one of `decision_function`
  374. or `predict_proba`.
  375. n_jobs : int or None, optional (default=None)
  376. The number of jobs to use for the computation.
  377. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  378. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  379. for more details.
  380. Attributes
  381. ----------
  382. estimators_ : list of `n_classes * (n_classes - 1) / 2` estimators
  383. Estimators used for predictions.
  384. classes_ : numpy array of shape [n_classes]
  385. Array containing labels.
  386. """
  387. def __init__(self, estimator, n_jobs=None):
  388. self.estimator = estimator
  389. self.n_jobs = n_jobs
  390. def fit(self, X, y):
  391. """Fit underlying estimators.
  392. Parameters
  393. ----------
  394. X : (sparse) array-like, shape = [n_samples, n_features]
  395. Data.
  396. y : array-like, shape = [n_samples]
  397. Multi-class targets.
  398. Returns
  399. -------
  400. self
  401. """
  402. X, y = check_X_y(X, y, accept_sparse=['csr', 'csc'])
  403. check_classification_targets(y)
  404. self.classes_ = np.unique(y)
  405. if len(self.classes_) == 1:
  406. raise ValueError("OneVsOneClassifier can not be fit when only one"
  407. " class is present.")
  408. n_classes = self.classes_.shape[0]
  409. estimators_indices = list(zip(*(Parallel(n_jobs=self.n_jobs)(
  410. delayed(_fit_ovo_binary)
  411. (self.estimator, X, y, self.classes_[i], self.classes_[j])
  412. for i in range(n_classes) for j in range(i + 1, n_classes)))))
  413. self.estimators_ = estimators_indices[0]
  414. try:
  415. self.pairwise_indices_ = (
  416. estimators_indices[1] if self._pairwise else None)
  417. except AttributeError:
  418. self.pairwise_indices_ = None
  419. return self
  420. @if_delegate_has_method(delegate='estimator')
  421. def partial_fit(self, X, y, classes=None):
  422. """Partially fit underlying estimators
  423. Should be used when memory is inefficient to train all data. Chunks
  424. of data can be passed in several iteration, where the first call
  425. should have an array of all target variables.
  426. Parameters
  427. ----------
  428. X : (sparse) array-like, shape = [n_samples, n_features]
  429. Data.
  430. y : array-like, shape = [n_samples]
  431. Multi-class targets.
  432. classes : array, shape (n_classes, )
  433. Classes across all calls to partial_fit.
  434. Can be obtained via `np.unique(y_all)`, where y_all is the
  435. target vector of the entire dataset.
  436. This argument is only required in the first call of partial_fit
  437. and can be omitted in the subsequent calls.
  438. Returns
  439. -------
  440. self
  441. """
  442. if _check_partial_fit_first_call(self, classes):
  443. self.estimators_ = [clone(self.estimator) for i in
  444. range(self.n_classes_ *
  445. (self.n_classes_ - 1) // 2)]
  446. if len(np.setdiff1d(y, self.classes_)):
  447. raise ValueError("Mini-batch contains {0} while it "
  448. "must be subset of {1}".format(np.unique(y),
  449. self.classes_))
  450. X, y = check_X_y(X, y, accept_sparse=['csr', 'csc'])
  451. check_classification_targets(y)
  452. combinations = itertools.combinations(range(self.n_classes_), 2)
  453. self.estimators_ = Parallel(
  454. n_jobs=self.n_jobs)(
  455. delayed(_partial_fit_ovo_binary)(
  456. estimator, X, y, self.classes_[i], self.classes_[j])
  457. for estimator, (i, j) in izip(self.estimators_,
  458. (combinations)))
  459. self.pairwise_indices_ = None
  460. return self
  461. def predict(self, X):
  462. """Estimate the best class label for each sample in X.
  463. This is implemented as ``argmax(decision_function(X), axis=1)`` which
  464. will return the label of the class with most votes by estimators
  465. predicting the outcome of a decision for each possible class pair.
  466. Parameters
  467. ----------
  468. X : (sparse) array-like, shape = [n_samples, n_features]
  469. Data.
  470. Returns
  471. -------
  472. y : numpy array of shape [n_samples]
  473. Predicted multi-class targets.
  474. """
  475. Y = self.decision_function(X)
  476. if self.n_classes_ == 2:
  477. return self.classes_[(Y > 0).astype(np.int)]
  478. return self.classes_[Y.argmax(axis=1)]
  479. def decision_function(self, X):
  480. """Decision function for the OneVsOneClassifier.
  481. The decision values for the samples are computed by adding the
  482. normalized sum of pair-wise classification confidence levels to the
  483. votes in order to disambiguate between the decision values when the
  484. votes for all the classes are equal leading to a tie.
  485. Parameters
  486. ----------
  487. X : array-like, shape = [n_samples, n_features]
  488. Returns
  489. -------
  490. Y : array-like, shape = [n_samples, n_classes]
  491. """
  492. check_is_fitted(self, 'estimators_')
  493. indices = self.pairwise_indices_
  494. if indices is None:
  495. Xs = [X] * len(self.estimators_)
  496. else:
  497. Xs = [X[:, idx] for idx in indices]
  498. predictions = np.vstack([est.predict(Xi)
  499. for est, Xi in zip(self.estimators_, Xs)]).T
  500. confidences = np.vstack([_predict_binary(est, Xi)
  501. for est, Xi in zip(self.estimators_, Xs)]).T
  502. Y = _ovr_decision_function(predictions,
  503. confidences, len(self.classes_))
  504. if self.n_classes_ == 2:
  505. return Y[:, 1]
  506. return Y
  507. @property
  508. def n_classes_(self):
  509. return len(self.classes_)
  510. @property
  511. def _pairwise(self):
  512. """Indicate if wrapped estimator is using a precomputed Gram matrix"""
  513. return getattr(self.estimator, "_pairwise", False)
  514. class OutputCodeClassifier(BaseEstimator, ClassifierMixin, MetaEstimatorMixin):
  515. """(Error-Correcting) Output-Code multiclass strategy
  516. Output-code based strategies consist in representing each class with a
  517. binary code (an array of 0s and 1s). At fitting time, one binary
  518. classifier per bit in the code book is fitted. At prediction time, the
  519. classifiers are used to project new points in the class space and the class
  520. closest to the points is chosen. The main advantage of these strategies is
  521. that the number of classifiers used can be controlled by the user, either
  522. for compressing the model (0 < code_size < 1) or for making the model more
  523. robust to errors (code_size > 1). See the documentation for more details.
  524. Read more in the :ref:`User Guide <ecoc>`.
  525. Parameters
  526. ----------
  527. estimator : estimator object
  528. An estimator object implementing `fit` and one of `decision_function`
  529. or `predict_proba`.
  530. code_size : float
  531. Percentage of the number of classes to be used to create the code book.
  532. A number between 0 and 1 will require fewer classifiers than
  533. one-vs-the-rest. A number greater than 1 will require more classifiers
  534. than one-vs-the-rest.
  535. random_state : int, RandomState instance or None, optional, default: None
  536. The generator used to initialize the codebook. If int, random_state is
  537. the seed used by the random number generator; If RandomState instance,
  538. random_state is the random number generator; If None, the random number
  539. generator is the RandomState instance used by `np.random`.
  540. n_jobs : int or None, optional (default=None)
  541. The number of jobs to use for the computation.
  542. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  543. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  544. for more details.
  545. Attributes
  546. ----------
  547. estimators_ : list of `int(n_classes * code_size)` estimators
  548. Estimators used for predictions.
  549. classes_ : numpy array of shape [n_classes]
  550. Array containing labels.
  551. code_book_ : numpy array of shape [n_classes, code_size]
  552. Binary array containing the code of each class.
  553. References
  554. ----------
  555. .. [1] "Solving multiclass learning problems via error-correcting output
  556. codes",
  557. Dietterich T., Bakiri G.,
  558. Journal of Artificial Intelligence Research 2,
  559. 1995.
  560. .. [2] "The error coding method and PICTs",
  561. James G., Hastie T.,
  562. Journal of Computational and Graphical statistics 7,
  563. 1998.
  564. .. [3] "The Elements of Statistical Learning",
  565. Hastie T., Tibshirani R., Friedman J., page 606 (second-edition)
  566. 2008.
  567. """
  568. def __init__(self, estimator, code_size=1.5, random_state=None,
  569. n_jobs=None):
  570. self.estimator = estimator
  571. self.code_size = code_size
  572. self.random_state = random_state
  573. self.n_jobs = n_jobs
  574. def fit(self, X, y):
  575. """Fit underlying estimators.
  576. Parameters
  577. ----------
  578. X : (sparse) array-like, shape = [n_samples, n_features]
  579. Data.
  580. y : numpy array of shape [n_samples]
  581. Multi-class targets.
  582. Returns
  583. -------
  584. self
  585. """
  586. X, y = check_X_y(X, y)
  587. if self.code_size <= 0:
  588. raise ValueError("code_size should be greater than 0, got {0}"
  589. "".format(self.code_size))
  590. _check_estimator(self.estimator)
  591. random_state = check_random_state(self.random_state)
  592. check_classification_targets(y)
  593. self.classes_ = np.unique(y)
  594. n_classes = self.classes_.shape[0]
  595. code_size_ = int(n_classes * self.code_size)
  596. # FIXME: there are more elaborate methods than generating the codebook
  597. # randomly.
  598. self.code_book_ = random_state.random_sample((n_classes, code_size_))
  599. self.code_book_[self.code_book_ > 0.5] = 1
  600. if hasattr(self.estimator, "decision_function"):
  601. self.code_book_[self.code_book_ != 1] = -1
  602. else:
  603. self.code_book_[self.code_book_ != 1] = 0
  604. classes_index = dict((c, i) for i, c in enumerate(self.classes_))
  605. Y = np.array([self.code_book_[classes_index[y[i]]]
  606. for i in range(X.shape[0])], dtype=np.int)
  607. self.estimators_ = Parallel(n_jobs=self.n_jobs)(
  608. delayed(_fit_binary)(self.estimator, X, Y[:, i])
  609. for i in range(Y.shape[1]))
  610. return self
  611. def predict(self, X):
  612. """Predict multi-class targets using underlying estimators.
  613. Parameters
  614. ----------
  615. X : (sparse) array-like, shape = [n_samples, n_features]
  616. Data.
  617. Returns
  618. -------
  619. y : numpy array of shape [n_samples]
  620. Predicted multi-class targets.
  621. """
  622. check_is_fitted(self, 'estimators_')
  623. X = check_array(X)
  624. Y = np.array([_predict_binary(e, X) for e in self.estimators_]).T
  625. pred = euclidean_distances(Y, self.code_book_).argmin(axis=1)
  626. return self.classes_[pred]