_perceptron.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. # Author: Mathieu Blondel
  2. # License: BSD 3 clause
  3. from numbers import Real
  4. from ..utils._param_validation import Interval, StrOptions
  5. from ._stochastic_gradient import BaseSGDClassifier
  6. class Perceptron(BaseSGDClassifier):
  7. """Linear perceptron classifier.
  8. Read more in the :ref:`User Guide <perceptron>`.
  9. Parameters
  10. ----------
  11. penalty : {'l2','l1','elasticnet'}, default=None
  12. The penalty (aka regularization term) to be used.
  13. alpha : float, default=0.0001
  14. Constant that multiplies the regularization term if regularization is
  15. used.
  16. l1_ratio : float, default=0.15
  17. The Elastic Net mixing parameter, with `0 <= l1_ratio <= 1`.
  18. `l1_ratio=0` corresponds to L2 penalty, `l1_ratio=1` to L1.
  19. Only used if `penalty='elasticnet'`.
  20. .. versionadded:: 0.24
  21. fit_intercept : bool, default=True
  22. Whether the intercept should be estimated or not. If False, the
  23. data is assumed to be already centered.
  24. max_iter : int, default=1000
  25. The maximum number of passes over the training data (aka epochs).
  26. It only impacts the behavior in the ``fit`` method, and not the
  27. :meth:`partial_fit` method.
  28. .. versionadded:: 0.19
  29. tol : float or None, default=1e-3
  30. The stopping criterion. If it is not None, the iterations will stop
  31. when (loss > previous_loss - tol).
  32. .. versionadded:: 0.19
  33. shuffle : bool, default=True
  34. Whether or not the training data should be shuffled after each epoch.
  35. verbose : int, default=0
  36. The verbosity level.
  37. eta0 : float, default=1
  38. Constant by which the updates are multiplied.
  39. n_jobs : int, default=None
  40. The number of CPUs to use to do the OVA (One Versus All, for
  41. multi-class problems) computation.
  42. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  43. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  44. for more details.
  45. random_state : int, RandomState instance or None, default=0
  46. Used to shuffle the training data, when ``shuffle`` is set to
  47. ``True``. Pass an int for reproducible output across multiple
  48. function calls.
  49. See :term:`Glossary <random_state>`.
  50. early_stopping : bool, default=False
  51. Whether to use early stopping to terminate training when validation.
  52. score is not improving. If set to True, it will automatically set aside
  53. a stratified fraction of training data as validation and terminate
  54. training when validation score is not improving by at least tol for
  55. n_iter_no_change consecutive epochs.
  56. .. versionadded:: 0.20
  57. validation_fraction : float, default=0.1
  58. The proportion of training data to set aside as validation set for
  59. early stopping. Must be between 0 and 1.
  60. Only used if early_stopping is True.
  61. .. versionadded:: 0.20
  62. n_iter_no_change : int, default=5
  63. Number of iterations with no improvement to wait before early stopping.
  64. .. versionadded:: 0.20
  65. class_weight : dict, {class_label: weight} or "balanced", default=None
  66. Preset for the class_weight fit parameter.
  67. Weights associated with classes. If not given, all classes
  68. are supposed to have weight one.
  69. The "balanced" mode uses the values of y to automatically adjust
  70. weights inversely proportional to class frequencies in the input data
  71. as ``n_samples / (n_classes * np.bincount(y))``.
  72. warm_start : bool, default=False
  73. When set to True, reuse the solution of the previous call to fit as
  74. initialization, otherwise, just erase the previous solution. See
  75. :term:`the Glossary <warm_start>`.
  76. Attributes
  77. ----------
  78. classes_ : ndarray of shape (n_classes,)
  79. The unique classes labels.
  80. coef_ : ndarray of shape (1, n_features) if n_classes == 2 else \
  81. (n_classes, n_features)
  82. Weights assigned to the features.
  83. intercept_ : ndarray of shape (1,) if n_classes == 2 else (n_classes,)
  84. Constants in decision function.
  85. loss_function_ : concrete LossFunction
  86. The function that determines the loss, or difference between the
  87. output of the algorithm and the target values.
  88. n_features_in_ : int
  89. Number of features seen during :term:`fit`.
  90. .. versionadded:: 0.24
  91. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  92. Names of features seen during :term:`fit`. Defined only when `X`
  93. has feature names that are all strings.
  94. .. versionadded:: 1.0
  95. n_iter_ : int
  96. The actual number of iterations to reach the stopping criterion.
  97. For multiclass fits, it is the maximum over every binary fit.
  98. t_ : int
  99. Number of weight updates performed during training.
  100. Same as ``(n_iter_ * n_samples + 1)``.
  101. See Also
  102. --------
  103. sklearn.linear_model.SGDClassifier : Linear classifiers
  104. (SVM, logistic regression, etc.) with SGD training.
  105. Notes
  106. -----
  107. ``Perceptron`` is a classification algorithm which shares the same
  108. underlying implementation with ``SGDClassifier``. In fact,
  109. ``Perceptron()`` is equivalent to `SGDClassifier(loss="perceptron",
  110. eta0=1, learning_rate="constant", penalty=None)`.
  111. References
  112. ----------
  113. https://en.wikipedia.org/wiki/Perceptron and references therein.
  114. Examples
  115. --------
  116. >>> from sklearn.datasets import load_digits
  117. >>> from sklearn.linear_model import Perceptron
  118. >>> X, y = load_digits(return_X_y=True)
  119. >>> clf = Perceptron(tol=1e-3, random_state=0)
  120. >>> clf.fit(X, y)
  121. Perceptron()
  122. >>> clf.score(X, y)
  123. 0.939...
  124. """
  125. _parameter_constraints: dict = {**BaseSGDClassifier._parameter_constraints}
  126. _parameter_constraints.pop("loss")
  127. _parameter_constraints.pop("average")
  128. _parameter_constraints.update(
  129. {
  130. "penalty": [StrOptions({"l2", "l1", "elasticnet"}), None],
  131. "alpha": [Interval(Real, 0, None, closed="left")],
  132. "l1_ratio": [Interval(Real, 0, 1, closed="both")],
  133. "eta0": [Interval(Real, 0, None, closed="left")],
  134. }
  135. )
  136. def __init__(
  137. self,
  138. *,
  139. penalty=None,
  140. alpha=0.0001,
  141. l1_ratio=0.15,
  142. fit_intercept=True,
  143. max_iter=1000,
  144. tol=1e-3,
  145. shuffle=True,
  146. verbose=0,
  147. eta0=1.0,
  148. n_jobs=None,
  149. random_state=0,
  150. early_stopping=False,
  151. validation_fraction=0.1,
  152. n_iter_no_change=5,
  153. class_weight=None,
  154. warm_start=False,
  155. ):
  156. super().__init__(
  157. loss="perceptron",
  158. penalty=penalty,
  159. alpha=alpha,
  160. l1_ratio=l1_ratio,
  161. fit_intercept=fit_intercept,
  162. max_iter=max_iter,
  163. tol=tol,
  164. shuffle=shuffle,
  165. verbose=verbose,
  166. random_state=random_state,
  167. learning_rate="constant",
  168. eta0=eta0,
  169. early_stopping=early_stopping,
  170. validation_fraction=validation_fraction,
  171. n_iter_no_change=n_iter_no_change,
  172. power_t=0.5,
  173. warm_start=warm_start,
  174. class_weight=class_weight,
  175. n_jobs=n_jobs,
  176. )