This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision | ||
code:perceptron [2015/08/28 10:36] asa |
code:perceptron [2016/09/08 11:04] asa |
||
---|---|---|---|
Line 5: | Line 5: | ||
<file python perceptron.py> | <file python perceptron.py> | ||
- | |||
import numpy as np | import numpy as np | ||
Line 21: | Line 20: | ||
def fit(self, X, y) : | 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])) | self.w = np.zeros(len(X[0])) | ||
converged = False | converged = False | ||
Line 31: | Line 43: | ||
self.w = self.w + y[i] * self.learning_rate * X[i] | self.w = self.w + y[i] * self.learning_rate * X[i] | ||
converged = False | converged = False | ||
+ | plot_data(X, y, self.w) | ||
iterations += 1 | iterations += 1 | ||
- | plot_data(X, y, self.w) | ||
self.converged = converged | self.converged = converged | ||
if converged : | if converged : | ||
- | print 'converged in %d iterations ' % iterations | + | print ('converged in %d iterations ' % iterations) |
def discriminant(self, x) : | def discriminant(self, x) : | ||
- | return np.dot(self.w, x) | + | return np.inner(self.w, x) |
| | ||
def predict(self, X) : | def predict(self, X) : | ||
+ | """ | ||
+ | make predictions using a trained linear classifier | ||
- | scores = np.dot(self.w, X) | + | Parameters |
- | return np.sign(scores) | + | ---------- |
+ | X : ndarray, shape (num_examples, n_features) | ||
+ | Training data. | ||
+ | """ | ||
+ | | ||
+ | scores = np.inner(self.w, X) | ||
+ | return np.sign(scores) | ||
def generate_separable_data(N) : | def generate_separable_data(N) : | ||
- | xA,yA,xB,yB = [np.random.uniform(-1, 1) for i in range(4)] | ||
w = np.random.uniform(-1, 1, 2) | w = np.random.uniform(-1, 1, 2) | ||
- | print w,w.shape | + | print (w,w.shape) |
X = np.random.uniform(-1, 1, [N, 2]) | X = np.random.uniform(-1, 1, [N, 2]) | ||
- | print X,X.shape | + | print (X,X.shape) |
y = np.sign(np.dot(X, w)) | y = np.sign(np.dot(X, w)) | ||
return X,y,w | return X,y,w | ||
Line 68: | Line 87: | ||
if __name__=='__main__' : | if __name__=='__main__' : | ||
- | X,y,w = generate_separable_data(20) | + | X,y,w = generate_separable_data(40) |
p = Perceptron() | p = Perceptron() | ||
p.fit(X,y) | p.fit(X,y) | ||
- | |||
</file> | </file> |