-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
339 lines (280 loc) · 8.47 KB
/
models.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
import numpy
import numpy as np
import random
from numpy import linalg as LA
from tqdm import tqdm
def buildPCI(X: numpy.ndarray, y: numpy.ndarray, w: numpy.ndarray) -> tuple:
"""
Builds a set of misclassified points (PCI) based on the current
weight vector.
Parameters
----------
X : numpy.ndarray
A matrix containing the input data.
y : numpy.ndarray
A vector containing the target labels (+1 or -1).
w : numpy.ndarray
A vector containing the weights of the linear classifier.
Returns
-------
Tuple(numpy.ndarray, numpy.ndarray)
A tuple containing the set of misclassified points and
corresponding labels.
"""
h = np.sign(X.dot(w))
bool_index = (h != y)
PCI = X[bool_index]
Y = y[bool_index]
return np.array(PCI), np.array(Y)
class PocketPLA():
"""
A class that implements the Pocket Perceptron Learning Algorithm
(PLA) for binary classification.
Attributes
----------
w : numpy.ndarray
The weight vector of the classifier.
n_iter : int
The number of iterations to run the algorithm.
"""
def __init__(self, n_iter):
self.w = None
self.n_iter = n_iter
def set_w(self, w: numpy.ndarray):
"""
Sets the weight vector.
Parameters
----------
w : numpy.ndarray
The weight vector.
"""
self.w = w
def fit(self, X: numpy.ndarray, y: numpy.ndarray):
"""
Fits the classifier to the given data and labels using the
pocket PLA algorithm.
Parameters
----------
X : numpy.ndarray
An array of that contains the data points.
y : numpy.ndarray
An array that contains the labels (-1 or 1) for each data
point.
"""
PCI = X.copy()
orig_y = y.copy()
if self.w is None:
self.w = np.zeros(X.shape[1])
best_w = self.w
best_error = len(y)
for _ in tqdm(range(self.n_iter)):
if len(PCI) == 0:
break
rand_index = np.random.randint(len(PCI))
x = PCI[rand_index]
self.w += y[rand_index] * x
PCI, y = buildPCI(X, orig_y, self.w)
error = len(PCI)
if error < best_error:
best_error = error
best_w = self.w
self.w = best_w
def predict(self, X: numpy.ndarray):
"""
Predicts the labels for the given data using the weight vector.
Parameters
----------
X : numpy.ndarray
An array that contains the data points.
Returns
-------
numpy.ndarray
An array that contains the predicted labels (-1 or 1) for
each data point.
"""
return np.sign(X.dot(self.w))
def get_w(self):
"""
Returns the weight vector.
Returns
----------
w : numpy.ndarray
The weight vector.
"""
return self.w
class LinearRegression:
"""
A class that implements the linear regression algorithm for binary
classification.
Attributes
----------
w : numpy.ndarray
The weight vector of the classifier.
"""
def fit(self, X: numpy.ndarray, y: numpy.ndarray):
"""
Fits the classifier to the given data and labels using the
pseudo inverse of X
Parameters
----------
X : numpy.ndarray
An array that contains the data points.
y : numpy.ndarray
An array that contains the labels (-1 or 1) for each data
point.
Returns
-------
w : numpy.ndarray
The weight vector of the classifier.
"""
XTX_inv = np.linalg.inv(X.T.dot(X))
pseudo_inv = XTX_inv.dot(X.T)
self.w = pseudo_inv.dot(y)
return self.w
def predict(self, X: numpy.ndarray):
"""
Predicts the label for a given data point using the weight vector.
Parameters
----------
X : numpy.ndarray
An array that contains the data point.
Returns
-------
int
The predicted label (-1 or 1) for the data point.
"""
x = np.array(X)
return np.sign(x.dot(self.w))
def get_w(self):
"""
Returns the weight vector.
Returns
----------
w : numpy.ndarray
The weight vector.
"""
return self.w
def set_w(self, w: numpy.ndarray):
"""
Sets the weight vector.
Parameters
----------
w : numpy.ndarray
The weight vector.
"""
self.w = w
class LogisticRegression:
"""
A class that implements the logistic regression algorithm for binary
classification.
Parameters
----------
eta : float, optional
The learning rate for the gradient descent algorithm
(default is 0.1).
tmax : int, optional
The maximum number of iterations for the gradient descent
algorithm (default is 1000).
batch_size : int, optional
The size of the mini-batch for the stochastic gradient descent
algorithm (default is 1000000).
Attributes
----------
eta : float
The learning rate for the gradient descent algorithm.
tmax : int
The maximum number of iterations for the gradient descent
algorithm.
batch_size : int
The size of the mini-batch for the stochastic gradient descent
algorithm.
w : numpy.ndarray
The weight vector of the classifier.
"""
def __init__(self, eta=0.1, tmax=1000, batch_size=1000000, validation_lambda=0):
self.eta = eta
self.tmax = tmax
self.batch_size = batch_size
self.validation_lambda = validation_lambda
def fit(self, X: numpy.ndarray, y: numpy.ndarray):
"""
Fits the classifier to the given data and labels using the
stochastic gradient descent algorithm depending on the size of
batch.
Parameters
----------
X : numpy.ndarray
An array that contains the data points.
y : numpy.ndarray
An array that contains the labels (-1 or 1) for each data
point.
"""
N = X.shape[0]
d = X.shape[1]
w = np.zeros(d)
for _ in tqdm(range(int(self.tmax))):
if self.batch_size < N:
indexes = random.sample(range(N), self.batch_size)
X_ = X[indexes]
y_ = y[indexes]
N_ = self.batch_size
else:
X_ = X
y_ = y
N_ = N
yhat = (w @ X_.T).reshape(-1, 1)
y_ = y_.reshape(-1, 1)
grad = (-1/N_ * np.sum((y_ * X_) / (1 + np.exp(y_ * yhat)), axis=0)) + (2 * self.validation_lambda * w)
if LA.norm(grad) < 1e-6:
break
w -= self.eta*grad
self.w = w
def predict_prob(self, X: numpy.ndarray):
"""
Predicts the probability of the class for the given data using
the weight vector.
Parameters
----------
X : numpy.ndarray
An array that contains the data points.
Returns
-------
numpy.ndarray
An array that contains the predicted probabilities for each
data point.
"""
return np.array([(1 / (1 + np.exp( -(self.w.dot(x)) ))) for x in X])
def predict(self, X: numpy.ndarray):
"""
Predicts the labels for the given data using a threshold of 0.5
on the probabilities.
Parameters
----------
X : numpy.ndarray
An array that contains the data points.
Returns
-------
numpy.ndarray
An array that contains the predicted labels (-1 or 1) for
each data point.
"""
pred = self.predict_prob(X)
return np.where(pred >= 0.5, 1, -1)
def get_w(self):
"""
Returns the weight vector.
Returns
----------
w : numpy.ndarray
The weight vector.
"""
return self.w
def set_w(self, w: list):
"""
Sets the weight vector.
Parameters
----------
w : numpy.ndarray
The weight vector.
"""
self.w = w