-
Notifications
You must be signed in to change notification settings - Fork 0
/
fit_models.py
252 lines (215 loc) · 8.94 KB
/
fit_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
""" This file contains the training script for the Bayesian logistic regression models
Author:
Claudio Fanconi
"""
import os
import pickle
import pandas as pd
import numpy as np
import pymc3 as pm
from pymc3.variational.callbacks import CheckParametersConvergence
import theano
from sklearn.linear_model import LogisticRegression
from tqdm import tqdm
from src.utils.config import config
from src.utils.data_preprocessing import preprocessing
from src.models.models import Horseshoe_Prior, Laplace_Prior
def main(random_state: int = 42) -> None:
"""Main function which trains the deep learning model
Args:
random_state (int, 42): random state for reproducibility
Returns:
None
"""
# Load test and train data
X_train, X_test, y_train, _ = preprocessing(
feature_path=config.data.data_path,
label_path=config.data.label_path,
train_ids_path=config.data.train_ids,
test_ids_path=config.data.test_ids,
outcome=config.data.label_type,
)
# Fit frequentist LASSO:
if config.model.frequentist_LASSO:
print("Fitting frequentist LASSO")
frequentist_LASSO = LogisticRegression(
penalty="l1", max_iter=1000, solver="liblinear", C=0.02
)
frequentist_LASSO.fit(X_train, y_train)
print("Predicting frequentist LASSO")
frequentist_LASSO_predictions = frequentist_LASSO.predict_proba(X_test)[:, 1]
# Save predictions
np.savez(
os.path.join(
config.data.save_predictions, "frequentist_LASSO_predictions.npz"
),
frequentist_LASSO_predictions,
)
# save model
with open(
os.path.join(config.data.save_posteriors, "frequentist_LASSO.pkl"), "wb"
) as f:
pickle.dump(frequentist_LASSO, f)
# ------------ Bootstrapped L1 Lasso Regression ------------------------------------------
if config.model.frequentist_LASSO_bootstrap:
bootstrapped_models = []
length = len(X_train)
print("Fitting frequentist Bootstrapped LASSO")
for i in tqdm(range(10000)):
indices = np.random.randint(0, length, length)
frequentist_LASSO = LogisticRegression(
penalty="l1", max_iter=1000, solver="liblinear", C=0.02
)
frequentist_LASSO.fit(X_train[indices], y_train.values[indices])
bootstrapped_models.append(frequentist_LASSO)
print("Predicting frequentist LASSO")
bootstrapped_predictions = np.zeros((10000, len(X_test)))
for i, model in enumerate(bootstrapped_models):
prediction = model.predict_proba(X_test)[:, 1]
bootstrapped_predictions[i] = prediction
# Save predictions
np.savez(
os.path.join(
config.data.save_predictions,
"frequentist_LASSO_bootstrapped_predictions.npz",
),
bootstrapped_predictions,
)
# save model
with open(
os.path.join(
config.data.save_posteriors, "frequentist_LASSO_boostrapped.pkl"
),
"wb",
) as f:
pickle.dump(bootstrapped_models, f)
# ------------ Laplace prior BLR with Variational Inference ------------------------------
if config.model.laplace_vi:
# Set Theano shared variables
X_i = theano.shared(X_train)
y_i = theano.shared(y_train.values)
d = X_train.shape[1]
print("Fitting Laplace prior BLR with Variational Inference")
with pm.Model() as BLL:
# Define model in context
Laplace_Prior(X_i, y_i, d)
if config.model.pretrained:
laplace_vi_posterior = pm.load_trace(
os.path.join(config.data.save_posteriors, "laplace_vi"), model=BLL
)
else:
# Perform ADVI
callback = CheckParametersConvergence(diff="absolute")
steps = 3000
posterior = pm.fit(
n=steps,
callbacks=[callback],
random_seed=random_state,
method="fullrank_advi",
)
laplace_vi_posterior = posterior.sample(1000)
# Save posterior
pm.save_trace(
trace=laplace_vi_posterior,
directory=os.path.join(config.data.save_posteriors, "laplace_vi_2"),
overwrite=True,
)
# save model
with open(
os.path.join(config.data.save_posteriors, "laplace_vi_2.pkl"), "wb"
) as f:
pickle.dump(laplace_vi_posterior, f)
print("Predicting Laplace prior BLR with Variational Inference")
X_i.set_value(X_test)
laplace_vi_predictive_distribution = pm.sample_posterior_predictive(
laplace_vi_posterior, 10000, BLL, var_names=["p"], random_seed=11
)
# Save predictive distrubtions
np.savez(
os.path.join(
config.data.save_predictions, "laplace_vi_predictive_distribution_2.npz"
),
laplace_vi_predictive_distribution["p"],
)
# ------------ Laplace prior BLR with Metrpolis-Hastings ------------------------------
if config.model.laplace_mh:
# Set Theano shared variables
X_i = theano.shared(X_train)
y_i = theano.shared(y_train.values)
d = X_train.shape[1]
print("Fitting Laplace prior BLR with Metrpolis-Hastings")
with pm.Model() as BLL:
# Define model in context
Laplace_Prior(X_i, y_i, d)
if config.model.pretrained:
laplace_mh_posterior = pm.load_trace(
os.path.join(config.data.save_posteriors, "laplace_mh"), model=BLL
)
else:
# Perform MH-sampling
warmup = 2000
num_samples = 2000
step = pm.Metropolis()
laplace_mh_posterior = pm.sample(
num_samples, step=step, tune=warmup, random_seed=random_state
)
# Save posterior
pm.save_trace(
trace=laplace_mh_posterior,
directory=os.path.join(config.data.save_posteriors, "laplace_mh"),
overwrite=True,
)
print("Predicting Laplace prior BLR with Metrpolis-Hastings")
X_i.set_value(X_test)
laplace_mh_predictive_distribution = pm.sample_posterior_predictive(
laplace_mh_posterior, 10000, BLL, var_names=["p"], random_seed=11
)
# Save predictive distrubtion
np.savez(
os.path.join(
config.data.save_predictions, "laplace_mh_predictive_distribution.npz"
),
laplace_mh_predictive_distribution["p"],
)
# ------------ Horseshoe+ prior BLR with Metropolis-Hastings ------------------------------
if config.model.horseshoe_mh:
# Set Theano shared variables
X_i = theano.shared(X_train)
y_i = theano.shared(y_train.values)
d = X_train.shape[1]
print("Fitting Horseshoe+ prior BLR with Metropolis-Hastings")
with pm.Model() as BLL:
# Define model in context
Horseshoe_Prior(X_i, y_i, d)
if config.model.pretrained:
horseshoe_mh_posterior = pm.load_trace(
os.path.join(config.data.save_posteriors, "horseshoe_mh"), model=BLL
)
else:
# Perform MH-sampling
warmup = 2000
num_samples = 2000
step = pm.Metropolis()
horseshoe_mh_posterior = pm.sample(
num_samples, step=step, tune=warmup, random_seed=random_state
)
# Save posterior
pm.save_trace(
trace=horseshoe_mh_posterior,
directory=os.path.join(config.data.save_posteriors, "horseshoe_mh"),
overwrite=True,
)
print("Predicting Horseshoe+ prior BLR with Metropolis-Hastings")
X_i.set_value(X_test)
horseshoe_mh_predictive_distribution = pm.sample_posterior_predictive(
horseshoe_mh_posterior, 10000, BLL, var_names=["p"], random_seed=11
)
# Save predictive distrubtion
np.savez(
os.path.join(
config.data.save_predictions, "horseshoe_mh_predictive_distribution.npz"
),
horseshoe_mh_predictive_distribution["p"],
)
if __name__ == "__main__":
main(random_state=config.seed)