Repository navigation
Expand file tree
/
Copy pathmodules.py
More file actions
270 lines (213 loc) · 7.89 KB
/
Copy pathmodules.py
File metadata and controls
270 lines (213 loc) · 7.89 KB
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
import numpy as np
from base_module import BaseModule
class L2(BaseModule):
"""
Class representing the L2 module
Represents the function: f(w)=||w||^2_2
"""
def __init__(self, weights: np.ndarray = None):
"""
Initialize a module instance
Parameters:
----------
weights: np.ndarray, default=None
Initial value of weights
"""
super().__init__(weights)
def compute_output(self, **kwargs) -> np.ndarray:
"""
Compute the output value of the L2 function at point self.weights
Parameters
----------
kwargs:
No additional arguments are expected
Returns
-------
output: ndarray of shape (1,)
Value of function at point self.weights
"""
return np.power(np.linalg.norm(self.weights, ord=2), 2)
def compute_jacobian(self, **kwargs) -> np.ndarray:
"""
Compute L2 derivative with respect to self.weights at point self.weights
Parameters
----------
kwargs:
No additional arguments are expected
Returns
-------
output: ndarray of shape (n_in,)
L2 derivative with respect to self.weights at point self.weights
"""
return self.weights * 2
class L1(BaseModule):
def __init__(self, weights: np.ndarray = None):
"""
Initialize a module instance
Parameters:
----------
weights: np.ndarray, default=None
Initial value of weights
"""
super().__init__(weights)
def compute_output(self, **kwargs) -> np.ndarray:
"""
Compute the output value of the L1 function at point self.weights
Parameters
----------
kwargs:
No additional arguments are expected
Returns
-------
output: ndarray of shape (1,)
Value of function at point self.weights
"""
return np.linalg.norm(self.weights, ord=1)
def compute_jacobian(self, **kwargs) -> np.ndarray:
"""
Compute L1 derivative with respect to self.weights at point self.weights
Parameters
----------
kwargs:
No additional arguments are expected
Returns
-------
output: ndarray of shape (n_in,)
L1 derivative with respect to self.weights at point self.weights
"""
return np.sign(self.weights)
class LogisticModule(BaseModule):
"""
Class representing the logistic regression objective function
Represents the function: f(w) = - (1/m) sum_i^m[y*<x_i,w> - log(1+exp(<x_i,w>))]
"""
def __init__(self, weights: np.ndarray = None):
"""
Initialize a logistic regression module instance
Parameters:
----------
weights: np.ndarray, default=None
Initial value of weights
"""
super().__init__(weights)
def compute_output(self, X: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:
"""
Compute the output value of the logistic regression objective function at point self.weights
Parameters
----------
X: ndarray of shape (n_samples, n_features)
Design matrix to use when computing objective
y: ndarray of shape(n_samples,)
Binary labels of samples to use when computing objective
Returns
-------
output: ndarray of shape (1,)
Value of function at point self.weights
"""
summ = np.sum((y * (X @ self.weights)) - np.log(1 + np.exp(X @ self.weights)))
return -summ / len(X)
def compute_jacobian(self, X: np.ndarray, y: np.ndarray, **kwargs) -> np.ndarray:
"""
Compute the gradient of the logistic regression objective function at point self.weights
Parameters
----------
X: ndarray of shape (n_samples, n_features)
Design matrix to use when computing objective
y: ndarray of shape(n_samples,)
Binary labels of samples to use when computing objective
Returns
-------
output: ndarray of shape (n_features,)
Derivative of function with respect to self.weights at point self.weights
"""
exp_res = np.exp(X @ self.weights)
jac_sum = (y @ X) - (exp_res / (1 + exp_res)) @ X
return -jac_sum / len(X)
class RegularizedModule(BaseModule):
"""
Class representing a general regularized objective function of the format:
f(w) = F(w) + lambda*R(w)
for F(w) being some fidelity function, R(w) some regularization function and lambda
the regularization parameter
"""
def __init__(self,
fidelity_module: BaseModule,
regularization_module: BaseModule,
lam: float = 1.,
weights: np.ndarray = None,
include_intercept: bool = True):
"""
Initialize a regularized objective module instance
Parameters:
-----------
fidelity_module: BaseModule
Module to be used as a fidelity term
regularization_module: BaseModule
Module to be used as a regularization term
lam: float, default=1
Value of regularization parameter
weights: np.ndarray, default=None
Initial value of weights
include_intercept: bool default=True
Should fidelity term (and not regularization term) include an intercept or not
"""
super().__init__()
self.fidelity_module_, self.regularization_module_, self.lam_ = fidelity_module, regularization_module, lam
self.include_intercept_ = include_intercept
if weights is not None:
self.weights = weights
def compute_output(self, **kwargs) -> np.ndarray:
"""
Compute the output value of the regularized objective function at point self.weights
Parameters
----------
kwargs:
No additional arguments are expected
Returns
-------
output: ndarray of shape (1,)
Value of function at point self.weights
"""
fid_output = self.fidelity_module_.compute_output(**kwargs)
reg_output = 0 if self.regularization_module_ is None else \
self.regularization_module_.compute_output(**kwargs)
return fid_output + self.lam_ * reg_output
def compute_jacobian(self, **kwargs) -> np.ndarray:
"""
Compute module derivative with respect to self.weights at point self.weights
Parameters
----------
kwargs:
No additional arguments are expected
Returns
-------
output: ndarray of shape (n_in,)
Derivative with respect to self.weights at point self.weights
"""
fid_jac = self.fidelity_module_.compute_jacobian(**kwargs)
reg_jac = 0 if self.regularization_module_ is None else \
self.regularization_module_.compute_jacobian(**kwargs)
return fid_jac + self.lam_ * reg_jac
@property
def weights(self):
"""
Wrapper property to retrieve module parameter
Returns
-------
weights: ndarray of shape (n_in, n_out)
"""
return self.fidelity_module_.weights
@weights.setter
def weights(self, weights: np.ndarray) -> None:
"""
Setter function for module parameters
In case self.include_intercept_ is set to True, weights[0] is regarded as the intercept
and is not passed to the regularization module
Parameters
----------
weights: ndarray of shape (n_in, n_out)
Weights to set for module
"""
inc_int = int(self.include_intercept_)
self.fidelity_module_.weights = weights
self.regularization_module_.weights = np.r_[np.zeros(inc_int), weights[inc_int:]]