Advertisement
Guest User

Untitled

a guest
Mar 4th, 2015
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. df = pd.read_csv('../data/iris.csv')
  2. df_1 = df.iloc[0:100]
  3.  
  4. d = {'setosa': 1,
  5. 'versicolor': 0}
  6. df_1['class'] = df_1['class'].map(d)
  7.  
  8. X = df_1[['sepal_length', 'petal_width']].values
  9. y = df_1['class'].values
  10.  
  11. # standardize
  12. X[:,0] = (X[:,0] - X[:,0].mean()) / X[:,0].std()
  13. X[:,1] = (X[:,1] - X[:,1].mean()) / X[:,1].std()
  14.  
  15. import numpy as np
  16.  
  17. class Perceptron(object):
  18.  
  19. def __init__(self, eta=0.01, epochs=50):
  20. self.eta = eta
  21. self.epochs = epochs
  22.  
  23. def fit(self, X, y):
  24.  
  25. # Initialize weights to 0
  26. self.w_ = np.zeros(1 + X.shape[1])
  27.  
  28. self.cost_ = []
  29.  
  30. for i in range(self.epochs):
  31.  
  32. # update weights
  33. y_pred = self._dot_prod(X)
  34. errors = (y - y_pred)
  35. self.w_[1:] += self.eta * X.T.dot(errors)
  36. self.w_[0] += self.eta * errors.sum()
  37.  
  38. cost = (errors**2).sum() / 2.0
  39. self.cost_.append(cost)
  40.  
  41. return self
  42.  
  43. def _dot_prod(self, X):
  44. return np.dot(X, self.w_[1:]) + self.w_[0]
  45.  
  46. def predict(self, X):
  47. return np.where(self._dot_prod(X) >= 0.0, 1, 0)
  48.  
  49. ppn = Perceptron(epochs=15, eta=0.01)
  50. ppn.fit(X, y)
  51.  
  52. array([ 0.5 , 0.02486745, -0.51024596])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement