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.

712 lines
25 KiB

4 years ago
  1. """
  2. This module implements multioutput regression and classification.
  3. The estimators provided in this module are meta-estimators: they require
  4. a base estimator to be provided in their constructor. The meta-estimator
  5. extends single output estimators to multioutput estimators.
  6. """
  7. # Author: Tim Head <betatim@gmail.com>
  8. # Author: Hugo Bowne-Anderson <hugobowne@gmail.com>
  9. # Author: Chris Rivera <chris.richard.rivera@gmail.com>
  10. # Author: Michael Williamson
  11. # Author: James Ashton Nichols <james.ashton.nichols@gmail.com>
  12. #
  13. # License: BSD 3 clause
  14. import numpy as np
  15. import scipy.sparse as sp
  16. from abc import ABCMeta, abstractmethod
  17. from .base import BaseEstimator, clone, MetaEstimatorMixin
  18. from .base import RegressorMixin, ClassifierMixin, is_classifier
  19. from .model_selection import cross_val_predict
  20. from .utils import check_array, check_X_y, check_random_state
  21. from .utils.fixes import parallel_helper
  22. from .utils.metaestimators import if_delegate_has_method
  23. from .utils.validation import check_is_fitted, has_fit_parameter
  24. from .utils.multiclass import check_classification_targets
  25. from .utils import Parallel, delayed
  26. from .externals import six
  27. __all__ = ["MultiOutputRegressor", "MultiOutputClassifier",
  28. "ClassifierChain", "RegressorChain"]
  29. def _fit_estimator(estimator, X, y, sample_weight=None):
  30. estimator = clone(estimator)
  31. if sample_weight is not None:
  32. estimator.fit(X, y, sample_weight=sample_weight)
  33. else:
  34. estimator.fit(X, y)
  35. return estimator
  36. def _partial_fit_estimator(estimator, X, y, classes=None, sample_weight=None,
  37. first_time=True):
  38. if first_time:
  39. estimator = clone(estimator)
  40. if sample_weight is not None:
  41. if classes is not None:
  42. estimator.partial_fit(X, y, classes=classes,
  43. sample_weight=sample_weight)
  44. else:
  45. estimator.partial_fit(X, y, sample_weight=sample_weight)
  46. else:
  47. if classes is not None:
  48. estimator.partial_fit(X, y, classes=classes)
  49. else:
  50. estimator.partial_fit(X, y)
  51. return estimator
  52. class MultiOutputEstimator(six.with_metaclass(ABCMeta, BaseEstimator,
  53. MetaEstimatorMixin)):
  54. @abstractmethod
  55. def __init__(self, estimator, n_jobs=None):
  56. self.estimator = estimator
  57. self.n_jobs = n_jobs
  58. @if_delegate_has_method('estimator')
  59. def partial_fit(self, X, y, classes=None, sample_weight=None):
  60. """Incrementally fit the model to data.
  61. Fit a separate model for each output variable.
  62. Parameters
  63. ----------
  64. X : (sparse) array-like, shape (n_samples, n_features)
  65. Data.
  66. y : (sparse) array-like, shape (n_samples, n_outputs)
  67. Multi-output targets.
  68. classes : list of numpy arrays, shape (n_outputs)
  69. Each array is unique classes for one output in str/int
  70. Can be obtained by via
  71. ``[np.unique(y[:, i]) for i in range(y.shape[1])]``, where y is the
  72. target matrix of the entire dataset.
  73. This argument is required for the first call to partial_fit
  74. and can be omitted in the subsequent calls.
  75. Note that y doesn't need to contain all labels in `classes`.
  76. sample_weight : array-like, shape = (n_samples) or None
  77. Sample weights. If None, then samples are equally weighted.
  78. Only supported if the underlying regressor supports sample
  79. weights.
  80. Returns
  81. -------
  82. self : object
  83. """
  84. X, y = check_X_y(X, y,
  85. multi_output=True,
  86. accept_sparse=True)
  87. if y.ndim == 1:
  88. raise ValueError("y must have at least two dimensions for "
  89. "multi-output regression but has only one.")
  90. if (sample_weight is not None and
  91. not has_fit_parameter(self.estimator, 'sample_weight')):
  92. raise ValueError("Underlying estimator does not support"
  93. " sample weights.")
  94. first_time = not hasattr(self, 'estimators_')
  95. self.estimators_ = Parallel(n_jobs=self.n_jobs)(
  96. delayed(_partial_fit_estimator)(
  97. self.estimators_[i] if not first_time else self.estimator,
  98. X, y[:, i],
  99. classes[i] if classes is not None else None,
  100. sample_weight, first_time) for i in range(y.shape[1]))
  101. return self
  102. def fit(self, X, y, sample_weight=None):
  103. """ Fit the model to data.
  104. Fit a separate model for each output variable.
  105. Parameters
  106. ----------
  107. X : (sparse) array-like, shape (n_samples, n_features)
  108. Data.
  109. y : (sparse) array-like, shape (n_samples, n_outputs)
  110. Multi-output targets. An indicator matrix turns on multilabel
  111. estimation.
  112. sample_weight : array-like, shape = (n_samples) or None
  113. Sample weights. If None, then samples are equally weighted.
  114. Only supported if the underlying regressor supports sample
  115. weights.
  116. Returns
  117. -------
  118. self : object
  119. """
  120. if not hasattr(self.estimator, "fit"):
  121. raise ValueError("The base estimator should implement a fit method")
  122. X, y = check_X_y(X, y,
  123. multi_output=True,
  124. accept_sparse=True)
  125. if is_classifier(self):
  126. check_classification_targets(y)
  127. if y.ndim == 1:
  128. raise ValueError("y must have at least two dimensions for "
  129. "multi-output regression but has only one.")
  130. if (sample_weight is not None and
  131. not has_fit_parameter(self.estimator, 'sample_weight')):
  132. raise ValueError("Underlying estimator does not support"
  133. " sample weights.")
  134. self.estimators_ = Parallel(n_jobs=self.n_jobs)(
  135. delayed(_fit_estimator)(
  136. self.estimator, X, y[:, i], sample_weight)
  137. for i in range(y.shape[1]))
  138. return self
  139. def predict(self, X):
  140. """Predict multi-output variable using a model
  141. trained for each target variable.
  142. Parameters
  143. ----------
  144. X : (sparse) array-like, shape (n_samples, n_features)
  145. Data.
  146. Returns
  147. -------
  148. y : (sparse) array-like, shape (n_samples, n_outputs)
  149. Multi-output targets predicted across multiple predictors.
  150. Note: Separate models are generated for each predictor.
  151. """
  152. check_is_fitted(self, 'estimators_')
  153. if not hasattr(self.estimator, "predict"):
  154. raise ValueError("The base estimator should implement a predict method")
  155. X = check_array(X, accept_sparse=True)
  156. y = Parallel(n_jobs=self.n_jobs)(
  157. delayed(parallel_helper)(e, 'predict', X)
  158. for e in self.estimators_)
  159. return np.asarray(y).T
  160. class MultiOutputRegressor(MultiOutputEstimator, RegressorMixin):
  161. """Multi target regression
  162. This strategy consists of fitting one regressor per target. This is a
  163. simple strategy for extending regressors that do not natively support
  164. multi-target regression.
  165. Parameters
  166. ----------
  167. estimator : estimator object
  168. An estimator object implementing `fit` and `predict`.
  169. n_jobs : int or None, optional (default=None)
  170. The number of jobs to run in parallel for `fit`.
  171. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  172. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  173. for more details.
  174. When individual estimators are fast to train or predict
  175. using `n_jobs>1` can result in slower performance due
  176. to the overhead of spawning processes.
  177. """
  178. def __init__(self, estimator, n_jobs=None):
  179. super(MultiOutputRegressor, self).__init__(estimator, n_jobs)
  180. @if_delegate_has_method('estimator')
  181. def partial_fit(self, X, y, sample_weight=None):
  182. """Incrementally fit the model to data.
  183. Fit a separate model for each output variable.
  184. Parameters
  185. ----------
  186. X : (sparse) array-like, shape (n_samples, n_features)
  187. Data.
  188. y : (sparse) array-like, shape (n_samples, n_outputs)
  189. Multi-output targets.
  190. sample_weight : array-like, shape = (n_samples) or None
  191. Sample weights. If None, then samples are equally weighted.
  192. Only supported if the underlying regressor supports sample
  193. weights.
  194. Returns
  195. -------
  196. self : object
  197. """
  198. super(MultiOutputRegressor, self).partial_fit(
  199. X, y, sample_weight=sample_weight)
  200. def score(self, X, y, sample_weight=None):
  201. """Returns the coefficient of determination R^2 of the prediction.
  202. The coefficient R^2 is defined as (1 - u/v), where u is the residual
  203. sum of squares ((y_true - y_pred) ** 2).sum() and v is the regression
  204. sum of squares ((y_true - y_true.mean()) ** 2).sum().
  205. Best possible score is 1.0 and it can be negative (because the
  206. model can be arbitrarily worse). A constant model that always
  207. predicts the expected value of y, disregarding the input features,
  208. would get a R^2 score of 0.0.
  209. Notes
  210. -----
  211. R^2 is calculated by weighting all the targets equally using
  212. `multioutput='uniform_average'`.
  213. Parameters
  214. ----------
  215. X : array-like, shape (n_samples, n_features)
  216. Test samples.
  217. y : array-like, shape (n_samples) or (n_samples, n_outputs)
  218. True values for X.
  219. sample_weight : array-like, shape [n_samples], optional
  220. Sample weights.
  221. Returns
  222. -------
  223. score : float
  224. R^2 of self.predict(X) wrt. y.
  225. """
  226. # XXX remove in 0.19 when r2_score default for multioutput changes
  227. from .metrics import r2_score
  228. return r2_score(y, self.predict(X), sample_weight=sample_weight,
  229. multioutput='uniform_average')
  230. class MultiOutputClassifier(MultiOutputEstimator, ClassifierMixin):
  231. """Multi target classification
  232. This strategy consists of fitting one classifier per target. This is a
  233. simple strategy for extending classifiers that do not natively support
  234. multi-target classification
  235. Parameters
  236. ----------
  237. estimator : estimator object
  238. An estimator object implementing `fit`, `score` and `predict_proba`.
  239. n_jobs : int or None, optional (default=None)
  240. The number of jobs to use for the computation.
  241. It does each target variable in y in parallel.
  242. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  243. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  244. for more details.
  245. Attributes
  246. ----------
  247. estimators_ : list of ``n_output`` estimators
  248. Estimators used for predictions.
  249. """
  250. def __init__(self, estimator, n_jobs=None):
  251. super(MultiOutputClassifier, self).__init__(estimator, n_jobs)
  252. def predict_proba(self, X):
  253. """Probability estimates.
  254. Returns prediction probabilities for each class of each output.
  255. Parameters
  256. ----------
  257. X : array-like, shape (n_samples, n_features)
  258. Data
  259. Returns
  260. -------
  261. p : array of shape = [n_samples, n_classes], or a list of n_outputs \
  262. such arrays if n_outputs > 1.
  263. The class probabilities of the input samples. The order of the
  264. classes corresponds to that in the attribute `classes_`.
  265. """
  266. check_is_fitted(self, 'estimators_')
  267. if not hasattr(self.estimator, "predict_proba"):
  268. raise ValueError("The base estimator should implement"
  269. "predict_proba method")
  270. results = [estimator.predict_proba(X) for estimator in
  271. self.estimators_]
  272. return results
  273. def score(self, X, y):
  274. """"Returns the mean accuracy on the given test data and labels.
  275. Parameters
  276. ----------
  277. X : array-like, shape [n_samples, n_features]
  278. Test samples
  279. y : array-like, shape [n_samples, n_outputs]
  280. True values for X
  281. Returns
  282. -------
  283. scores : float
  284. accuracy_score of self.predict(X) versus y
  285. """
  286. check_is_fitted(self, 'estimators_')
  287. n_outputs_ = len(self.estimators_)
  288. if y.ndim == 1:
  289. raise ValueError("y must have at least two dimensions for "
  290. "multi target classification but has only one")
  291. if y.shape[1] != n_outputs_:
  292. raise ValueError("The number of outputs of Y for fit {0} and"
  293. " score {1} should be same".
  294. format(n_outputs_, y.shape[1]))
  295. y_pred = self.predict(X)
  296. return np.mean(np.all(y == y_pred, axis=1))
  297. class _BaseChain(six.with_metaclass(ABCMeta, BaseEstimator)):
  298. def __init__(self, base_estimator, order=None, cv=None, random_state=None):
  299. self.base_estimator = base_estimator
  300. self.order = order
  301. self.cv = cv
  302. self.random_state = random_state
  303. @abstractmethod
  304. def fit(self, X, Y):
  305. """Fit the model to data matrix X and targets Y.
  306. Parameters
  307. ----------
  308. X : {array-like, sparse matrix}, shape (n_samples, n_features)
  309. The input data.
  310. Y : array-like, shape (n_samples, n_classes)
  311. The target values.
  312. Returns
  313. -------
  314. self : object
  315. """
  316. X, Y = check_X_y(X, Y, multi_output=True, accept_sparse=True)
  317. random_state = check_random_state(self.random_state)
  318. check_array(X, accept_sparse=True)
  319. self.order_ = self.order
  320. if self.order_ is None:
  321. self.order_ = np.array(range(Y.shape[1]))
  322. elif isinstance(self.order_, str):
  323. if self.order_ == 'random':
  324. self.order_ = random_state.permutation(Y.shape[1])
  325. elif sorted(self.order_) != list(range(Y.shape[1])):
  326. raise ValueError("invalid order")
  327. self.estimators_ = [clone(self.base_estimator)
  328. for _ in range(Y.shape[1])]
  329. if self.cv is None:
  330. Y_pred_chain = Y[:, self.order_]
  331. if sp.issparse(X):
  332. X_aug = sp.hstack((X, Y_pred_chain), format='lil')
  333. X_aug = X_aug.tocsr()
  334. else:
  335. X_aug = np.hstack((X, Y_pred_chain))
  336. elif sp.issparse(X):
  337. Y_pred_chain = sp.lil_matrix((X.shape[0], Y.shape[1]))
  338. X_aug = sp.hstack((X, Y_pred_chain), format='lil')
  339. else:
  340. Y_pred_chain = np.zeros((X.shape[0], Y.shape[1]))
  341. X_aug = np.hstack((X, Y_pred_chain))
  342. del Y_pred_chain
  343. for chain_idx, estimator in enumerate(self.estimators_):
  344. y = Y[:, self.order_[chain_idx]]
  345. estimator.fit(X_aug[:, :(X.shape[1] + chain_idx)], y)
  346. if self.cv is not None and chain_idx < len(self.estimators_) - 1:
  347. col_idx = X.shape[1] + chain_idx
  348. cv_result = cross_val_predict(
  349. self.base_estimator, X_aug[:, :col_idx],
  350. y=y, cv=self.cv)
  351. if sp.issparse(X_aug):
  352. X_aug[:, col_idx] = np.expand_dims(cv_result, 1)
  353. else:
  354. X_aug[:, col_idx] = cv_result
  355. return self
  356. def predict(self, X):
  357. """Predict on the data matrix X using the ClassifierChain model.
  358. Parameters
  359. ----------
  360. X : {array-like, sparse matrix}, shape (n_samples, n_features)
  361. The input data.
  362. Returns
  363. -------
  364. Y_pred : array-like, shape (n_samples, n_classes)
  365. The predicted values.
  366. """
  367. X = check_array(X, accept_sparse=True)
  368. Y_pred_chain = np.zeros((X.shape[0], len(self.estimators_)))
  369. for chain_idx, estimator in enumerate(self.estimators_):
  370. previous_predictions = Y_pred_chain[:, :chain_idx]
  371. if sp.issparse(X):
  372. if chain_idx == 0:
  373. X_aug = X
  374. else:
  375. X_aug = sp.hstack((X, previous_predictions))
  376. else:
  377. X_aug = np.hstack((X, previous_predictions))
  378. Y_pred_chain[:, chain_idx] = estimator.predict(X_aug)
  379. inv_order = np.empty_like(self.order_)
  380. inv_order[self.order_] = np.arange(len(self.order_))
  381. Y_pred = Y_pred_chain[:, inv_order]
  382. return Y_pred
  383. class ClassifierChain(_BaseChain, ClassifierMixin, MetaEstimatorMixin):
  384. """A multi-label model that arranges binary classifiers into a chain.
  385. Each model makes a prediction in the order specified by the chain using
  386. all of the available features provided to the model plus the predictions
  387. of models that are earlier in the chain.
  388. Read more in the :ref:`User Guide <classifierchain>`.
  389. Parameters
  390. ----------
  391. base_estimator : estimator
  392. The base estimator from which the classifier chain is built.
  393. order : array-like, shape=[n_outputs] or 'random', optional
  394. By default the order will be determined by the order of columns in
  395. the label matrix Y.::
  396. order = [0, 1, 2, ..., Y.shape[1] - 1]
  397. The order of the chain can be explicitly set by providing a list of
  398. integers. For example, for a chain of length 5.::
  399. order = [1, 3, 2, 4, 0]
  400. means that the first model in the chain will make predictions for
  401. column 1 in the Y matrix, the second model will make predictions
  402. for column 3, etc.
  403. If order is 'random' a random ordering will be used.
  404. cv : int, cross-validation generator or an iterable, optional \
  405. (default=None)
  406. Determines whether to use cross validated predictions or true
  407. labels for the results of previous estimators in the chain.
  408. If cv is None the true labels are used when fitting. Otherwise
  409. possible inputs for cv are:
  410. * integer, to specify the number of folds in a (Stratified)KFold,
  411. * An object to be used as a cross-validation generator.
  412. * An iterable yielding train, test splits.
  413. random_state : int, RandomState instance or None, optional (default=None)
  414. If int, random_state is the seed used by the random number generator;
  415. If RandomState instance, random_state is the random number generator;
  416. If None, the random number generator is the RandomState instance used
  417. by `np.random`.
  418. The random number generator is used to generate random chain orders.
  419. Attributes
  420. ----------
  421. classes_ : list
  422. A list of arrays of length ``len(estimators_)`` containing the
  423. class labels for each estimator in the chain.
  424. estimators_ : list
  425. A list of clones of base_estimator.
  426. order_ : list
  427. The order of labels in the classifier chain.
  428. See also
  429. --------
  430. RegressorChain: Equivalent for regression
  431. MultioutputClassifier: Classifies each output independently rather than
  432. chaining.
  433. References
  434. ----------
  435. Jesse Read, Bernhard Pfahringer, Geoff Holmes, Eibe Frank, "Classifier
  436. Chains for Multi-label Classification", 2009.
  437. """
  438. def fit(self, X, Y):
  439. """Fit the model to data matrix X and targets Y.
  440. Parameters
  441. ----------
  442. X : {array-like, sparse matrix}, shape (n_samples, n_features)
  443. The input data.
  444. Y : array-like, shape (n_samples, n_classes)
  445. The target values.
  446. Returns
  447. -------
  448. self : object
  449. """
  450. super(ClassifierChain, self).fit(X, Y)
  451. self.classes_ = []
  452. for chain_idx, estimator in enumerate(self.estimators_):
  453. self.classes_.append(estimator.classes_)
  454. return self
  455. @if_delegate_has_method('base_estimator')
  456. def predict_proba(self, X):
  457. """Predict probability estimates.
  458. Parameters
  459. ----------
  460. X : {array-like, sparse matrix}, shape (n_samples, n_features)
  461. Returns
  462. -------
  463. Y_prob : array-like, shape (n_samples, n_classes)
  464. """
  465. X = check_array(X, accept_sparse=True)
  466. Y_prob_chain = np.zeros((X.shape[0], len(self.estimators_)))
  467. Y_pred_chain = np.zeros((X.shape[0], len(self.estimators_)))
  468. for chain_idx, estimator in enumerate(self.estimators_):
  469. previous_predictions = Y_pred_chain[:, :chain_idx]
  470. if sp.issparse(X):
  471. X_aug = sp.hstack((X, previous_predictions))
  472. else:
  473. X_aug = np.hstack((X, previous_predictions))
  474. Y_prob_chain[:, chain_idx] = estimator.predict_proba(X_aug)[:, 1]
  475. Y_pred_chain[:, chain_idx] = estimator.predict(X_aug)
  476. inv_order = np.empty_like(self.order_)
  477. inv_order[self.order_] = np.arange(len(self.order_))
  478. Y_prob = Y_prob_chain[:, inv_order]
  479. return Y_prob
  480. @if_delegate_has_method('base_estimator')
  481. def decision_function(self, X):
  482. """Evaluate the decision_function of the models in the chain.
  483. Parameters
  484. ----------
  485. X : array-like, shape (n_samples, n_features)
  486. Returns
  487. -------
  488. Y_decision : array-like, shape (n_samples, n_classes )
  489. Returns the decision function of the sample for each model
  490. in the chain.
  491. """
  492. Y_decision_chain = np.zeros((X.shape[0], len(self.estimators_)))
  493. Y_pred_chain = np.zeros((X.shape[0], len(self.estimators_)))
  494. for chain_idx, estimator in enumerate(self.estimators_):
  495. previous_predictions = Y_pred_chain[:, :chain_idx]
  496. if sp.issparse(X):
  497. X_aug = sp.hstack((X, previous_predictions))
  498. else:
  499. X_aug = np.hstack((X, previous_predictions))
  500. Y_decision_chain[:, chain_idx] = estimator.decision_function(X_aug)
  501. Y_pred_chain[:, chain_idx] = estimator.predict(X_aug)
  502. inv_order = np.empty_like(self.order_)
  503. inv_order[self.order_] = np.arange(len(self.order_))
  504. Y_decision = Y_decision_chain[:, inv_order]
  505. return Y_decision
  506. class RegressorChain(_BaseChain, RegressorMixin, MetaEstimatorMixin):
  507. """A multi-label model that arranges regressions into a chain.
  508. Each model makes a prediction in the order specified by the chain using
  509. all of the available features provided to the model plus the predictions
  510. of models that are earlier in the chain.
  511. Read more in the :ref:`User Guide <regressorchain>`.
  512. Parameters
  513. ----------
  514. base_estimator : estimator
  515. The base estimator from which the classifier chain is built.
  516. order : array-like, shape=[n_outputs] or 'random', optional
  517. By default the order will be determined by the order of columns in
  518. the label matrix Y.::
  519. order = [0, 1, 2, ..., Y.shape[1] - 1]
  520. The order of the chain can be explicitly set by providing a list of
  521. integers. For example, for a chain of length 5.::
  522. order = [1, 3, 2, 4, 0]
  523. means that the first model in the chain will make predictions for
  524. column 1 in the Y matrix, the second model will make predictions
  525. for column 3, etc.
  526. If order is 'random' a random ordering will be used.
  527. cv : int, cross-validation generator or an iterable, optional \
  528. (default=None)
  529. Determines whether to use cross validated predictions or true
  530. labels for the results of previous estimators in the chain.
  531. If cv is None the true labels are used when fitting. Otherwise
  532. possible inputs for cv are:
  533. * integer, to specify the number of folds in a (Stratified)KFold,
  534. * An object to be used as a cross-validation generator.
  535. * An iterable yielding train, test splits.
  536. random_state : int, RandomState instance or None, optional (default=None)
  537. If int, random_state is the seed used by the random number generator;
  538. If RandomState instance, random_state is the random number generator;
  539. If None, the random number generator is the RandomState instance used
  540. by `np.random`.
  541. The random number generator is used to generate random chain orders.
  542. Attributes
  543. ----------
  544. estimators_ : list
  545. A list of clones of base_estimator.
  546. order_ : list
  547. The order of labels in the classifier chain.
  548. See also
  549. --------
  550. ClassifierChain: Equivalent for classification
  551. MultioutputRegressor: Learns each output independently rather than
  552. chaining.
  553. """
  554. def fit(self, X, Y):
  555. """Fit the model to data matrix X and targets Y.
  556. Parameters
  557. ----------
  558. X : {array-like, sparse matrix}, shape (n_samples, n_features)
  559. The input data.
  560. Y : array-like, shape (n_samples, n_classes)
  561. The target values.
  562. Returns
  563. -------
  564. self : object
  565. """
  566. super(RegressorChain, self).fit(X, Y)
  567. return self