Warning: Declaration of action_plugin_tablewidth::register(&$controller) should be compatible with DokuWiki_Action_Plugin::register(Doku_Event_Handler $controller) in /s/bach/b/class/cs545/public_html/fall16/lib/plugins/tablewidth/action.php on line 93
import numpy as np from matplotlib import pyplot as plt from sklearn.base import BaseEstimator class Perceptron (BaseEstimator) : """An implementation of the perceptron algorithm. Note that this implementation does not include a bias term""" def __init__(self, max_iterations=500, learning_rate=0.2) : self.max_iterations = max_iterations self.learning_rate = learning_rate def fit(self, X, y) : """ Train a classifier using the perceptron training algorithm. After training the attribute 'w' will contain the perceptron weight vector. Parameters ---------- X : ndarray, shape (num_examples, n_features) Training data. y : ndarray, shape (n_examples,) Array of labels. """ self.w = np.zeros(len(X[0])) converged = False iterations = 0 while (not converged and iterations < self.max_iterations) : converged = True for i in range(len(X)) : if y[i] * self.decision_function(X[i]) <= 0 : self.w = self.w + y[i] * self.learning_rate * X[i] converged = False iterations += 1 self.converged = converged if converged : print ('converged in %d iterations ' % iterations) def decision_function(self, X) : return np.inner(self.w, X) def predict(self, X) : """ make predictions using a trained linear classifier Parameters ---------- X : ndarray, shape (num_examples, n_features) Training data. """ scores = np.inner(self.w, X) return np.sign(scores) if __name__=='__main__' : X,y,w = generate_separable_data(40) p = Perceptron() p.fit(X,y)