_passive_aggressive.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. # Authors: Rob Zinkov, Mathieu Blondel
  2. # License: BSD 3 clause
  3. from numbers import Real
  4. from ..base import _fit_context
  5. from ..utils._param_validation import Interval, StrOptions
  6. from ._stochastic_gradient import DEFAULT_EPSILON, BaseSGDClassifier, BaseSGDRegressor
  7. class PassiveAggressiveClassifier(BaseSGDClassifier):
  8. """Passive Aggressive Classifier.
  9. Read more in the :ref:`User Guide <passive_aggressive>`.
  10. Parameters
  11. ----------
  12. C : float, default=1.0
  13. Maximum step size (regularization). Defaults to 1.0.
  14. fit_intercept : bool, default=True
  15. Whether the intercept should be estimated or not. If False, the
  16. data is assumed to be already centered.
  17. max_iter : int, default=1000
  18. The maximum number of passes over the training data (aka epochs).
  19. It only impacts the behavior in the ``fit`` method, and not the
  20. :meth:`PassiveAggressive.partial_fit` method.
  21. .. versionadded:: 0.19
  22. tol : float or None, default=1e-3
  23. The stopping criterion. If it is not None, the iterations will stop
  24. when (loss > previous_loss - tol).
  25. .. versionadded:: 0.19
  26. early_stopping : bool, default=False
  27. Whether to use early stopping to terminate training when validation.
  28. score is not improving. If set to True, it will automatically set aside
  29. a stratified fraction of training data as validation and terminate
  30. training when validation score is not improving by at least tol for
  31. n_iter_no_change consecutive epochs.
  32. .. versionadded:: 0.20
  33. validation_fraction : float, default=0.1
  34. The proportion of training data to set aside as validation set for
  35. early stopping. Must be between 0 and 1.
  36. Only used if early_stopping is True.
  37. .. versionadded:: 0.20
  38. n_iter_no_change : int, default=5
  39. Number of iterations with no improvement to wait before early stopping.
  40. .. versionadded:: 0.20
  41. shuffle : bool, default=True
  42. Whether or not the training data should be shuffled after each epoch.
  43. verbose : int, default=0
  44. The verbosity level.
  45. loss : str, default="hinge"
  46. The loss function to be used:
  47. hinge: equivalent to PA-I in the reference paper.
  48. squared_hinge: equivalent to PA-II in the reference paper.
  49. n_jobs : int or None, default=None
  50. The number of CPUs to use to do the OVA (One Versus All, for
  51. multi-class problems) computation.
  52. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  53. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  54. for more details.
  55. random_state : int, RandomState instance, default=None
  56. Used to shuffle the training data, when ``shuffle`` is set to
  57. ``True``. Pass an int for reproducible output across multiple
  58. function calls.
  59. See :term:`Glossary <random_state>`.
  60. warm_start : bool, default=False
  61. When set to True, reuse the solution of the previous call to fit as
  62. initialization, otherwise, just erase the previous solution.
  63. See :term:`the Glossary <warm_start>`.
  64. Repeatedly calling fit or partial_fit when warm_start is True can
  65. result in a different solution than when calling fit a single time
  66. because of the way the data is shuffled.
  67. class_weight : dict, {class_label: weight} or "balanced" or None, \
  68. default=None
  69. Preset for the class_weight fit parameter.
  70. Weights associated with classes. If not given, all classes
  71. are supposed to have weight one.
  72. The "balanced" mode uses the values of y to automatically adjust
  73. weights inversely proportional to class frequencies in the input data
  74. as ``n_samples / (n_classes * np.bincount(y))``.
  75. .. versionadded:: 0.17
  76. parameter *class_weight* to automatically weight samples.
  77. average : bool or int, default=False
  78. When set to True, computes the averaged SGD weights and stores the
  79. result in the ``coef_`` attribute. If set to an int greater than 1,
  80. averaging will begin once the total number of samples seen reaches
  81. average. So average=10 will begin averaging after seeing 10 samples.
  82. .. versionadded:: 0.19
  83. parameter *average* to use weights averaging in SGD.
  84. Attributes
  85. ----------
  86. coef_ : ndarray of shape (1, n_features) if n_classes == 2 else \
  87. (n_classes, n_features)
  88. Weights assigned to the features.
  89. intercept_ : ndarray of shape (1,) if n_classes == 2 else (n_classes,)
  90. Constants in decision function.
  91. n_features_in_ : int
  92. Number of features seen during :term:`fit`.
  93. .. versionadded:: 0.24
  94. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  95. Names of features seen during :term:`fit`. Defined only when `X`
  96. has feature names that are all strings.
  97. .. versionadded:: 1.0
  98. n_iter_ : int
  99. The actual number of iterations to reach the stopping criterion.
  100. For multiclass fits, it is the maximum over every binary fit.
  101. classes_ : ndarray of shape (n_classes,)
  102. The unique classes labels.
  103. t_ : int
  104. Number of weight updates performed during training.
  105. Same as ``(n_iter_ * n_samples + 1)``.
  106. loss_function_ : callable
  107. Loss function used by the algorithm.
  108. See Also
  109. --------
  110. SGDClassifier : Incrementally trained logistic regression.
  111. Perceptron : Linear perceptron classifier.
  112. References
  113. ----------
  114. Online Passive-Aggressive Algorithms
  115. <http://jmlr.csail.mit.edu/papers/volume7/crammer06a/crammer06a.pdf>
  116. K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR (2006)
  117. Examples
  118. --------
  119. >>> from sklearn.linear_model import PassiveAggressiveClassifier
  120. >>> from sklearn.datasets import make_classification
  121. >>> X, y = make_classification(n_features=4, random_state=0)
  122. >>> clf = PassiveAggressiveClassifier(max_iter=1000, random_state=0,
  123. ... tol=1e-3)
  124. >>> clf.fit(X, y)
  125. PassiveAggressiveClassifier(random_state=0)
  126. >>> print(clf.coef_)
  127. [[0.26642044 0.45070924 0.67251877 0.64185414]]
  128. >>> print(clf.intercept_)
  129. [1.84127814]
  130. >>> print(clf.predict([[0, 0, 0, 0]]))
  131. [1]
  132. """
  133. _parameter_constraints: dict = {
  134. **BaseSGDClassifier._parameter_constraints,
  135. "loss": [StrOptions({"hinge", "squared_hinge"})],
  136. "C": [Interval(Real, 0, None, closed="right")],
  137. }
  138. def __init__(
  139. self,
  140. *,
  141. C=1.0,
  142. fit_intercept=True,
  143. max_iter=1000,
  144. tol=1e-3,
  145. early_stopping=False,
  146. validation_fraction=0.1,
  147. n_iter_no_change=5,
  148. shuffle=True,
  149. verbose=0,
  150. loss="hinge",
  151. n_jobs=None,
  152. random_state=None,
  153. warm_start=False,
  154. class_weight=None,
  155. average=False,
  156. ):
  157. super().__init__(
  158. penalty=None,
  159. fit_intercept=fit_intercept,
  160. max_iter=max_iter,
  161. tol=tol,
  162. early_stopping=early_stopping,
  163. validation_fraction=validation_fraction,
  164. n_iter_no_change=n_iter_no_change,
  165. shuffle=shuffle,
  166. verbose=verbose,
  167. random_state=random_state,
  168. eta0=1.0,
  169. warm_start=warm_start,
  170. class_weight=class_weight,
  171. average=average,
  172. n_jobs=n_jobs,
  173. )
  174. self.C = C
  175. self.loss = loss
  176. @_fit_context(prefer_skip_nested_validation=True)
  177. def partial_fit(self, X, y, classes=None):
  178. """Fit linear model with Passive Aggressive algorithm.
  179. Parameters
  180. ----------
  181. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  182. Subset of the training data.
  183. y : array-like of shape (n_samples,)
  184. Subset of the target values.
  185. classes : ndarray of shape (n_classes,)
  186. Classes across all calls to partial_fit.
  187. Can be obtained by via `np.unique(y_all)`, where y_all is the
  188. target vector of the entire dataset.
  189. This argument is required for the first call to partial_fit
  190. and can be omitted in the subsequent calls.
  191. Note that y doesn't need to contain all labels in `classes`.
  192. Returns
  193. -------
  194. self : object
  195. Fitted estimator.
  196. """
  197. if not hasattr(self, "classes_"):
  198. self._more_validate_params(for_partial_fit=True)
  199. if self.class_weight == "balanced":
  200. raise ValueError(
  201. "class_weight 'balanced' is not supported for "
  202. "partial_fit. For 'balanced' weights, use "
  203. "`sklearn.utils.compute_class_weight` with "
  204. "`class_weight='balanced'`. In place of y you "
  205. "can use a large enough subset of the full "
  206. "training set target to properly estimate the "
  207. "class frequency distributions. Pass the "
  208. "resulting weights as the class_weight "
  209. "parameter."
  210. )
  211. lr = "pa1" if self.loss == "hinge" else "pa2"
  212. return self._partial_fit(
  213. X,
  214. y,
  215. alpha=1.0,
  216. C=self.C,
  217. loss="hinge",
  218. learning_rate=lr,
  219. max_iter=1,
  220. classes=classes,
  221. sample_weight=None,
  222. coef_init=None,
  223. intercept_init=None,
  224. )
  225. @_fit_context(prefer_skip_nested_validation=True)
  226. def fit(self, X, y, coef_init=None, intercept_init=None):
  227. """Fit linear model with Passive Aggressive algorithm.
  228. Parameters
  229. ----------
  230. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  231. Training data.
  232. y : array-like of shape (n_samples,)
  233. Target values.
  234. coef_init : ndarray of shape (n_classes, n_features)
  235. The initial coefficients to warm-start the optimization.
  236. intercept_init : ndarray of shape (n_classes,)
  237. The initial intercept to warm-start the optimization.
  238. Returns
  239. -------
  240. self : object
  241. Fitted estimator.
  242. """
  243. self._more_validate_params()
  244. lr = "pa1" if self.loss == "hinge" else "pa2"
  245. return self._fit(
  246. X,
  247. y,
  248. alpha=1.0,
  249. C=self.C,
  250. loss="hinge",
  251. learning_rate=lr,
  252. coef_init=coef_init,
  253. intercept_init=intercept_init,
  254. )
  255. class PassiveAggressiveRegressor(BaseSGDRegressor):
  256. """Passive Aggressive Regressor.
  257. Read more in the :ref:`User Guide <passive_aggressive>`.
  258. Parameters
  259. ----------
  260. C : float, default=1.0
  261. Maximum step size (regularization). Defaults to 1.0.
  262. fit_intercept : bool, default=True
  263. Whether the intercept should be estimated or not. If False, the
  264. data is assumed to be already centered. Defaults to True.
  265. max_iter : int, default=1000
  266. The maximum number of passes over the training data (aka epochs).
  267. It only impacts the behavior in the ``fit`` method, and not the
  268. :meth:`partial_fit` method.
  269. .. versionadded:: 0.19
  270. tol : float or None, default=1e-3
  271. The stopping criterion. If it is not None, the iterations will stop
  272. when (loss > previous_loss - tol).
  273. .. versionadded:: 0.19
  274. early_stopping : bool, default=False
  275. Whether to use early stopping to terminate training when validation.
  276. score is not improving. If set to True, it will automatically set aside
  277. a fraction of training data as validation and terminate
  278. training when validation score is not improving by at least tol for
  279. n_iter_no_change consecutive epochs.
  280. .. versionadded:: 0.20
  281. validation_fraction : float, default=0.1
  282. The proportion of training data to set aside as validation set for
  283. early stopping. Must be between 0 and 1.
  284. Only used if early_stopping is True.
  285. .. versionadded:: 0.20
  286. n_iter_no_change : int, default=5
  287. Number of iterations with no improvement to wait before early stopping.
  288. .. versionadded:: 0.20
  289. shuffle : bool, default=True
  290. Whether or not the training data should be shuffled after each epoch.
  291. verbose : int, default=0
  292. The verbosity level.
  293. loss : str, default="epsilon_insensitive"
  294. The loss function to be used:
  295. epsilon_insensitive: equivalent to PA-I in the reference paper.
  296. squared_epsilon_insensitive: equivalent to PA-II in the reference
  297. paper.
  298. epsilon : float, default=0.1
  299. If the difference between the current prediction and the correct label
  300. is below this threshold, the model is not updated.
  301. random_state : int, RandomState instance, default=None
  302. Used to shuffle the training data, when ``shuffle`` is set to
  303. ``True``. Pass an int for reproducible output across multiple
  304. function calls.
  305. See :term:`Glossary <random_state>`.
  306. warm_start : bool, default=False
  307. When set to True, reuse the solution of the previous call to fit as
  308. initialization, otherwise, just erase the previous solution.
  309. See :term:`the Glossary <warm_start>`.
  310. Repeatedly calling fit or partial_fit when warm_start is True can
  311. result in a different solution than when calling fit a single time
  312. because of the way the data is shuffled.
  313. average : bool or int, default=False
  314. When set to True, computes the averaged SGD weights and stores the
  315. result in the ``coef_`` attribute. If set to an int greater than 1,
  316. averaging will begin once the total number of samples seen reaches
  317. average. So average=10 will begin averaging after seeing 10 samples.
  318. .. versionadded:: 0.19
  319. parameter *average* to use weights averaging in SGD.
  320. Attributes
  321. ----------
  322. coef_ : array, shape = [1, n_features] if n_classes == 2 else [n_classes,\
  323. n_features]
  324. Weights assigned to the features.
  325. intercept_ : array, shape = [1] if n_classes == 2 else [n_classes]
  326. Constants in decision function.
  327. n_features_in_ : int
  328. Number of features seen during :term:`fit`.
  329. .. versionadded:: 0.24
  330. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  331. Names of features seen during :term:`fit`. Defined only when `X`
  332. has feature names that are all strings.
  333. .. versionadded:: 1.0
  334. n_iter_ : int
  335. The actual number of iterations to reach the stopping criterion.
  336. t_ : int
  337. Number of weight updates performed during training.
  338. Same as ``(n_iter_ * n_samples + 1)``.
  339. See Also
  340. --------
  341. SGDRegressor : Linear model fitted by minimizing a regularized
  342. empirical loss with SGD.
  343. References
  344. ----------
  345. Online Passive-Aggressive Algorithms
  346. <http://jmlr.csail.mit.edu/papers/volume7/crammer06a/crammer06a.pdf>
  347. K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR (2006).
  348. Examples
  349. --------
  350. >>> from sklearn.linear_model import PassiveAggressiveRegressor
  351. >>> from sklearn.datasets import make_regression
  352. >>> X, y = make_regression(n_features=4, random_state=0)
  353. >>> regr = PassiveAggressiveRegressor(max_iter=100, random_state=0,
  354. ... tol=1e-3)
  355. >>> regr.fit(X, y)
  356. PassiveAggressiveRegressor(max_iter=100, random_state=0)
  357. >>> print(regr.coef_)
  358. [20.48736655 34.18818427 67.59122734 87.94731329]
  359. >>> print(regr.intercept_)
  360. [-0.02306214]
  361. >>> print(regr.predict([[0, 0, 0, 0]]))
  362. [-0.02306214]
  363. """
  364. _parameter_constraints: dict = {
  365. **BaseSGDRegressor._parameter_constraints,
  366. "loss": [StrOptions({"epsilon_insensitive", "squared_epsilon_insensitive"})],
  367. "C": [Interval(Real, 0, None, closed="right")],
  368. "epsilon": [Interval(Real, 0, None, closed="left")],
  369. }
  370. def __init__(
  371. self,
  372. *,
  373. C=1.0,
  374. fit_intercept=True,
  375. max_iter=1000,
  376. tol=1e-3,
  377. early_stopping=False,
  378. validation_fraction=0.1,
  379. n_iter_no_change=5,
  380. shuffle=True,
  381. verbose=0,
  382. loss="epsilon_insensitive",
  383. epsilon=DEFAULT_EPSILON,
  384. random_state=None,
  385. warm_start=False,
  386. average=False,
  387. ):
  388. super().__init__(
  389. penalty=None,
  390. l1_ratio=0,
  391. epsilon=epsilon,
  392. eta0=1.0,
  393. fit_intercept=fit_intercept,
  394. max_iter=max_iter,
  395. tol=tol,
  396. early_stopping=early_stopping,
  397. validation_fraction=validation_fraction,
  398. n_iter_no_change=n_iter_no_change,
  399. shuffle=shuffle,
  400. verbose=verbose,
  401. random_state=random_state,
  402. warm_start=warm_start,
  403. average=average,
  404. )
  405. self.C = C
  406. self.loss = loss
  407. @_fit_context(prefer_skip_nested_validation=True)
  408. def partial_fit(self, X, y):
  409. """Fit linear model with Passive Aggressive algorithm.
  410. Parameters
  411. ----------
  412. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  413. Subset of training data.
  414. y : numpy array of shape [n_samples]
  415. Subset of target values.
  416. Returns
  417. -------
  418. self : object
  419. Fitted estimator.
  420. """
  421. if not hasattr(self, "coef_"):
  422. self._more_validate_params(for_partial_fit=True)
  423. lr = "pa1" if self.loss == "epsilon_insensitive" else "pa2"
  424. return self._partial_fit(
  425. X,
  426. y,
  427. alpha=1.0,
  428. C=self.C,
  429. loss="epsilon_insensitive",
  430. learning_rate=lr,
  431. max_iter=1,
  432. sample_weight=None,
  433. coef_init=None,
  434. intercept_init=None,
  435. )
  436. @_fit_context(prefer_skip_nested_validation=True)
  437. def fit(self, X, y, coef_init=None, intercept_init=None):
  438. """Fit linear model with Passive Aggressive algorithm.
  439. Parameters
  440. ----------
  441. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  442. Training data.
  443. y : numpy array of shape [n_samples]
  444. Target values.
  445. coef_init : array, shape = [n_features]
  446. The initial coefficients to warm-start the optimization.
  447. intercept_init : array, shape = [1]
  448. The initial intercept to warm-start the optimization.
  449. Returns
  450. -------
  451. self : object
  452. Fitted estimator.
  453. """
  454. self._more_validate_params()
  455. lr = "pa1" if self.loss == "epsilon_insensitive" else "pa2"
  456. return self._fit(
  457. X,
  458. y,
  459. alpha=1.0,
  460. C=self.C,
  461. loss="epsilon_insensitive",
  462. learning_rate=lr,
  463. coef_init=coef_init,
  464. intercept_init=intercept_init,
  465. )