-
Notifications
You must be signed in to change notification settings - Fork 44
/
estimator_suite_spark.py
453 lines (392 loc) · 14.9 KB
/
estimator_suite_spark.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
"""
Example using Spark
====================
This script reproduces parts of skggm/examples/estimator_suite.py using the
built-in inverse_covariance.profiling tools and spark support.
To test on databricks:
1) Install (in this order):
- cython
- nose
- matplotlib
- scikit-learn
- skggm (0.2.5 or higher)
2) Create a new notebook
3) Copy this file into a notebook cell
4) shift+return to run the cell
To test on other Apache Spark systems:
1) Define the variable `spark` to be your spark session.
"""
import sys
import numpy as np
import tabulate
import time
import matplotlib.pyplot as plt
from sklearn.covariance import ledoit_wolf
sys.path.append("..")
sys.path.append("../inverse_covariance")
from inverse_covariance import (
QuicGraphicalLasso,
QuicGraphicalLassoCV,
QuicGraphicalLassoEBIC,
AdaptiveGraphicalLasso,
ModelAverage,
)
from inverse_covariance.profiling import LatticeGraph
def make_data(n_samples, n_features):
alpha = 0.4
cov, prec, adj = LatticeGraph(
n_blocks=5, chain_blocks=True, random_sign=True, seed=1
).create(n_features, alpha)
prng = np.random.RandomState(2)
X = prng.multivariate_normal(np.zeros(n_features), cov, size=n_samples)
return X, cov, prec
def quic_graph_lasso_cv(X, metric):
"""Run QuicGraphicalLassoCV on data with metric of choice.
Compare results with GridSearchCV + quic_graph_lasso. The number of lambdas
tested should be much lower with similar final lam_ selected.
"""
print("QuicGraphicalLassoCV with:")
print(" metric: {}".format(metric))
model = QuicGraphicalLassoCV(
cv=2, # cant deal w more folds at small size
n_refinements=6,
sc=spark.sparkContext, # NOQA
init_method="cov",
score_metric=metric,
)
model.fit(X)
print(" len(cv_lams): {}".format(len(model.cv_lams_)))
print(" lam_scale_: {}".format(model.lam_scale_))
print(" lam_: {}".format(model.lam_))
return model.covariance_, model.precision_, model.lam_
def adaptive_graph_lasso(X, model_selector, method):
"""Run QuicGraphicalLassoCV or QuicGraphicalLassoEBIC as a two step adaptive fit
with method of choice (currently: 'binary', 'inverse', 'inverse_squared').
Compare the support and values to the model-selection estimator.
"""
metric = "log_likelihood"
print("Adaptive {} with:".format(model_selector))
print(" adaptive-method: {}".format(method))
if model_selector == "QuicGraphicalLassoCV":
print(" metric: {}".format(metric))
model = AdaptiveGraphicalLasso(
estimator=QuicGraphicalLassoCV(
cv=2, # cant deal w more folds at small size
n_refinements=6,
init_method="cov",
score_metric=metric,
sc=spark.sparkContext, # NOQA
),
method=method,
)
elif model_selector == "QuicGraphicalLassoEBIC":
model = AdaptiveGraphicalLasso(
estimator=QuicGraphicalLassoEBIC(), method=method
)
model.fit(X)
lam_norm_ = np.linalg.norm(model.estimator_.lam_)
print(" ||lam_||_2: {}".format(lam_norm_))
return model.estimator_.covariance_, model.estimator_.precision_, lam_norm_
def quic_graph_lasso_ebic_manual(X, gamma=0):
"""Run QuicGraphicalLasso with mode='path' and gamma; use EBIC criteria for model
selection.
The EBIC criteria is built into InverseCovarianceEstimator base class
so we demonstrate those utilities here.
"""
print("QuicGraphicalLasso (manual EBIC) with:")
print(" mode: path")
print(" gamma: {}".format(gamma))
model = QuicGraphicalLasso(
lam=1.0,
mode="path",
init_method="cov",
path=np.logspace(np.log10(0.01), np.log10(1.0), num=100, endpoint=True),
)
model.fit(X)
ebic_index = model.ebic_select(gamma=gamma)
covariance_ = model.covariance_[ebic_index]
precision_ = model.precision_[ebic_index]
lam_ = model.lam_at_index(ebic_index)
print(" len(path lams): {}".format(len(model.path_)))
print(" lam_scale_: {}".format(model.lam_scale_))
print(" lam_: {}".format(lam_))
print(" ebic_index: {}".format(ebic_index))
return covariance_, precision_, lam_
def quic_graph_lasso_ebic(X, gamma=0):
"""Run QuicGraphicalLassoEBIC with gamma.
QuicGraphicalLassoEBIC is a convenience class. Results should be identical to
those obtained via quic_graph_lasso_ebic_manual.
"""
print("QuicGraphicalLassoEBIC with:")
print(" mode: path")
print(" gamma: {}".format(gamma))
model = QuicGraphicalLassoEBIC(lam=1.0, init_method="cov", gamma=gamma)
model.fit(X)
print(" len(path lams): {}".format(len(model.path_)))
print(" lam_scale_: {}".format(model.lam_scale_))
print(" lam_: {}".format(model.lam_))
return model.covariance_, model.precision_, model.lam_
def model_average(X, penalization):
"""Run ModelAverage in default mode (QuicGraphicalLassoCV) to obtain proportion
matrix.
NOTE: This returns precision_ proportions, not cov, prec estimates, so we
return the raw proportions for "cov" and the threshold support
estimate for prec.
"""
n_trials = 100
print("ModelAverage with:")
print(" estimator: QuicGraphicalLasso (default)")
print(" n_trials: {}".format(n_trials))
print(" penalization: {}".format(penalization))
# if penalization is random, first find a decent scalar lam_ to build
# random perturbation matrix around. lam doesn't matter for fully-random.
lam = 0.5
if penalization == "random":
cv_model = QuicGraphicalLassoCV(
cv=2,
n_refinements=6,
sc=spark.sparkContext, # NOQA
init_method="cov",
score_metric=metric,
)
cv_model.fit(X)
lam = cv_model.lam_
print(" lam: {}".format(lam))
model = ModelAverage(
n_trials=n_trials, penalization=penalization, lam=lam, sc=spark.sparkContext
) # NOQA
model.fit(X)
print(" lam_: {}".format(model.lam_))
return model.proportion_, model.support_, model.lam_
def adaptive_model_average(X, penalization, method):
"""Run ModelAverage in default mode (QuicGraphicalLassoCV) to obtain proportion
matrix.
NOTE: Only method = 'binary' really makes sense in this case.
"""
n_trials = 100
print("Adaptive ModelAverage with:")
print(" estimator: QuicGraphicalLasso (default)")
print(" n_trials: {}".format(n_trials))
print(" penalization: {}".format(penalization))
print(" adaptive-method: {}".format(method))
# if penalization is random, first find a decent scalar lam_ to build
# random perturbation matrix around. lam doesn't matter for fully-random.
lam = 0.5
if penalization == "random":
cv_model = QuicGraphicalLassoCV(
cv=2,
n_refinements=6,
sc=spark.sparkContext, # NOQA
init_method="cov",
score_metric=metric,
)
cv_model.fit(X)
lam = cv_model.lam_
print(" lam: {}".format(lam))
model = AdaptiveGraphicalLasso(
estimator=ModelAverage(
n_trials=n_trials, penalization=penalization, lam=lam, sc=spark.sparkContext
), # NOQA
method=method,
)
model.fit(X)
lam_norm_ = np.linalg.norm(model.estimator_.lam_)
print(" ||lam_||_2: {}".format(lam_norm_))
return model.estimator_.covariance_, model.estimator_.precision_, lam_norm_
def empirical(X):
"""Compute empirical covariance as baseline estimator.
"""
print("Empirical")
cov = np.dot(X.T, X) / n_samples
return cov, np.linalg.inv(cov)
def sk_ledoit_wolf(X):
"""Estimate inverse covariance via scikit-learn ledoit_wolf function.
"""
print("Ledoit-Wolf (sklearn)")
lw_cov_, _ = ledoit_wolf(X)
lw_prec_ = np.linalg.inv(lw_cov_)
return lw_cov_, lw_prec_
def _count_support_diff(m, m_hat):
n_features, _ = m.shape
m_no_diag = m.copy()
m_no_diag[np.diag_indices(n_features)] = 0
m_hat_no_diag = m_hat.copy()
m_hat_no_diag[np.diag_indices(n_features)] = 0
m_nnz = len(np.nonzero(m_no_diag.flat)[0])
m_hat_nnz = len(np.nonzero(m_hat_no_diag.flat)[0])
nnz_intersect = len(
np.intersect1d(np.nonzero(m_no_diag.flat)[0], np.nonzero(m_hat_no_diag.flat)[0])
)
return m_nnz + m_hat_nnz - (2 * nnz_intersect)
if __name__ == "__main__":
n_samples = 600
n_features = 50
cv_folds = 3
# make data
X, true_cov, true_prec = make_data(n_samples, n_features)
plot_covs = [("True", true_cov), ("True", true_cov), ("True", true_cov)]
plot_precs = [
("True", true_prec, ""),
("True", true_prec, ""),
("True", true_prec, ""),
]
results = []
# Empirical
start_time = time.time()
cov, prec = empirical(X)
end_time = time.time()
ctime = end_time - start_time
name = "Empirical"
plot_covs.append((name, cov))
plot_precs.append((name, prec, ""))
error = np.linalg.norm(true_cov - cov, ord="fro")
supp_diff = _count_support_diff(true_prec, prec)
results.append([name, error, supp_diff, ctime, ""])
print(" frobenius error: {}".format(error))
print("")
# sklearn LedoitWolf
start_time = time.time()
cov, prec = sk_ledoit_wolf(X)
end_time = time.time()
ctime = end_time - start_time
name = "Ledoit-Wolf (sklearn)"
plot_covs.append((name, cov))
plot_precs.append((name, prec, ""))
error = np.linalg.norm(true_cov - cov, ord="fro")
supp_diff = _count_support_diff(true_prec, prec)
results.append([name, error, supp_diff, ctime, ""])
print(" frobenius error: {}".format(error))
print("")
# QuicGraphicalLassoCV
params = [
("QuicGraphicalLassoCV : ll", "log_likelihood"),
("QuicGraphicalLassoCV : kl", "kl"),
("QuicGraphicalLassoCV : fro", "frobenius"),
]
for name, metric in params:
start_time = time.time()
cov, prec, lam = quic_graph_lasso_cv(X, metric=metric)
end_time = time.time()
ctime = end_time - start_time
plot_covs.append((name, cov))
plot_precs.append((name, prec, lam))
error = np.linalg.norm(true_cov - cov, ord="fro")
supp_diff = _count_support_diff(true_prec, prec)
results.append([name, error, supp_diff, ctime, lam])
print(" frobenius error: {}".format(error))
print("")
# QuicGraphicalLassoEBIC
params = [
("QuicGraphicalLassoEBIC : BIC", 0),
("QuicGraphicalLassoEBIC : g=0.01", 0.01),
("QuicGraphicalLassoEBIC : g=0.1", 0.1),
]
for name, gamma in params:
start_time = time.time()
# cov, prec, lam = quic_graph_lasso_ebic_manual(X, gamma=gamma)
cov, prec, lam = quic_graph_lasso_ebic(X, gamma=gamma)
end_time = time.time()
ctime = end_time - start_time
plot_covs.append((name, cov))
plot_precs.append((name, prec, lam))
error = np.linalg.norm(true_cov - cov, ord="fro")
supp_diff = _count_support_diff(true_prec, prec)
results.append([name, error, supp_diff, ctime, lam])
print(" error: {}".format(error))
print("")
# Default ModelAverage
params = [
("ModelAverage : random", "random"),
("ModelAverage : fully-random", "fully-random"),
]
for name, model_selector in params:
start_time = time.time()
cov, prec, lam = model_average(X, model_selector)
end_time = time.time()
ctime = end_time - start_time
plot_covs.append((name, cov))
plot_precs.append((name, prec, ""))
supp_diff = _count_support_diff(true_prec, prec)
results.append([name, "", supp_diff, ctime, lam])
print("")
# Adaptive QuicGraphicalLassoCV and QuicGraphicalLassoEBIC
params = [
("Adaptive CV : binary", "QuicGraphicalLassoCV", "binary"),
("Adaptive CV : inv", "QuicGraphicalLassoCV", "inverse"),
("Adaptive CV : inv**2", "QuicGraphicalLassoCV", "inverse_squared"),
("Adaptive BIC : binary", "QuicGraphicalLassoEBIC", "binary"),
("Adaptive BIC : inv", "QuicGraphicalLassoEBIC", "inverse"),
("Adaptive BIC : inv**2", "QuicGraphicalLassoEBIC", "inverse_squared"),
]
for name, model_selector, method in params:
start_time = time.time()
cov, prec, lam = adaptive_graph_lasso(X, model_selector, method)
end_time = time.time()
ctime = end_time - start_time
plot_covs.append((name, cov))
plot_precs.append((name, prec, ""))
error = np.linalg.norm(true_cov - cov, ord="fro")
supp_diff = _count_support_diff(true_prec, prec)
results.append([name, error, supp_diff, ctime, ""])
print(" frobenius error: {}".format(error))
print("")
# Adaptive ModelAverage
params = [("Adaptive MA : random, binary", "random", "binary")]
for name, model_selector, method in params:
start_time = time.time()
cov, prec, lam = adaptive_model_average(X, model_selector, method)
end_time = time.time()
ctime = end_time - start_time
plot_covs.append((name, cov))
plot_precs.append((name, prec, ""))
error = np.linalg.norm(true_cov - cov, ord="fro")
supp_diff = _count_support_diff(true_prec, prec)
results.append([name, error, supp_diff, ctime, ""])
print(" frobenius error: {}".format(error))
print("")
# tabulate errors
print(
tabulate.tabulate(
results,
headers=[
"Estimator",
"Error (Frobenius)",
"Support Diff",
"Time",
"Lambda",
],
tablefmt="pipe",
)
)
print("")
# plots must be inline for notebooks on databricks
named_mats = plot_precs
suptitle = "Precision Estimates"
num_rows = len(named_mats) / 3
num_plots = int(np.ceil(num_rows / 4.))
figs = []
for nn in range(num_plots):
fig = plt.figure(figsize=(10, 8))
plt.subplots_adjust(left=0.02, right=0.98, hspace=0.4)
for i, item in enumerate(named_mats[nn * 4 * 3 : (nn + 1) * 4 * 3]):
lam = None
if len(item) == 3:
name, this_mat, lam = item
elif len(item) == 2:
name, this_mat = item
vmax = np.abs(this_mat).max()
ax = plt.subplot(4, 3, i + 1)
plt.imshow(np.ma.masked_values(this_mat, 0), interpolation="nearest")
plt.xticks(())
plt.yticks(())
if lam is None or lam == "":
plt.title("{}".format(name))
else:
plt.title("{}\n(lam={:.2f})".format(name, lam))
plt.suptitle(suptitle + " (page {})".format(nn), fontsize=14)
figs.append(fig)
#
# In separate cells, run each of these commands
#
display(figs[0]) # NOQA
display(figs[1]) # NOQA