-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathado.py
258 lines (206 loc) · 8.37 KB
/
ado.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
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 27 13:57:14 2020
@author: sun.fa
"""
import numpy as np
# =========================================
# sparsity-promoting optimiazations
# =========================================
def FTRidge(X0, y, lam, maxit, tol, Mreg, normalize = 2, print_results = True):
"""
This function is a single iteration of FTRidge
"""
n, d = X0.shape
X = np.zeros((n, d))
# First normalize data
if normalize != 0:
Mreg = np.zeros(d)
for i in range(0, d):
Mreg[i] = 1.0 / (np.linalg.norm(X0[:, i],normalize))
X[:, i] = Mreg[i] * X0[:, i]
else: X = X0
# Get the standard ridge esitmate
w = np.linalg.lstsq(X.T.dot(X) + lam * np.eye(d), X.T.dot(y))[0]
num_relevant = d
biginds = np.where(abs(np.multiply(Mreg, w)) > tol)[0]
# Threshold and continue
for j in range(maxit):
# Figure out which items to cut out
smallinds = np.where(abs(np.multiply(Mreg, w)) < tol)[0]
new_biginds = [i for i in range(d) if i not in smallinds]
# If nothing changes then stop
if num_relevant == len(new_biginds): break
else: num_relevant = len(new_biginds)
# Also make sure we didn't just lose all the coefficients
if len(new_biginds) == 0:
if j == 0:
if print_results: print("Tolerance too high - all coefficients set below tolerance")
return w
else: break
biginds = new_biginds
# Otherwise get a new guess
w[smallinds] = 0
if lam != 0:
w[biginds] = np.linalg.lstsq(X[:, biginds].T.dot(X[:, biginds]) +
lam * np.eye(len(biginds)), X[:, biginds].T.dot(y))[0]
else:
w[biginds] = np.linalg.lstsq(X[:, biginds], y)[0]
# Now that we have the sparsity pattern, use standard least squares to get w
if biginds != []: w[biginds] = np.linalg.lstsq(X[:, biginds], y)[0]
if normalize != 0:
return np.multiply(Mreg, w)
else: return w
def TrainFTRidge(R0, Ut, tol, lam, eta, maxit = 200, FTR_iters = 10, l0_penalty = None, normalize = 0, split = 0.8,
print_best_tol = False, plot_loss = False):
"""
This function trains a predictor using FTRidge.
It runs over different values of tolerance and trains predictors on a training set, then evaluates them
using a loss function on a holdout set.
R is Phi (evaluation of basis functions)
Ut is f (simulation of the derivatives)
"""
n,d = R0.shape
R = np.zeros((n,d), dtype=np.float32)
if normalize != 0:
Mreg = np.zeros(d)
for i in range(0,d):
Mreg[i] = 1.0 / (np.linalg.norm(R0[:,i],normalize))
R[:,i] = Mreg[i] * R0[:,i]
normalize_inner = 0
else:
R = R0
Mreg = np.ones(d)
normalize_inner = 2
# Split data into 80% training and 20% test, then search for the best tolderance.
np.random.seed(0) # for consistancy
n,_ = R.shape
train = np.random.choice(n, int(n*split), replace = False)
test = [i for i in np.arange(n) if i not in train]
TrainR = R[train,:]
TestR = R[test,:]
TrainY = Ut[train]
TestY = Ut[test]
# Set up l0 penalty
if l0_penalty == None: l0_penalty = eta * np.linalg.cond(R)
# Get the standard least squares estimator
w_best = np.linalg.lstsq(TrainR, TrainY)[0]
err_f = np.linalg.norm(TestY - TestR.dot(w_best), 2)
err_lambda = l0_penalty * np.count_nonzero(w_best)
err_best = err_f + err_lambda
# Now increase tolerance until test performance decreases
for iter in range(maxit):
# Get a set of coefficients and error
w = FTRidge(TrainR, TrainY, lam, FTR_iters, tol, Mreg, normalize = normalize_inner)
err_f = np.linalg.norm(TestY - TestR.dot(w), 2)
err_lambda = l0_penalty * np.count_nonzero(w)
err = err_f + err_lambda
# Has the accuracy improved?
if err <= err_best:
err_best = err
w_best = w
return np.multiply(Mreg, w_best)
def STRidge(X0, y, lam, maxit, tol, Mreg, normalize = 2, print_results = True):
"""
This function is a single iteration of STRidge
"""
n, d = X0.shape
X = np.zeros((n, d))
# First normalize data
if normalize != 0:
Mreg = np.zeros(d)
for i in range(0, d):
Mreg[i] = 1.0 / (np.linalg.norm(X0[:, i],normalize))
X[:, i] = Mreg[i] * X0[:, i]
else: X = X0
# Get the standard ridge esitmate
w = np.linalg.lstsq(X.T.dot(X) + lam * np.eye(d), X.T.dot(y))[0]
num_relevant = d
biginds = np.where(abs(np.multiply(Mreg, w)) > tol)[0]
# Threshold and continue
for j in range(maxit):
# Figure out which items to cut out
smallinds = np.where(abs(np.multiply(Mreg, w)) < tol)[0]
new_biginds = [i for i in range(d) if i not in smallinds]
# If nothing changes then stop
if num_relevant == len(new_biginds): break
else: num_relevant = len(new_biginds)
# Also make sure we didn't just lose all the coefficients
if len(new_biginds) == 0:
if j == 0:
if print_results: print("Tolerance too high - all coefficients set below tolerance")
return w
else: break
biginds = new_biginds
# Otherwise get a new guess
w[smallinds] = 0
if lam != 0:
w[biginds] = np.linalg.lstsq(X[:, biginds].T.dot(X[:, biginds]) +
lam * np.eye(len(biginds)), X[:, biginds].T.dot(y))[0]
else:
w[biginds] = np.linalg.lstsq(X[:, biginds], y)[0]
# Now that we have the sparsity pattern, use standard least squares to get w
if biginds != []: w[biginds] = np.linalg.lstsq(X[:, biginds], y)[0]
if normalize != 0:
return np.multiply(Mreg, w)
else: return w
def TrainSTRidge(R0, Ut, lam, eta, d_tol, maxit = 200, STR_iters = 10, l0_penalty = None, normalize = 0, split = 0.8,
print_best_tol = False, plot_loss = False):
"""
This function trains a predictor using STRidge.
It runs over different values of tolerance and trains predictors on a training set, then evaluates them
using a loss function on a holdout set.
R is Phi (evaluation of basis functions)
Ut is f (simulation of the derivatives)
"""
n,d = R0.shape
R = np.zeros((n,d), dtype=np.float32)
if normalize != 0:
Mreg = np.zeros(d)
for i in range(0,d):
Mreg[i] = 1.0 / (np.linalg.norm(R0[:,i],normalize))
R[:,i] = Mreg[i] * R0[:,i]
normalize_inner = 0
else:
R = R0
Mreg = np.ones(d)
normalize_inner = 2
# Split data into 80% training and 20% test, then search for the best tolderance.
np.random.seed(0) # for consistancy
n,_ = R.shape
train = np.random.choice(n, int(n*split), replace = False)
test = [i for i in np.arange(n) if i not in train]
TrainR = R[train,:]
TestR = R[test,:]
TrainY = Ut[train]
TestY = Ut[test]
#initialize threshold
d_tol = float(d_tol)
tol = d_tol
# Set up l0 penalty
if l0_penalty == None: l0_penalty = eta * np.linalg.cond(R)
# Get the standard least squares estimator
w_best = np.linalg.lstsq(TrainR, TrainY)[0]
err_f = np.linalg.norm(TestY - TestR.dot(w_best), 2)
err_lambda = l0_penalty * np.count_nonzero(w_best)
err_best = err_f + err_lambda
tol_best = 0
# Now increase tolerance until test performance decreases
for iter in range(maxit):
# Get a set of coefficients and error
w = STRidge(TrainR, TrainY, lam, STR_iters, tol, Mreg, normalize = normalize_inner)
err_f = np.linalg.norm(TestY - TestR.dot(w), 2)
err_lambda = l0_penalty * np.count_nonzero(w)
err = err_f + err_lambda
# Has the accuracy improved?
if err <= err_best:
err_best = err
w_best = w
tol_best = tol
tol = tol + d_tol
else:
tol = max([0,tol - 2*d_tol])
# d_tol = 2*d_tol / (maxit - iter)
d_tol = d_tol / 1.618
tol = tol + d_tol
return np.multiply(Mreg, w_best), tol_best