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.

41 lines
1.2 KiB

  1. import numpy as np
  2. class Perceptron(object):
  3. """Implements a perceptron network"""
  4. def __init__(self, input_size, lr=1, epochs=100):
  5. self.W = np.zeros(input_size+1)
  6. # add one for bias
  7. self.epochs = epochs
  8. self.lr = lr
  9. #activation function
  10. def activation_fn(self, x):
  11. #return (x >= 0).astype(np.float32)
  12. return 1 if x >= 0 else 0
  13. #we need a prediction function to run an input through the perceptron and return an output.
  14. def predict(self, x):
  15. z = self.W.T.dot(x)
  16. a = self.activation_fn(z)
  17. return a
  18. def fit(self, X, d):
  19. for _ in range(self.epochs):
  20. for i in range(d.shape[0]):
  21. x = np.insert(X[i], 0, 1)
  22. y = self.predict(x)
  23. e = d[i] - y
  24. self.W = self.W + self.lr * e * x
  25. #the easiset set of data that we can provide is the AND gate. Given is set of inputs and outputs.
  26. if __name__ == '__main__':
  27. X = np.array([
  28. [0, 0],
  29. [0, 1],
  30. [1, 0],
  31. [1, 1]
  32. ])
  33. d = np.array([0, 0, 0, 1])
  34. perceptron = Perceptron(input_size=2)
  35. perceptron.fit(X, d)
  36. print(perceptron.W)