-
Notifications
You must be signed in to change notification settings - Fork 0
/
algorithm.py
379 lines (237 loc) · 9.99 KB
/
algorithm.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
377
378
379
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <[email protected]>
# Wed 17 Jun 2015 17:51:02 CEST
import logging
logger = logging.getLogger()
import numpy
import scipy.optimize
def make_labels(X):
"""Helper function that generates a single 1D numpy.ndarray with labels which
are good targets for stock logistic regression.
Parameters:
X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray
with 3 dimensions or an iterable containing 2 numpy.ndarrays with 2
dimensions each. Each correspond to the data for one of the two classes,
every row corresponds to one example of the data set, every column, one
different feature.
Returns:
numpy.ndarray: With a single dimension, containing suitable labels for all
rows and for all classes defined in X (depth).
"""
return numpy.hstack([k*numpy.ones(len(X[k]), dtype=int) for k in range(len(X))])
class Machine:
"""A class to handle all run-time aspects for Logistic Regression
Parameters:
theta (numpy.ndarray): A set of parameters for the Logistic Regression
model. This must be an iterable (or numpy.ndarray) with all parameters
for the model, including the bias term, which must be on entry 0 (the
first entry at the iterable).
"""
def __init__(self, theta):
self.theta = numpy.array(theta).copy()
def __call__(self, X):
"""Spits out the hypothesis given the data.
Parameters:
X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray
with 2 dimensions. Every row corresponds to one example of the data
set, every column, one different feature.
Returns:
numpy.ndarray: A 1D numpy.ndarray with as many entries as rows in the
input 2D array ``X``, representing g(x), the sigmoidal hypothesis.
"""
Xp = numpy.hstack((numpy.ones((len(X),1)), X)) #add bias term
return 1. / (1. + numpy.exp(-numpy.dot(Xp, self.theta)))
def predict(self, X):
"""Predicts the class of each row of X
Parameters:
X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray
with 2 dimensions. Every row corresponds to one example of the data
set, every column, one different feature.
Returns:
numpy.ndarray: A 1D numpy.ndarray with as many entries as rows in the
input 2D array ``X``, representing g(x), the class predictions for the
current machine.
"""
retval = self(X)
retval[retval<0.5] = 0.
retval[retval>=0.5] = 1.
return retval.astype(int)
def J(self, X, regularizer=0.0):
"""
Calculates the logistic regression cost
Parameters:
X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray
with 3 dimensions or an iterable containing 2 numpy.ndarrays with 2
dimensions each. Each correspond to the data for one of the two classes,
every row corresponds to one example of the data set, every column, one
different feature.
regularizer (float): A regularization parameter
Returns:
float: The averaged (regularized) cost for the whole dataset
"""
h = numpy.hstack([self(X[k]) for k in (0,1)])
y = make_labels(X)
logh = numpy.nan_to_num(numpy.log(h))
log1h = numpy.nan_to_num(numpy.log(1-h))
regularization_term = regularizer*(self.theta[1:]**2).sum()
main_term = -(y*logh + ((1-y)*log1h)).mean()
return main_term + regularization_term
def dJ(self, X, regularizer=0.0):
"""
Calculates the logistic regression first derivative of the cost w.r.t. each
parameter theta
Parameters:
X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray
with 3 dimensions or an iterable containing 2 numpy.ndarrays with 2
dimensions each. Each correspond to the data for one of the two classes,
every row corresponds to one example of the data set, every column, one
different feature.
regularizer (float): A regularization parameter, if the solution should
be regularized.
Returns:
numpy.ndarray: A 1D numpy.ndarray with as many entries as columns on the
input matrix ``X`` plus 1 (the bias term). It denotes the average
gradient of the cost w.r.t. to each machine parameter theta.
"""
Xflat = numpy.vstack([k for k in X])
Xp = numpy.hstack((numpy.ones((len(Xflat),1)), Xflat)) #add bias term
y = make_labels(X)
retval = ((self(Xflat) - y) * Xp.T).T.mean(axis=0)
retval[1:] += (regularizer*self.theta[1:])/len(X)
return retval
class Trainer:
"""A class to handle all training aspects for Logistic Regression
Parameters:
regularizer (float): A regularization parameter
"""
def __init__(self, regularizer=0.0):
self.regularizer = regularizer
def J(self, theta, machine, X):
"""
Calculates the vectorized cost *J*.
"""
machine.theta = theta
return machine.J(X, self.regularizer)
def dJ(self, theta, machine, X):
"""
Calculates the vectorized partial derivative of the cost *J* w.r.t. to
**all** :math:`\theta`'s. Use the training dataset.
"""
machine.theta = theta
return machine.dJ(X, self.regularizer)
def train(self, X):
"""
Optimizes the machine parameters to fit the input data, using
``scipy.optimize.fmin_l_bfgs_b``.
Parameters:
X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray
with 3 dimensions or an iterable containing 2 numpy.ndarrays with 2
dimensions each. Each correspond to the data for one of the two classes,
every row corresponds to one example of the data set, every column, one
different feature.
Returns:
Machine: A trained machine.
Raises:
RuntimeError: In case problems exist with the design matrix ``X`` or with
convergence.
"""
# check data dimensionality if not organized in a matrix
if not isinstance(X, numpy.ndarray):
baseline = X[0].shape[1]
for k in X:
if k.shape[1] != baseline:
raise RuntimeError("Mismatch on the dimensionality of input `X`")
# prepare the machine
theta0 = numpy.zeros(X[0].shape[1]+1) #include bias terms
machine = Machine(theta0)
logger.debug('Settings:')
logger.debug(' * initial guess = %s', [k for k in theta0])
logger.debug(' * cost (J) = %g', machine.J(X, self.regularizer))
logger.debug('Training using scipy.optimize.fmin_l_bfgs_b()...')
# Fill in the right parameters so that the minimization can take place
theta, cost, d = scipy.optimize.fmin_l_bfgs_b(
self.J,
theta0,
self.dJ,
(machine, X),
)
if d['warnflag'] == 0:
logger.info("** LBFGS converged successfuly **")
machine.theta = theta
logger.debug('Final settings:')
logger.debug(' * theta = %s', [k for k in theta])
logger.debug(' * cost (J) = %g', cost)
return machine
else:
message = "LBFGS did **not** converged:"
if d['warnflag'] == 1:
message += " Too many function evaluations"
elif d['warnflag'] == 2:
message += " %s" % d['task']
raise RuntimeError(message)
class MultiClassMachine:
"""A class to handle all run-time aspects for Multiclass Log. Regression
Parameters:
machines (iterable): An iterable over any number of machines that will be
stored.
"""
def __init__(self, machines):
self.machines = machines
def __call__(self, X):
"""Spits out the hypothesis for each machine given the data
Parameters:
X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray
with 2 dimensions. Every row corresponds to one example of the data
set, every column, one different feature.
Returns:
numpy.ndarray: A 2D numpy.ndarray with as many entries as rows in the
input 2D array ``X``, representing g(x), the sigmoidal hypothesis. Each
column on the output array represents the output of one of the logistic
regression machines in this
"""
return numpy.vstack([m(X) for m in self.machines]).T
def predict(self, X):
"""Predicts the class of each row of X
Parameters:
X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray
with 3 dimensions or an iterable containing 2 numpy.ndarrays with 2
dimensions each. Each correspond to the data for one of the two classes,
every row corresponds to one example of the data set, every column, one
different feature.
Returns:
numpy.ndarray: A 1D numpy.ndarray with as many entries as rows in the
input 2D array ``X``, representing g(x), the class predictions for the
current machine.
"""
return self(X).argmax(axis=1)
class MultiClassTrainer:
"""A class to handle all training aspects for Multiclass Log. Regression
Parameters:
regularizer (float): A regularization parameter
"""
def __init__(self, regularizer=0.0):
self.regularizer = regularizer
def train(self, X):
"""
Trains multiple logistic regression classifiers to handle the multiclass
problem posed by ``X``
X (numpy.ndarray): The input data matrix. This must be a numpy.ndarray
with 3 dimensions or an iterable containing 2 numpy.ndarrays with 2
dimensions each. Each correspond to the data for one of the input
classes, every row corresponds to one example of the data set, every
column, one different feature.
Returns:
Machine: A trained multiclass machine.
"""
_trainer = Trainer(self.regularizer)
if len(X) == 2: #trains and returns a single logistic regression classifer
return _trainer.train(X)
else: #trains and returns a multi-class logistic regression classifier
# use one-versus-all strategy
machines = []
for k in range(len(X)):
NC_range = range(0,k) + range(k+1,len(X))
Xp = numpy.array([numpy.vstack(X[NC_range]), X[k]])
machines.append(_trainer.train(Xp))
return MultiClassMachine(machines)