Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- df = pd.read_csv('../data/iris.csv')
- df_1 = df.iloc[0:100]
- d = {'setosa': 1,
- 'versicolor': 0}
- df_1['class'] = df_1['class'].map(d)
- X = df_1[['sepal_length', 'petal_width']].values
- y = df_1['class'].values
- # standardize
- X[:,0] = (X[:,0] - X[:,0].mean()) / X[:,0].std()
- X[:,1] = (X[:,1] - X[:,1].mean()) / X[:,1].std()
- import numpy as np
- class Perceptron(object):
- def __init__(self, eta=0.01, epochs=50):
- self.eta = eta
- self.epochs = epochs
- def fit(self, X, y):
- # Initialize weights to 0
- self.w_ = np.zeros(1 + X.shape[1])
- self.cost_ = []
- for i in range(self.epochs):
- # update weights
- y_pred = self._dot_prod(X)
- errors = (y - y_pred)
- self.w_[1:] += self.eta * X.T.dot(errors)
- self.w_[0] += self.eta * errors.sum()
- cost = (errors**2).sum() / 2.0
- self.cost_.append(cost)
- return self
- def _dot_prod(self, X):
- return np.dot(X, self.w_[1:]) + self.w_[0]
- def predict(self, X):
- return np.where(self._dot_prod(X) >= 0.0, 1, 0)
- ppn = Perceptron(epochs=15, eta=0.01)
- ppn.fit(X, y)
- array([ 0.5 , 0.02486745, -0.51024596])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement