-
Notifications
You must be signed in to change notification settings - Fork 3
/
losgisticRegression.py
378 lines (323 loc) · 12.4 KB
/
losgisticRegression.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 30 18:25:46 2019
@author: kenneth
"""
import numpy as np
class Logistic():
def __init__(self):
return
#classification metrics
'''
Actual
+ve -ve
---------------------
+ve | TP | FP | +---> Precision
--------------------- |
predicted -ve | FN | TN | v
--------------------- Recall
'''
def TP(self, A, P):
'''Docstring
when actual is 1 and prediction is 1
:params: A: Actual label
:params: P: predicted labels
'''
return np.sum((A == 1) & (P == 1))
def FP(self, A, P):
'''Docstring
when actual is 0 and prediction is 1
:params: A: Actual label
:params: P: predicted labels
'''
return np.sum((A == 0) & (P == 1))
def FN(self, A, P):
'''Docstring
when actual is 1 and prediction is 0
:params: A: Actual label
:params: P: predicted labels
'''
return np.sum((A == 1) & (P == 0))
def TN(self, A, P):
'''Docstring
when actual is 0 and prediction is 0
:params: A: Actual label
:params: P: predicted labels
'''
return np.sum((A == 0) & (P == 0))
def confusionMatrix(self, A, P):
'''Docstring
:params: A: Actual label
:params: P: predicted labels
'''
TP, FP, FN, TN = (self.TP(A, P),\
self.FP(A, P),\
self.FN(A, P),\
self.TN(A, P))
return np.array([[TP, FP], [FN, TN]])
def accuracy(self, A, P):
'''Docstring
:params: A: Actual label
:params: P: predicted labels
Also: Accuracy np.mean(Y == model.predict(X))
'''
return (self.TP(A, P) + self.TN(A, P))/(self.TP(A, P) + self.FP(A, P) +\
self.FN(A, P) + self.TN(A, P))
def precision(self, A, P):
'''Docstring
:params: A: Actual label
:params: P: predicted labels
'''
return self.TP(A, P)/(self.TP(A, P) + self.FP(A, P))
def recall(self, A, P):
'''Docstring
:params: A: Actual label
:params: P: predicted labels
'''
return self.TP(A, P)/(self.TP(A, P) + self.FN(A, P))
def TPR(self, A, P):
'''Docstring
True Positive rate:
True Positive Rate corresponds to the
proportion of positive data points that
are correctly considered as positive,
with respect to all positive data points.
:params: A: Actual label
:params: P: predicted labels
'''
return self.recall(A, P)
def FPR(self, A, P):
'''Docstring
False Positive rate:
False Positive Rate corresponds to the
proportion of negative data points that
are mistakenly considered as positive,
with respect to all negative data points.
:params: A: Actual label
:params: P: predicted labels
'''
return self.FP(A, P)/(self.FP(A, P) + self.TN(A, P))
def TNR(self, A, P):
'''Docstring
True Negative Rate
'''
return self.TN(A, P)/(self.TN(A, P) + self.FP(A, P))
def f1(self, A, P):
'''Docstring
:params: A: Actual label
:params: P: predicted labels
'''
return (2 * (self.precision(A, P) * self.recall(A, P)))/(self.precision(A, P) + self.recall(A, P))
def summary(self, A, P):
print('*'*40)
print('\t\tSummary')
print('*'*40)
print('>> Accuracy: %s'%self.accuracy(A, P))
print('>> Precision: %s'%self.precision(A, P))
print('>> Recall: %s'%self.recall(A, P))
print('>> F1-score: %s'%self.f1(A, P))
print('>> True positive rate: %s'%self.TPR(A, P))
print('>> False positive rate: %s'%self.FPR(A, P))
print('*'*40)
@staticmethod
def sigmoid(X, beta):
'''Docstring
:params: X: features N x (M+1)
:params: beta: weights N x 1
'''
return 1/(1 + np.exp(-(np.dot(X, beta))))
@staticmethod
def cost(X, Y, beta):
'''Docstring
:params: X: features N x (M+1)
:params: Y: label y \in {0,1} N x 1 dimension
:params: beta: weights N x 1
'''
return -(1/len(Y)) * np.sum((Y*np.log(Logistic.sigmoid(X, beta))) + ((1 - Y)*np.log(1 - Logistic.sigmoid(X, beta))))
def fit(self, X, Y, alpha, iterations):
self.alpha = alpha
self.iterations = iterations
self.beta = np.zeros(X.shape[1])
self.cost_rec = np.zeros(self.iterations)
self.beta_rec = np.zeros((self.iterations, X.shape[1]))
for ii in range(self.iterations):
#compute gradient
self.beta = self.beta + (1/len(Y)) *(self.alpha) * X.T.dot(Y - Logistic.sigmoid(X, self.beta))
self.beta_rec[ii, :] = self.beta.T
self.cost_rec[ii] = self.cost(X, Y, self.beta)
print('*'*40)
print('%s iteratiion, cost = %s'%(ii, self.cost_rec[ii]))
return self
def predict(self, X):
'''
param: X_test = NxD feature matrix
'''
y_pred = np.zeros(X.shape[0])
for ii in range(len(y_pred)):
if Logistic.sigmoid(X[ii], self.beta) > 0.5:
y_pred[ii] = 1
return y_pred
class RegularizedLogit(Logistic):
def __init__(self, lamda):
super().__init__()
self.lamda = lamda
return
def cost(self, X, Y, beta):
'''Docstring
:params: X: features N x (M+1)
:params: Y: label y \in {0,1} N x 1 dimension
:params: beta: weights N x 1
'''
return -(1/len(Y)) * (np.sum((Y*np.log(Logistic.sigmoid(X, beta))) + ((1 - Y)*np.log(1 - Logistic.sigmoid(X, beta)))) +\
((self.lamda/2)*np.sum(np.square(beta))))
def fit(self, X, Y, alpha, iterations):
self.alpha = alpha
self.iterations = iterations
self.beta = np.zeros(X.shape[1])
self.cost_rec = np.zeros(self.iterations)
self.beta_rec = np.zeros((self.iterations, X.shape[1]))
for ii in range(self.iterations):
#compute gradient
self.beta = self.beta + (1/len(Y)) *(self.alpha) * (X.T.dot(Y - Logistic.sigmoid(X, self.beta)) +\
((self.lamda/len(Y))*self.beta))
self.beta_rec[ii, :] = self.beta.T
self.cost_rec[ii] = self.cost(X, Y, self.beta)
print('*'*40)
print('%s iteratiion, cost = %s'%(ii, self.cost_rec[ii]))
return self
def predict(self, X):
'''
param: X_test = NxD feature matrix
'''
y_pred = np.zeros(X.shape[0])
for ii in range(len(y_pred)):
if Logistic.sigmoid(X[ii], self.beta) > 0.5:
y_pred[ii] = 1
return y_pred
class stochasticLogistic(Logistic):
def __init__(self, alpha, iterations):
super().__init__()
self.alpha = alpha
self.iterations = iterations
return
@staticmethod
def sigmoid(X, beta):
'''Docstring
:params: X: features N x (M+1)
:params: beta: weights N x 1
'''
return 1/(1 + np.exp(-(np.dot(X, beta))))
@staticmethod
def cost(X, Y, beta):
'''Docstring
:params: X: features N x (M+1)
:params: Y: label y \in {0,1} N x 1 dimension
:params: beta: weights N x 1
'''
return -(1/len(Y)) * np.sum((Y*np.log(stochasticLogistic.sigmoid(X, beta))) +\
((1 - Y)*np.log(1 - stochasticLogistic.sigmoid(X, beta))))
def fit(self, X, Y):
self.beta = np.zeros(X.shape[1])
self.cost_rec = np.zeros(self.iterations)
self.beta_rec = np.zeros((self.iterations, X.shape[1]))
ylen = len(Y)
for ii in range(self.iterations):
#compute stochastic gradient
sampledCost = []
for ij in range(ylen):
random_samples = np.random.randint(1, ylen)
X_samp = X[:random_samples]
Y_samp = Y[:random_samples]
self.beta = self.beta + (1/len(Y_samp)) *(self.alpha) * X_samp.T.dot(Y_samp - stochasticLogistic.sigmoid(X_samp, self.beta))
self.beta_rec[ii, :] = self.beta.T
sampledCost.append(self.cost(X_samp, Y_samp, self.beta))
self.cost_rec[ii] = np.average(sampledCost)
print('*'*40)
print('%s iteratiion, cost = %s'%(ii, self.cost_rec[ii]))
return self
def predict(self, X):
'''
param: X_test = NxD feature matrix
'''
y_pred = np.zeros(X.shape[0])
for ii in range(len(y_pred)):
if stochasticLogistic.sigmoid(X[ii], self.beta) > 0.5:
y_pred[ii] = 1
return y_pred
class minibatchLogistic(Logistic):
def __init__(self, alpha, iterations):
super().__init__()
self.alpha = alpha
self.iterations = iterations
return
@staticmethod
def sigmoid(X, beta):
'''Docstring
:params: X: features N x (M+1)
:params: beta: weights N x 1
'''
return 1/(1 + np.exp(-(np.dot(X, beta))))
@staticmethod
def cost(X, Y, beta):
'''Docstring
:params: X: features N x (M+1)
:params: Y: label y \in {0,1} N x 1 dimension
:params: beta: weights N x 1
'''
return -(1/len(Y)) * np.sum((Y*np.log(minibatchLogistic.sigmoid(X, beta))) +\
((1 - Y)*np.log(1 - minibatchLogistic.sigmoid(X, beta))))
def fit(self, X, Y, batchSize = None):
self.beta = np.zeros(X.shape[1])
self.cost_rec = np.zeros(self.iterations)
self.beta_rec = np.zeros((self.iterations, X.shape[1]))
ylen = len(Y)
batchNumber = int(ylen/batchSize)
for ii in range(self.iterations):
#compute minibatch gradient
sampledCost = []
random_samples = np.random.permutation(ylen)
X_random = X[random_samples]
Y_random = Y[random_samples]
for ij in range(0, ylen, batchNumber):
X_samp = X_random[ij:ij+batchSize]
Y_samp = Y_random[ij:ij+batchSize]
self.beta = self.beta + (1/len(Y_samp)) *(self.alpha) * X_samp.T.dot(Y_samp - minibatchLogistic.sigmoid(X_samp, self.beta))
self.beta_rec[ii, :] = self.beta.T
sampledCost.append(self.cost(X_samp, Y_samp, self.beta))
self.cost_rec[ii] = np.average(sampledCost)
print('*'*40)
print('%s iteratiion, cost = %s'%(ii, self.cost_rec[ii]))
return self
def predict(self, X):
'''
param: X_test = NxD feature matrix
'''
y_pred = np.zeros(X.shape[0])
for ii in range(len(y_pred)):
if minibatchLogistic.sigmoid(X[ii], self.beta) > 0.5:
y_pred[ii] = 1
return y_pred
#%%
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
X, y = make_blobs(n_samples=100, centers=2, n_features=2 )
X = np.c_[np.ones(X.shape[0]), X]
X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size = 0.3)
logit = Logistic().fit(X_train, Y_train, 0.1, 100)
plt.scatter(X_train[:, 0], X_train[:, 1], c = logit.predict(X_train))
y_pred = logit.predict(X_test)
logit.summary(Y_test, y_pred)
logit.confusionMatrix(Y_test, y_pred)
plt.plot(np.arange(len(logit.cost_rec)), logit.cost_rec)
stlog = stochasticLogistic(alpha=0.1, iterations=100).fit(X_train, Y_train)
y_pred = stlog.predict(X_test)
stlog.summary(Y_test, y_pred)
stlog.confusionMatrix(Y_test, y_pred)
plt.scatter(X_train[:, 0], X_train[:, 1], c = stlog.predict(X_train))
plt.plot(np.arange(len(stlog.cost_rec)), stlog.cost_rec)
minilog = minibatchLogistic(alpha=0.1, iterations=100).fit(X_test, Y_test, batchSize= 10)
y_pred = minilog.predict(X_test)
minilog.summary(Y_test, y_pred)
minilog.confusionMatrix(Y_test, y_pred)