-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscore_structure_learn.py
More file actions
executable file
·620 lines (485 loc) · 18.8 KB
/
score_structure_learn.py
File metadata and controls
executable file
·620 lines (485 loc) · 18.8 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
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Project in probabilistic models
# Aaro Salosensaari
# 1st attempt at structure learning
# optimize BIC/AIC/BDeu score with greedy hill climbing
import numpy as np
import scipy.special
import warnings
from stuff import load_data
from stuff import initial_network
from stuff import initial_network_indg
from stuff import initial_network_in_outdg
from stuff import check_dagness
#np.random.seed(42)
np.seterr(all='warn')
curdir = '..'
# network format:
# a np matrix A of N x N, A[i,j] = 1 -> arc from i to j
# i = corresp ith letter in alphabet A,B,C,...,Z
ll_dyn_memory = dict()
bdeu_dyn_memory = dict()
def bdeu_score(A, data, alpha, dynamic=False, batch=False, dynamic_batch=None):
"""
assumes no prior ie. log P(D|G)
"""
n_parents = np.sum(A,0)
qi_terms = np.power(3,n_parents)
ri = 3 # constant for all i
N = A.shape[0] # note, number of variables
data_len = data.shape[0]
alpha = np.double(alpha)
s = np.double(0.0)
for i in range(N):
parents = np.where(A[:,i])[0]
if dynamic and (i, parents.tostring()) in bdeu_dyn_memory:
if batch:
tmp = bdeu_dyn_memory[(dynamic_batch, i, parents.tostring())]
else:
tmp = bdeu_dyn_memory[(i, parents.tostring())]
else:
confs_seen = dict() # N_ij
confs_seen_by_ival = dict() # N_ijk
for n in range(data_len):
ival = data[n,i]
conf_orig = data[n,:][parents]
conf = conf_orig.tostring() # 'hash'
if conf not in confs_seen:
confs_seen[conf] = 1
else:
confs_seen[conf] += 1
if (conf, ival) not in confs_seen_by_ival:
confs_seen_by_ival[(conf, ival)] = 1
else:
confs_seen_by_ival[(conf, ival)] += 1
tmp = np.double(0.0)
for conf in confs_seen:
Nij = confs_seen[conf]
alpha_ij = alpha/qi_terms[i]
alpha_ijk = alpha_ij/ri # ri constant for all i
tmp_d = Nij + alpha_ij
if tmp_d < np.finfo(np.double).eps:
print('warn, Nij+alpha_ij = 0')
tmp_d = np.finfo(np.double).eps
tmp_a = scipy.special.gammaln(alpha_ij) - scipy.special.gammaln(tmp_d)
tmp_b = np.double(0.0)
for ival in range(3):
if (conf, ival) not in confs_seen_by_ival:
Nijk = np.finfo(np.double).eps
else:
Nijk = confs_seen_by_ival[(conf, ival)]
Nijk = np.double(Nijk)
#tmp_gna_ga = np.log(scipy.special.gamma(Nijk + alpha_ijk)/scipy.special.gamma(alpha_ijk))
tmp_gna_ga = scipy.special.gammaln(Nijk + alpha_ijk) - scipy.special.gammaln(alpha_ijk)
tmp_b += tmp_gna_ga
tmp += tmp_a + tmp_b
#with warnings.catch_warnings():
# warnings.filterwarnings('error')
# try:
# tmp += tmp_a + tmp_b
# except Warning:
# print('err')
# print(tmp_a)
# print(tmp_b)
# print(alpha,alpha_ij,alpha_ijk,Nij+alpha_ij, tmp_c, tmp_a)
# raise
if dynamic:
if batch:
bdeu_dyn_memory[(dynamic_batch, i, parents.tostring())] = tmp
else:
bdeu_dyn_memory[(i, parents.tostring())] = tmp
s += tmp
return s #TODO return s => maximizers found empty network always. maybe we should negate it?
# however no idea if it's theoretically justified in any way, probably something wrong in comp
# maybe we are just sensitive to alpha (too small alpha, network ege count small, see lect slide p.24)
# it appears that alpha = 10.0**20 might even work?
def ll_score(A, data, dynamic=False, batch=False, dynamic_batch=None):
# LL term
# sum_{i=1}^n sum_{j=1}^{q_i} sum_{k=1}^{r_i} N_{ijk} log(N_{ijk}/N_{ij}
# notice that this is a sum of local scores
# -> each change during a search is only a couple of steps at a time
# -> most of the scores could be stored and retrieved on the next calc round?
# note that ^will not 'sync' with batch based learning (data set will be different on each call)
# number of parents for each node i
n_parents = np.sum(A,0)
N = A.shape[0]
data_len = data.shape[0]
ll = 0.0
# replicate this with C/Cython? arrays?
for i in range(N):
parents = np.where(A[:,i])[0]
if dynamic and (i, parents.tostring()) in ll_dyn_memory:
if batch:
tmp = ll_dyn_memory[(dynamic_batch, i, parents.tostring())]
else:
tmp = ll_dyn_memory[(i, parents.tostring())]
else:
confs_seen = dict() # N_ij
confs_seen_by_ival = dict() # N_ijk
for n in range(data_len):
ival = data[n,i]
conf_orig = data[n,:][parents]
conf = conf_orig.tostring() # 'hash'
if conf not in confs_seen:
confs_seen[conf] = 1
else:
confs_seen[conf] += 1
if (conf, ival) not in confs_seen_by_ival:
confs_seen_by_ival[(conf, ival)] = 1
else:
confs_seen_by_ival[(conf, ival)] += 1
tmp = 0.0
with warnings.catch_warnings():
warnings.filterwarnings('error')
for conf in confs_seen:
Nij = confs_seen[conf]
for ival in range(3):
if (conf, ival) not in confs_seen_by_ival:
Nijk = np.finfo(np.double).eps
#print('Warning: BIC score had to resort to eps for Nijk')
#print(parents)
#print(np.fromstring(conf, dtype=int))
#print(ll, i, ival)
else:
Nijk = confs_seen_by_ival[(conf, ival)]
Nijk = np.double(Nijk)
try:
tmp += Nijk * np.log(Nijk/Nij)
except Warning:
print('RuntimeWarning in BIC score')
print(Nijk, Nij)
print(ll, i)
if dynamic:
if batch:
ll_dyn_memory[(dynamic_batch, i, parents.tostring())] = tmp
else:
ll_dyn_memory[(i, parents.tostring())] = tmp
ll += tmp
return ll
def bic_score(A, data, dynamic=False, batch=False, dynamic_batch=False):
"""
BIC score for network structure A given data.
Numerical evaluation not optimized much.
# main loops are very parallizable
# consider some kind of parallel solution + C/Fortran?
"""
N = A.shape[0]
data_len = data.shape[0]
# denote
# r_i = number of states of variable i == 3 always
# q_i = number of possible configurations of parents = 3^{number of parents of i in graph A}
# N_{ijk} = number of instances in data where variable i has value k and parents are in configuration j
# N_{ij} = previous summed over k = 1 .. r_i
ll = ll_score(A, data, dynamic=dynamic, batch=batch, dynamic_batch=dynamic_batch)
# penalty term
# sum_{i=1}^n (r_i -1)q_i
n_parents = np.sum(A,0)
# number of states its parents can be for each i
qi_terms = np.power(3,n_parents)
complexity = 2*np.sum(qi_terms)
penalty = 0.5 * np.log(N) * complexity
return ll - penalty
def aic_score(A, data, dynamic=False, batch=False, dynamic_batch=False):
N = A.shape[0]
data_len = data.shape[0]
# denote
# r_i = number of states of variable i == 3 always
# q_i = number of possible configurations of parents = 3^{number of parents of i in graph A}
# N_{ijk} = number of instances in data where variable i has value k and parents are in configuration j
# N_{ij} = previous summed over k = 1 .. r_i
ll = ll_score(A, data, dynamic=dynamic, batch=batch, dynamic_batch=dynamic_batch)
# penalty term
# sum_{i=1}^n (r_i -1)q_i
n_parents = np.sum(A,0)
# number of states its parents can be for each i
qi_terms = np.power(3,n_parents)
complexity = 2*np.sum(qi_terms)
penalty = complexity
return ll - penalty
def random_perturb(A_orig, perturb=20):
"""
perturb network A, with size perturb
don't care about in/outdg constraints, perturb assumed small anyway
"""
n_add = np.random.randint(perturb)
n_remove = perturb - n_add
# this ns are max to remove instead of precise amount removed
# first remove n_remove random edges
A = A_orig.copy()
N = A.shape[0]
n_r = 0
for i in np.random.permutation(N):
for j in np.random.permutation(N):
if not A[i,j]:
continue
if n_r > n_remove:
continue
A[i,j] = 0
n_r += 1
# add n_add random edges, ensuring DAGness
n_a = 0
attempts = 0
while n_a < n_add or attempts < 50:
for i in np.random.permutation(N):
for j in np.random.permutation(N):
if A[i,j]:
continue
if n_a > n_add:
continue
A_try = A.copy()
A_try[i,j] = 1
if not check_dagness(A_try, i,j):
continue
A = A_try
n_a += 1
attempts += 1
return A
def find_nb_max(A_start, s_start, score, max_indg, max_outdg, tabu):
# try deleting edges
N = A_start.shape[0]
A = A_start
s = s_start
# find best network starting from A by deleting edges
A_dbest = None
s_dbest = -np.inf
for i in range(N):
for j in range(N):
if not A[i,j]:
continue
A_try = A.copy()
A_try[i,j] = 0
s_try = score(A_try)
if s_try > s_dbest:
if A_try.tostring() in tabu:
continue
s_dbest = s_try
A_dbest = A_try
# find best network starting from A by adding edges
A_abest = None
s_abest = -np.inf
for j in range(N):
if np.sum(A[:,j]) >= max_indg:
continue
for i in range(N):
if A[i,j]:
continue
if np.sum(A[i,:]) >= max_outdg:
continue
A_try = A.copy()
A_try[i,j] = 1
# check that networks stays DAG
if not check_dagness(A_try, i,j):
continue
s_try = score(A_try)
if s_try > s_abest:
if A_try.tostring() in tabu:
continue
s_abest = s_try
A_abest = A_try
# TODO swapping directions
if s_abest > s_dbest:
return A_abest, s_abest
elif s_dbest > s_start:
return A_dbest, s_dbest
else:
return A_start, s_start
def greedy_hill_climber(score, max_indg=5, max_outdg=5, max_iter=1000, outname=""):
"""
score: larger is better; function accepts only one param (network)
uses totally random restarts
"""
# generate initial random network
A_init = initial_network_indg(max_indg)
A_prev = A_init
s_prev = score(A_prev)
A_best = A_prev
s_best = s_prev
tabu = set()
s_history = np.zeros(max_iter)
i = 0
while i < max_iter:
A_local_max, s_local_max = find_nb_max(A_prev, s_prev, score, max_indg, max_outdg, tabu)
if s_prev >= s_local_max:
A = initial_network_indg(max_indg)
s = score(A)
else:
A = A_local_max
s = s_local_max
if s > s_best:
A_best = A
s_best = s
tabu.add(A_prev.tostring())
A_prev = A
s_prev = s
s_history[i] = s
if i % 100 == 0:
print(i, s_best, s)
np.savez(curdir+"/testoutput/cur{0}_{1}".format(outname, str(i)), A)
np.savez(curdir+"/testoutput/best{0}_{1}".format(outname, str(i)), A_best)
i = i+1
return A_best, s_best, s_history, A_init
def greedy_hill_climber_perturb(score, max_indg=5, max_outdg=5, max_iter=1000, outname="", perturb=50):
"""
score: larger is better; function accepts only one param (network)
uses small perturbs.
"""
# generate initial random network
A_init = initial_network_in_outdg(max_indg, max_outdg)
A_prev = A_init
s_prev = score(A_prev)
A_best = A_prev
s_best = s_prev
tabu = set()
s_history = np.zeros(max_iter)
i = 0
while i < max_iter:
A_local_max, s_local_max = find_nb_max(A_prev, s_prev, score, max_indg, max_outdg, tabu)
if s_prev >= s_local_max:
A = random_perturb(A_prev, perturb)
s = score(A)
else:
A = A_local_max
s = s_local_max
if s > s_best:
A_best = A
s_best = s
tabu.add(A_prev.tostring())
A_prev = A
s_prev = s
s_history[i] = s
if i % 50 == 0:
print(i, s_best, np.sum(A_best), s, np.sum(A))
np.savez(curdir+"/testoutput/cur{0}_{1}".format(outname, str(i)), A)
np.savez(curdir+"/testoutput/best{0}_{1}".format(outname, str(i)), A_best)
i = i+1
return A_best, s_best, s_history, A_init
def greedy_hill_climber_randombatch(score, data, max_indg=5, max_outdg=5, max_iter=1000, outname="", batch_size=100):
"""
score: larger is better, accepts network,data,etc as params (for selecting data batch)
uses totally random restarts
consider only small batch of data at a time
"""
# generate initial random network
A_init = initial_network_indg(max_indg)
N = data.shape[0]
tmp = 0
batches = []
while tmp + batch_size < N:
batches.append((tmp, tmp + batch_size))
tmp += batch_size
batches.append((tmp, N))
n_batches = len(batches)
A_prev = A_init
s_prevs = np.zeros(n_batches)
for bi,b in enumerate(batches):
s_prevs[bi] = score(A_prev,data[b[0]:b[1]], dynamic=True, batch=True, dynamic_batch=bi)
A_best = A_prev
s_bests = s_prevs.copy()
tabu = set()
s_history = np.zeros((max_iter, n_batches))
i = 0
while i < max_iter:
bi = np.random.randint(n_batches)
b_start = batches[bi][0]
b_end = batches[bi][1]
score_batch = lambda x: score(x, data[b_start:b_end,:], dynamic=True, batch=True, dynamic_batch=bi)
A_local_max, s_local_max = find_nb_max(A_prev, s_prevs[bi], score_batch, max_indg, max_outdg, tabu)
if s_prevs[bi] >= s_local_max:
A = initial_network_indg(max_indg)
s = score_batch(A)
else:
A = A_local_max
s = s_local_max
if s > s_bests[bi]:
A_best = A
s_bests[bi] = s
tabu.add(A_prev.tostring())
A_prev = A
s_prevs[bi] = s
s_history[i,bi] = s
if i % 10 == 0:
print(i, s_bests, s)
np.savez(curdir+"/testoutput/cur{0}_{1}".format(outname, str(i)), A)
np.savez(curdir+"/testoutput/best{0}_{1}".format(outname, str(i)), A_best)
i = i+1
s_best = score(A_best, data)
return A_best, s_best, s_history, A_init
def run_bic_climber(outname):
"""TODO: Docstring for main.
:returns: TODO
"""
global ll_dyn_memory
ll_dyn_memory = dict()
# todo consider saving / loading this?
#
keys, data = load_data()
# first try: 2300 for tr, rest for valid
#data_train = data[:2300]
data_valid = data[2300:]
data_train = data
score = lambda x: bic_score(x, data_train, dynamic=True)
#A_best, s_best, s_history, A_init = greedy_hill_climber(score, max_indg=3)
#A_best, s_best, s_history, A_init = greedy_hill_climber(score, max_indg=5, max_outdg=5, max_iter=6000, outname=outname)
A_best, s_best, s_history, A_init = greedy_hill_climber_perturb(score, max_indg=15, max_outdg=15, max_iter=500, outname=outname)
#A_best, s_best, s_history, A_init = greedy_hill_climber_randombatch(bic_score, data, max_indg=5, outname=outname, batch_size=500)
# batch is actually slower than full with ext memory...
# evaluate network with data_valid
bic_valid = bic_score(A_best, data_valid)
bic_valid_init = bic_score(A_init, data_valid)
ll_valid = ll_score(A_best, data_valid)
ll_valid_init = ll_score(A_init, data_valid)
return A_best, s_best, s_history, A_init, bic_valid_init, bic_valid, ll_valid_init, ll_valid
def run_aic_climber(outname):
"""TODO: Docstring for main.
:returns: TODO
"""
global ll_dyn_memory
ll_dyn_memory = dict()
# todo consider saving / loading this?
#
keys, data = load_data()
# first try: 2300 for tr, rest for valid
#data_train = data[:2300]
data_valid = data[2300:]
data_train = data
score = lambda x: aic_score(x, data_train, dynamic=True)
A_best, s_best, s_history, A_init = greedy_hill_climber_perturb(score, max_indg=15, max_outdg=15, max_iter=500, outname=outname)
# evaluate network with data_valid
aic_valid = aic_score(A_best, data_valid)
aic_valid_init = aic_score(A_init, data_valid)
ll_valid = ll_score(A_best, data_valid)
ll_valid_init = ll_score(A_init, data_valid)
return A_best, s_best, s_history, A_init, aic_valid_init, aic_valid, ll_valid_init, ll_valid
def run_bdeu_climber(outname):
"""
note. still no CV
"""
global ll_dyn_memory
ll_dyn_memory = dict()
# todo consider saving / loading this?
#
keys, data = load_data()
# first try: 2300 for tr, rest for valid
#data_train = data[:500]
data_valid = data[2400:]
data_train = data
#alpha = 10.0**20
#alpha = 10.**22
alpha = 5.0
print(np.log(alpha))
#miter = 2000 # for full run 2000
miter = 800
score = lambda x: bdeu_score(x, data_train, alpha=alpha, dynamic=True)
A_best, s_best, s_history, A_init = greedy_hill_climber_perturb(score, max_indg=26, max_outdg=26, max_iter=miter, outname=outname)
# evaluate network with data_valid
#aic_valid = aic_score(A_best, data_valid)
#aic_valid_init = aic_score(A_init, data_valid)
print(alpha)
bd_valid = bdeu_score(A_best, data_valid, alpha=alpha)
bd_valid_init = bdeu_score(A_init, data_valid, alpha=alpha)
ll_valid = ll_score(A_best, data_valid)
ll_valid_init = ll_score(A_init, data_valid,)
print(bd_valid, bd_valid_init)
print(ll_valid, ll_valid_init)
return A_best, s_best, s_history, A_init