Repository where I mostly put random python scripts.
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.

64 lines
1.7 KiB

  1. import numpy as np
  2. class Perceptron(object):
  3. """
  4. Perceptron classifier
  5. ___________________
  6. parameters
  7. __________________
  8. eta: float
  9. learning rate betweeen 0.0 and 1.0
  10. n_iter: int
  11. Passes over the training dataset
  12. ___________________
  13. Attributes
  14. ___________________
  15. w_: 1d array
  16. weights after training
  17. errors_: list
  18. Number of msiclassifications for every epoch
  19. """
  20. def __init__(self, eta, n_iter):
  21. self.eta = eta
  22. self.n_iter = n_iter
  23. def fit(self, X, y):
  24. """
  25. Fit training data
  26. ______________________
  27. parameters
  28. ______________________
  29. X: {array-like}, shape = [n_samples, n_features]
  30. Training vectors where n_samples is the number of samples
  31. and n_features is the number of features
  32. y: array-like, shape = [n_samples]
  33. Target values
  34. ____________________
  35. Returns
  36. ____________________
  37. self: object
  38. """
  39. self.w_ = np.zeros(1 + X.shape[1])
  40. self.errors_ = []
  41. for _ in range(self.n_iter):
  42. errors = 0
  43. for xi,target in zip(X, y):
  44. update = self.eta * (target - self.predict(xi))
  45. self.w_[1:] += update * xi
  46. self.w_[0] += update
  47. errors += int(update != 0.0)
  48. self.errors_.append(errors)
  49. return self
  50. def net_input(self, X):
  51. """
  52. Calculate net input
  53. """
  54. return np.dot(X, self.w_[1:]) + self.w_[0]
  55. def predict(self, X):
  56. """
  57. Return class label after unit step
  58. """
  59. return np.where(self.net_input(X) >= 0.0, 1, -1)