-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathlogistic.py
71 lines (53 loc) · 1.99 KB
/
logistic.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from __future__ import print_function, division
from builtins import range
# Note: you may need to update your version of future
# sudo pip install -U future
import numpy as np
import matplotlib.pyplot as plt
from util import getData, softmax, cost, y2indicator, error_rate
from sklearn.utils import shuffle
class LogisticModel(object):
def __init__(self):
pass
def fit(self, X, Y, Xvalid, Yvalid, learning_rate=1e-7, reg=0., epochs=10000, show_fig=False):
Tvalid = y2indicator(Yvalid)
N, D = X.shape
K = len(set(Y))
T = y2indicator(Y)
self.W = np.random.randn(D, K) / np.sqrt(D)
self.b = np.zeros(K)
costs = []
best_validation_error = 1
for i in range(epochs):
# forward propagation and cost calculation
pY = self.forward(X)
# gradient descent step
self.W -= learning_rate*(X.T.dot(pY - T) + reg*self.W)
self.b -= learning_rate*((pY - T).sum(axis=0) + reg*self.b)
if i % 10 == 0:
pYvalid = self.forward(Xvalid)
c = cost(Tvalid, pYvalid)
costs.append(c)
e = error_rate(Yvalid, np.argmax(pYvalid, axis=1))
print("i:", i, "cost:", c, "error:", e)
if e < best_validation_error:
best_validation_error = e
print("best_validation_error:", best_validation_error)
if show_fig:
plt.plot(costs)
plt.show()
def forward(self, X):
return softmax(X.dot(self.W) + self.b)
def predict(self, X):
pY = self.forward(X)
return np.argmax(pY, axis=1)
def score(self, X, Y):
prediction = self.predict(X)
return 1 - error_rate(Y, prediction)
def main():
Xtrain, Ytrain, Xvalid, Yvalid = getData()
model = LogisticModel()
model.fit(Xtrain, Ytrain, Xvalid, Yvalid, show_fig=True)
print(model.score(Xvalid, Yvalid))
if __name__ == '__main__':
main()