forked from lazyprogrammer/machine_learning_examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.py
240 lines (187 loc) · 5.69 KB
/
util.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# Some utility functions we need for the class.
# For the class Data Science: Practical Deep Learning Concepts in Theano and TensorFLow
# https://www.udemy.com/data-science-deep-learning-in-theano-tensorflow
# Note: run this from the current folder it is in.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
def get_transformed_data():
print "Reading in and transforming data..."
df = pd.read_csv('../large_files/train.csv')
data = df.as_matrix().astype(np.float32)
np.random.shuffle(data)
X = data[:, 1:]
mu = X.mean(axis=0)
X = X - mu # center the data
pca = PCA()
Z = pca.fit_transform(X)
Y = data[:, 0]
return Z, Y, pca, mu
def get_normalized_data():
print "Reading in and transforming data..."
df = pd.read_csv('../large_files/train.csv')
data = df.as_matrix().astype(np.float32)
np.random.shuffle(data)
X = data[:, 1:]
mu = X.mean(axis=0)
std = X.std(axis=0)
np.place(std, std == 0, 1)
X = (X - mu) / std # normalize the data
Y = data[:, 0]
return X, Y
def plot_cumulative_variance(pca):
P = []
for p in pca.explained_variance_ratio_:
if len(P) == 0:
P.append(p)
else:
P.append(p + P[-1])
plt.plot(P)
plt.show()
return P
def forward(X, W, b):
# softmax
a = X.dot(W) + b
# print "any nan in X?:", np.any(np.isnan(X))
# print "any nan in W?:", np.any(np.isnan(W))
# print "W:", W
# print "X.dot(W):", X.dot(W)
# print "b:", b
# print "a:", a
expa = np.exp(a)
# print "expa:", expa
y = expa / expa.sum(axis=1, keepdims=True)
# exit()
return y
def predict(p_y):
return np.argmax(p_y, axis=1)
def error_rate(p_y, t):
prediction = predict(p_y)
return np.mean(prediction != t)
def cost(p_y, t):
# print "any nan in log p_y?:", np.any(np.isnan(np.log(p_y)))
# print "log(p_y):", np.log(p_y)
# exit()
tot = t * np.log(p_y)
return -tot.sum()
def gradW(t, y, X):
return X.T.dot(t - y)
def gradb(t, y):
return (t - y).sum(axis=0)
def y2indicator(y):
N = len(y)
ind = np.zeros((N, 10))
for i in xrange(N):
ind[i, y[i]] = 1
return ind
def benchmark_full():
X, Y = get_normalized_data()
print "Performing logistic regression..."
# lr = LogisticRegression(solver='lbfgs')
# # test on the last 1000 points
# lr.fit(X[:-1000, :200], Y[:-1000]) # use only first 200 dimensions
# print lr.score(X[-1000:, :200], Y[-1000:])
# print "X:", X
# normalize X first
# mu = X.mean(axis=0)
# std = X.std(axis=0)
# X = (X - mu) / std
Xtrain = X[:-1000,]
Ytrain = Y[:-1000]
Xtest = X[-1000:,]
Ytest = Y[-1000:]
# convert Ytrain and Ytest to (N x K) matrices of indicator variables
N, D = Xtrain.shape
Ytrain_ind = y2indicator(Ytrain)
Ytest_ind = y2indicator(Ytest)
W = np.random.randn(D, 10) / 28
b = np.zeros(10)
LL = []
LLtest = []
CRtest = []
# reg = 1
# learning rate 0.0001 is too high, 0.00005 is also too high
# 0.00003 / 2000 iterations => 0.363 error, -7630 cost
# 0.00004 / 1000 iterations => 0.295 error, -7902 cost
# 0.00004 / 2000 iterations => 0.321 error, -7528 cost
# reg = 0.1, still around 0.31 error
# reg = 0.01, still around 0.31 error
lr = 0.00004
reg = 0.01
for i in xrange(500):
p_y = forward(Xtrain, W, b)
# print "p_y:", p_y
ll = cost(p_y, Ytrain_ind)
LL.append(ll)
p_y_test = forward(Xtest, W, b)
lltest = cost(p_y_test, Ytest_ind)
LLtest.append(lltest)
err = error_rate(p_y_test, Ytest)
CRtest.append(err)
W += lr*(gradW(Ytrain_ind, p_y, Xtrain) - reg*W)
b += lr*(gradb(Ytrain_ind, p_y) - reg*b)
if i % 10 == 0:
print "Cost at iteration %d: %.6f" % (i, ll)
print "Error rate:", err
p_y = forward(Xtest, W, b)
print "Final error rate:", error_rate(p_y, Ytest)
iters = range(len(LL))
plt.plot(iters, LL, iters, LLtest)
plt.show()
plt.plot(CRtest)
plt.show()
def benchmark_pca():
X, Y, _, _ = get_transformed_data()
X = X[:, :300]
# normalize X first
mu = X.mean(axis=0)
std = X.std(axis=0)
X = (X - mu) / std
print "Performing logistic regression..."
Xtrain = X[:-1000,]
Ytrain = Y[:-1000]
Xtest = X[-1000:,]
Ytest = Y[-1000:]
N, D = Xtrain.shape
Ytrain_ind = np.zeros((N, 10))
for i in xrange(N):
Ytrain_ind[i, Ytrain[i]] = 1
Ntest = len(Ytest)
Ytest_ind = np.zeros((Ntest, 10))
for i in xrange(Ntest):
Ytest_ind[i, Ytest[i]] = 1
W = np.random.randn(D, 10) / 28
b = np.zeros(10)
LL = []
LLtest = []
CRtest = []
# D = 300 -> error = 0.07
lr = 0.0001
reg = 0.01
for i in xrange(200):
p_y = forward(Xtrain, W, b)
# print "p_y:", p_y
ll = cost(p_y, Ytrain_ind)
LL.append(ll)
p_y_test = forward(Xtest, W, b)
lltest = cost(p_y_test, Ytest_ind)
LLtest.append(lltest)
err = error_rate(p_y_test, Ytest)
CRtest.append(err)
W += lr*(gradW(Ytrain_ind, p_y, Xtrain) - reg*W)
b += lr*(gradb(Ytrain_ind, p_y) - reg*b)
if i % 10 == 0:
print "Cost at iteration %d: %.6f" % (i, ll)
print "Error rate:", err
p_y = forward(Xtest, W, b)
print "Final error rate:", error_rate(p_y, Ytest)
iters = range(len(LL))
plt.plot(iters, LL, iters, LLtest)
plt.show()
plt.plot(CRtest)
plt.show()
if __name__ == '__main__':
benchmark_pca()
# benchmark_full()