Reikriam

Perceptron test

Feb 2nd, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. import numpy as np
  2. from sklearn.datasets import load_iris
  3. from sklearn.model_selection import train_test_split
  4.  
  5. class Perceptron(object):
  6.  
  7. def __init__(self, shape, learning_rate=0.1, epochs=100):
  8. self.weight = np.random.randn(1, shape + 1)
  9. self.epochs = epochs
  10. self.learning_rate = learning_rate
  11.  
  12. def activation(self, X):
  13. prediction = []
  14. for elem in X:
  15. if elem>=0.5:
  16. prediction.append(1)
  17. else:
  18. prediction.append(0)
  19. prediction = np.asarray(prediction)
  20. return prediction
  21.  
  22. def predict(self, X):
  23. z = np.dot(X, self.weight[:, 1:].T) + self.weight[0, 0]
  24. a = self.activation(z)
  25. return a
  26.  
  27. def fit(self, X, d):
  28. self.errors = []
  29. for epoch in range(self.epochs):
  30. y = self.predict(X)
  31. e = d - y
  32. mean_error = np.mean(e)
  33. self.weight[:, 1:] += (self.learning_rate*np.dot(X.T, e)).T
  34. self.weight[:, 0] += self.learning_rate*mean_error
  35. err = mean_error**2
  36. self.errors.append(err)
  37. print("epoch=%d, error=%.2f" % (epoch, err))
  38.  
  39. def test_perceptron(self, X, y):
  40. predicted = self.predict(X)
  41. e = predicted - y
  42. correct = 0
  43. for error in e:
  44. if error==0:
  45. correct += 1
  46. accuracy = (correct/y.shape[0])*100
  47. return accuracy
  48.  
  49. if __name__ == "__main__":
  50. iris = load_iris()
  51. X = iris.data
  52. mean = np.mean(X)
  53. std = np.std(X)
  54. X = (X - mean)/std
  55. y = iris.target
  56. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)
  57.  
  58. perceptron = Perceptron(shape=X.shape[1])
  59. perceptron.fit(X_train, y_train)
  60.  
  61. print("Accuracy = {0}%".format(perceptron.test_perceptron(X_test, y_test)))
Add Comment
Please, Sign In to add comment