-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathpocket.py
47 lines (40 loc) · 1.28 KB
/
pocket.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import numpy as np
import metrics
class Pocket:
def fit(self, X, y, epochs):
'''
Parameters
----------
X : shape (n_samples, n_features)
Training data
y : shape (n_samples,)
Target values, 1 or -1
epochs : The number of epochs
'''
n_features = X.shape[1]
self.__W = np.zeros(n_features)
self.__b = 0
accuracy = 0
for _ in range(epochs):
h = self.predict(X)
error_index = np.random.choice(np.flatnonzero(y != h))
W_tmp = self.__W + (y[error_index] * X[error_index]).reshape(self.__W.shape)
b_tmp = self.__b + y[error_index]
h = np.sign(X.dot(W_tmp) + b_tmp)
accuracy_tmp = metrics.accuracy(y, h)
if accuracy_tmp > accuracy:
accuracy = accuracy_tmp
self.__W = W_tmp
self.__b = b_tmp
def predict(self, X):
'''
Parameters
----------
X : shape (n_samples, n_features)
Predicting data
Returns
-------
y : shape (n_samples,)
Predicted class label per sample, 1 or -1
'''
return np.sign(X.dot(self.__W) + self.__b)