-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_compensating_alpha.py
2872 lines (2569 loc) · 162 KB
/
utils_compensating_alpha.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
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#This file allows to fit any model (with supervised or unsupervised methods) with given (which_CI, which_alpha, which_w, which_Mext) to perform approximate inference
# -*- coding: utf-8 -*-
# from utils_plot_dict import *
from simulate import *
from graph_generator import create_random_weighted_graph, get_w_matrix #,generate_graph
from generate_Mext import generate_M_ext, generate_M_ext_one, generate_M_ext_all
from utils_exact_inference import *
# import os, sys
# sys.path.append(os.getcwd()[:-len(os.getcwd().split('/')[-1])]) #adds to python path, the parent directory: see print(sys.path)
# from functions_utils import W, W_prime, create_factor, create_unitary_factor#,get_mean_durations,get_durations #needs the 2 lines above to work correctly
# from scipy.stats import logistic
from sklearn.metrics import r2_score
import pandas as pd
import pandas
from scipy.optimize import least_squares
# from jax import jit #I removed that as it is not speeding up the computations
# import jax.numpy as np #I removed that as it is not speeding up the computations
import numpy as np
from itertools import repeat, chain #, product
import random
from multiprocessing import cpu_count, Pool
n_cpus = 4 #cpu_count() #4 gives the fastest results (even though there are cpu_count()=8 cpus on my machine...)
from utils_basic_functions import sig, from_dict_to_matrix, from_dict_to_vector
import time
from copy import deepcopy, copy #copy is shallow copy (implemented for most objects: obj.copy() is the same)
# from utils_pytorch import *
# import utils_pytorch
# from utils_plot import *
from utils_dict import get_keys_min_val
from utils_save_load_file import *
from utils_data_convert import *
# from utils_stability_analysis import *
def KL_divergence(p_1_true_vec, p_1_approx_vec, log=False):
"""
Returns KL(p_i(x_i) || \hat{p}_i(x_i)) = sum_{x_i} p_i(x_i) . log(p_i(x_i) / \hat{p}_i(x_i))
log = True means that p_1_approx_vec is in fact B_approx_vec (p(X=1) = sig(B) and p(X=0) = 1-sig(B) = sig(-B))
I tested the function --> ok
Example:
p_1_true_vec = np.array([0.95,0.4,0.55,0.001])
B_1_approx_vec = np.array([35,-1.32,0.1,-80])
p_1_approx_vec = 1 / (1 + np.exp(-B_1_approx_vec))
print(KL_divergence(p_1_true_vec, p_1_approx_vec, log=False))
print(KL_divergence(p_1_true_vec, B_1_approx_vec, log=True))
"""
p_true = np.array([p_1_true_vec, 1 - p_1_true_vec]) #(p(X=1), p(X=0))
if log == False:
p_approx = np.array([p_1_approx_vec, 1 - p_1_approx_vec]) #(p(X=1), p(X=0))
# return scipy.stats.entropy(p_true, p_approx) #slower than the line below
return np.sum(p_true * np.log(p_true / p_approx), axis=0)
else:
B_approx = np.array([p_1_approx_vec, - p_1_approx_vec]) #(B, -B) --> sig(...) gives (p(X=1), p(X=0))
return np.sum(p_true * (np.log(p_true) - logsig(B_approx)), axis=0)
def sqrt_loss(x):
"""
Loss used in least-square function (scipy optimizer)
"If callable, it must take a 1-D ndarray z=f**2 and return an array_like with shape (3, m) where row 0 contains function values, row 1 contains first derivatives and row 2 contains second derivatives. Method ‘lm’ supports only ‘linear’ loss."
"""
# return np.array([np.sqrt(x), 1/2 * x**(-1/2), -1/4 * x**(-3/2)]) #slower than the lines below
x_sqrt = np.sqrt(x)
return np.array([x_sqrt, 1 / (2 * x_sqrt), -1/(4 * x * x_sqrt)])
def is_saturating(l, percent=1, back=20):
"""
Early stopping criterion: 1% difference max in the last 20 iterations
"""
converged = (100 * np.abs(l[-1] - l[-back]) / l[-1] < percent) #percent % difference at max
return converged
def is_valid_model(which_CI, which_alpha, which_w, which_Mext, verbose=True):
if which_CI == 'BP' and which_alpha == '1' and which_w is None and which_Mext is None:
return True
if which_CI == 'BP' and which_alpha != '1':
print("PASS (not a valid BP model)")
return False
if (which_CI == 'BP' or which_alpha in ['1', '0']) and which_w is None and which_Mext is None:
print("PASS (we want to fit something)")
return False
if 'CIpower' in which_CI and which_alpha in ['0', 'directed']:
print("PASS (impossible model)")
return False
if which_CI in ['full_CIpower_approx', 'full_CIpower_approx_approx_tanh', 'rate_network'] and which_alpha in ['0', 'directed', 'undirected', 'directed_ratio', '1_directed_ratio', 'directed_ratio_directed']: #these models don't use any K_edges (contrary to 'full_CIpower' and 'full_CIpower_approx_tanh')
print("PASS (impossible model)")
return False
if ('power' in which_CI and which_CI != 'BP') and which_alpha == '1':
print("PASS (BP covers this model + it's not implemented)")
return False
if which_CI == 'CInew' and which_alpha in ['0', '1']:
print("PASS (impossible model)")
return False
if (which_CI not in ['BP', 'rate_network']) and which_alpha == '1':
print("PASS (BP covers this model)")
return False
# if which_alpha not in ['1', '0'] and which_w is not None:
# print("PASS (we don't want to fit both w and alpha for now)") #but in the code nothing prevents from fitting both w and alpha
# return False
return True
def fit_models_list(list_X, list_y, list_graph,
which_CI, which_alpha, which_w, which_Mext, method_fitting,
damping=0, k_max=None,
options={},
plot_graph=False,
parallel_graphs=True,
parallel_Mext=True,
list_which_error=['KL','MSE', 'CE'], portions_dataset={'train': 0.5, 'val': 0.25, 'test': 0.25}
):
class Object(object):
pass
res = Object()
if method_fitting == 'unsupervised_learning_rule':
#generating a bigger X_train (training set), without y_train (otherwise too long)
nodes_max = 10 #max number of nodes for the graph used later
print("check that nodes_max is ok (in function fit_models_list in utils_compensating_alpha.py")
assert 'N_training_ex' in options.keys()
N_training_ex = options['N_training_ex']
print("add possibilities here by giving additionnal arguments (in particular std_Mext)")
X_all = generate_M_ext_all(nx.erdos_renyi_graph(n=nodes_max, p=1),
N=N_training_ex, std_Mext=1/2
) #the 1st argument (graph) is used not later, it is just needed for the number of nodes
else:
X_all = None
if 'pytorch' in method_fitting:
utils_pytorch.get_model(list_graph[0], which_CI, which_alpha, which_w, which_Mext, print_free_params=True) #just prints the model's free parameters
if 'pytorch' in method_fitting and torch.cuda.is_available():
#not using multiprocessing (as it is not compatible with multiprocessing, or at least I couldn't make it work. I identified this by running the code outside of jupyter notebook, i.e., using .py files)
print("Changing parallel_graphs to False (multiprocessing and CUDA are not compatible)")
parallel_graphs = False
#Non-parallel implementation
if parallel_graphs == False:
if method_fitting != 'unsupervised_learning_rule':
res.list_error_train = []
res.list_error_val = []
res.list_error_test = []
res.list_alpha_fitted = []
res.list_w_fitted = []
res.list_w_input_fitted = []
if method_fitting == 'unsupervised_learning_rule':
if 'keep_history_learning' in options.keys() and options['keep_history_learning'] == True:
res.list_error_val_history = []
res.list_error_test_history = []
res.list_alpha_fitted_history = []
res.list_w_fitted_history = []
res.list_w_input_fitted_history = []
for ind, (graph, X, y) in enumerate(zip(list_graph, list_X, list_y)):
# if ind != 14:
# continue
print("-------- ind = {} --------".format(ind))
res_one = fit_model(X, y, graph,
which_CI, which_alpha, which_w, which_Mext, method_fitting,
damping=damping, k_max=k_max,
X_all=X_all,
options=options,
plot_graph=plot_graph,
parallel_Mext=parallel_Mext,
list_which_error=list_which_error, portions_dataset=portions_dataset
)
#maybe I should plot the loss curve if the validation loss did not converge (as in the parallel implementation below)?
if 'error_train' in res_one.keys():
res.list_error_train.append(res_one['error_train'])
res.list_error_val.append(res_one['error_val'])
res.list_error_test.append(res_one['error_test'])
res.list_alpha_fitted.append(res_one['alpha_fitted'])
res.list_w_fitted.append(res_one['w_fitted'])
res.list_w_input_fitted.append(res_one['w_input_fitted'])
if 'error_val_history' in res_one.keys():
res.list_error_val_history.append(res_one['error_test_history']) #error_val_history or error_test_history?
if 'error_val_history' in res_one.keys():
res.list_alpha_fitted_history.append(res_one['alpha_history'])
res.list_w_fitted_history.append(res_one['w_history'])
res.list_w_input_fitted_history.append(res_one['w_input_history'])
#Parallel implementation
else: #if parallel_graphs == True:
from multiprocessing import cpu_count, Pool
n_cpus = 4 #cpu_count() #4 gives the fastest results (even though there are cpu_count()=8 cpus on my machine...)
with Pool(n_cpus) as p:
list_res = p.starmap(fit_model,
zip(list_X, list_y, list_graph,
repeat(which_CI), repeat(which_alpha), repeat(which_w), repeat(which_Mext),
repeat(method_fitting),
repeat(damping), repeat(k_max),
repeat(X_all),
repeat(options),
repeat(plot_graph),
repeat(parallel_Mext), repeat(list_which_error), repeat(portions_dataset),
range(len(list_graph))))
#plot the loss curve if the validation loss did not converge
for model, i_graph in zip(list_res, range(len(list_graph))):
if 'no_convergence' in model.keys() and model['no_convergence'] == True:
loss_all_epochs = model['loss_all_epochs']
loss_val_all_epochs = model['loss_test_all_epochs']
plt.plot(loss_all_epochs, label='train')
plt.plot(loss_val_all_epochs, label='val')
plt.legend()
plt.title("i_graph = {}: loss - try #3 (should work)".format(i_graph))
plt.xlabel("iteration")
plt.show()
if 'error_train' in list_res[0].keys():
res.list_error_train = [res['error_train'] for res in list_res]
res.list_error_val = [res['error_val'] for res in list_res]
res.list_error_test = [res['error_test'] for res in list_res]
res.list_alpha_fitted = [res['alpha_fitted'] for res in list_res]
res.list_w_fitted = [res['w_fitted'] for res in list_res]
res.list_w_input_fitted = [res['w_input_fitted'] for res in list_res]
if 'error_val_history' in list_res[0].keys():
res.list_error_val_history = [res['error_val_history'] for res in list_res]
if 'alpha_history' in list_res[0].keys():
res.list_alpha_fitted_history = [res['alpha_history'] for res in list_res]
res.list_w_fitted_history = [res['w_history'] for res in list_res]
res.list_w_input_fitted_history = [res['w_input_history'] for res in list_res]
return res
def fit_model(X, y, graph,
which_CI, which_alpha, which_w, which_Mext, method_fitting,
damping=0,
k_max=None, #for CIbeliefs
X_all=None,
options=None,
plot_graph=False,
parallel_Mext=True,
list_which_error=['KL','MSE', 'CE'],
portions_dataset={'train': 0.5, 'val': 0.25, 'test': 0.25},
print_index=None, log=False, which_error_print='MSE'
):
"""
Note that list_which_error does not change how the model is fitted (=based on which error measure), but instead only which error is computed between the y_predict and y_true, which is returned.
Anyway, the error can be computed very easily (using the saved alpha_fitted) with other error measures (but it's a bit long)
"""
if plot_graph:
plot_graph(graph, print_w_edges=True)
res = {}
#Define the model
X_train, X_val, X_test, y_train, y_val, y_test = split_train_test(X, y, portions_dataset=portions_dataset,
return_test=True)
# print("sizes: X_train = {}, X_val = {}, X_test = {}, y_train = {}, y_val = {}, y_test = {}".format(X_train.shape, X_val.shape, X_test.shape, y_train.shape, y_val.shape, y_test.shape))
if method_fitting == 'unsupervised_learning_rule':
X_train = X_all[list(graph.nodes)] #unsupervised learning
model = Model_alpha_ij_all(graph, which_CI, which_alpha=which_alpha, which_w=which_w, which_Mext=which_Mext,
damping=damping, k_max=k_max)
#Compute things for BP
# print("BP")
y_predict = Model_alpha_ij_CI(graph, damping=damping).predict_BP(X_val, log=log)
error_BP = accuracy_score(y_predict, y_val, which_error=which_error_print, log=log)
if print_index is None:
print("val set: {} error (initial BP) = {}".format(which_error_print, error_BP))
else:
print("index = {} - val set: {} error (initial BP) = {}".format(print_index, which_error_print, error_BP))
#Fit the model
# print("Fit the model")
if method_fitting in ['supervised_MSE_scipy', 'supervised_KL_scipy']:
model.fit(X_train, y_train, method_fitting=method_fitting, parallel_Mext=parallel_Mext,
options=options)
elif method_fitting in ['supervised_KL_pytorch', 'supervised_CE_pytorch', 'supervised_MSE_pytorch']:
model.fit(X_train, y_train, method_fitting=method_fitting, parallel_Mext=parallel_Mext,
options=options, X_test=X_val, y_test=y_val) #val data provided: needed for the stopping criterion used in Pytorch fitting (stable validation loss)
elif method_fitting == 'unsupervised_learning_rule':
model.fit(X_train, method_fitting=method_fitting,
options=options,
parallel_Mext=parallel_Mext
) #unsupervised learning --> no need for y
elif method_fitting == 'unsupervised':
model.fit(X_train, method_fitting=method_fitting, parallel_Mext=parallel_Mext,
options=options) #unsupervised learning --> no need for y
else:
print("method_fitting is not an available option")
sys.exit()
#Dealing with no convergence of the validation loss (bad training?)
if hasattr(model, 'no_convergence') and model.no_convergence == True:
print("inside fit_model function - trying to plot")
loss_all_epochs = model.loss_all_epochs
loss_val_all_epochs = model.loss_test_all_epochs
plt.plot(loss_all_epochs, label='train')
plt.plot(loss_val_all_epochs, label='val')
plt.legend()
plt.title("loss - try #2 (but shouldn't work)")
plt.xlabel("iteration")
plt.show()
res['no_convergence'] = True
res['loss_all_epochs'] = loss_all_epochs
res['loss_val_all_epochs'] = loss_val_all_epochs
#Compute the error on the training, validation, and test sets
d_error_all_sets = {}
dict_Xy = {'train': [X_train, y_train], 'val': [X_val, y_val], 'test': [X_test, y_test]}
list_sets = ['train', 'val', 'test'] #if method_fitting != 'unsupervised_learning_rule' else ['val', 'set'] #careful: if unsupervised_learning_rule, then another X_train is taken
for which_set in list_sets:
X_select, y_select = dict_Xy[which_set]
y_predict = model.predict(X_select, parallel_Mext=parallel_Mext, log=log)
# print("which_set = {}".format(which_set))
# print("y_predict[55]", y_predict[55])
# print("y_predict", pd.DataFrame(y_predict).to_numpy())
# print("y_select[55]", y_select.to_numpy()[55])
# print("len(y_predict) = {}, len(y_select) = {}".format(len(y_predict), len(y_select)))
error_set = accuracy_score(y_predict, y_select, list_which_error=list_which_error, log=log)
if print_index is None:
print("{} set: {} error ({}) = {}".format(which_set, which_error_print, which_CI, error_set[which_error_print]))
else:
print("index = {} - {} set: {} error ({}) = {}".format(print_index, which_set, which_error_print, which_CI, error_set[which_error_print]))
d_error_all_sets[which_set] = error_set
#Compute the error on the val set during training (--> history of the error)
if hasattr(model, 'alpha_history'):
alpha_history = model.alpha_history
print("I couldn't find function get_history_error --> implement if necessary")
error_history = get_history_error(X_val, y_val, alpha_history) #add argument list_which_error
x = list(error_history.keys())
y = list(error_history.values())
plt.plot(x, y, label='learning')
plt.xlabel("iteration")
plt.ylabel("error (val set)")
plt.axhline(y=error_BP, label='BP', linestyle='--', color='black')
if print_index is not None:
plt.title(print_index)
plt.legend()
plt.show()
#Save the results into variable
if method_fitting != 'unsupervised_learning_rule':
res['error_train'] = d_error_all_sets['train']
res['error_val'] = d_error_all_sets['val']
res['error_test'] = d_error_all_sets['test']
res['alpha_fitted'] = model.alpha
res['w_fitted'] = model.w
res['w_input_fitted'] = model.w_input
if hasattr(model, 'alpha_history'): #i.e., keep_history_learning == True and which_CI != 'BP'
res['error_val_history'] = error_history
res['alpha_fitted_history'] = alpha_history
res['w_fitted_history'] = w_history
res['w_input_fitted_history'] = w_input_history
# print("alpha", model.alpha)
# print("w", model.w)
# print("w_input", model.w_input)
return res
def starting_point_least_squares(graph, which_CI, which_alpha, which_w=None, which_Mext=None, k_max=None):
"""
Determines:
- x0 (starting point for least_squares): a vector which size depends on the model used, and represents alpha
- the bounds for the least-square minimization
"""
assert xor(k_max is None, which_CI == 'CIbeliefs') #k_max is provided for and only for which_CI == 'CIbeliefs'
assert not(which_w is None and which_alpha in ['0','1'] and which_Mext is None) #otherwise there is nothing to fit
#starting point for alpha
if which_alpha not in ['0', '1']:
if which_CI != 'CIbeliefs':
if which_CI == 'CIbeliefs2':
x0_alpha_val = {'val': 0} #x0_alpha_val = 0
bounds_alpha = (-2, 2) #because the alpha_ij from CIbeliefs2 is in fact (with alpha_ij from CI) alpha_ij*J_ji (where J_ji can be negative)
# elif which_CI == 'CIpower': #alpha_ij = K_nodes[i] / K_edges[i,j], also written = alpha_i / K_ij
# x0_alpha_val = 1
# if which_alpha in ['uniform', 'nodal']: #alpha_ij = alpha_i, which should be in [-2,4]
# bounds_alpha = (-2, 4)
# elif which_alpha == 'undirected':
# bounds_alpha = (1/5, np.inf) #so that alpha = 1 / K_ij is < 5 (here we prevent alpha from being <0, but I think it's not a problem). Anyway, if alpha is too big, then it can create numerical problems in arctanh, probably because the new factor has factors which are too big if K_ij is too close to 0, positive or negative - anyway the solutions <0 seem to be bad)
# elif which_alpha == 'directed_ratio': #we want alpha_ij = alpha_i / K_ij to be <5 (or at least not too big)
# bounds_Knodes = (-2, 4)
# bounds_Kedges = (1/5, np.inf)
# #we concatenate the bounds, using that x0 indicates K_nodes and then K_edges
# bounds_alpha = ([bounds_Knodes[0]]*len(list(graph.nodes)) + [bounds_Kedges[0]]*len(list(graph.edges)),
# [bounds_Knodes[1]]*len(list(graph.nodes)) + [bounds_Kedges[1]]*len(list(graph.edges)))
# #Note that an alternative would be to indicate the constraint that we shouldn't have max(K_nodes/K_edges) be >4, but I don't think that it is possible with function least_squares, and also it would also control for K_nodes[i]/K_edges[j,k] and not only for K_nodes[i]/K_edges[i,j]
# else:
# print("This case is not dealt with - which_CI = {} and which_alpha = {}".format(which_CI, which_alpha))
else:
x0_alpha_val = {'K_nodes': 1, 'inverse_K_edges': 1, 'val': 1} #x0_alpha_val = 1 #alpha = 1 (BP)
if which_alpha in ['directed_ratio', 'directed_ratio_directed']:
if which_CI in dict_get_stability_matrix.keys(): #dict_get_stability_matrix is defined in utils_stability_analysis.py
#choosing (K_edges, K_nodes) such that the algo converges with K_edges = K_nodes (file 'supervised2')
# K = get_Knodes_Kedges_val_convergence_algo(graph, which_CI)
# print("initial K = {} (K_nodes=K_edges=K)".format(K))
# x0_alpha_val['K_nodes'] = K
# x0_alpha_val['inverse_K_edges'] = 1/K
#choosing (K_edges=1, K_nodes) such that the algo converges (file 'supervised3', + 'supervised4' as well because it seems that some supervised3 files actually have a mistake: x0_alpha_val was = 1/K instead of 1...)
# K = get_Knodes_val_convergence_algo(graph, which_CI)
# print("initial K = {} (K_nodes=K and K_edges=1)".format(K))
# x0_alpha_val['K_nodes'] = K
# x0_alpha_val['inverse_K_edges'] = 1 #1/K
#choosing (K_edges=1, K_nodes=1) + low beta such that the algo converges (file 'supervised4' for some models like eFBP)
print("initial K_nodes=1 and K_edges=1")
x0_alpha_val['K_nodes'] = 1
x0_alpha_val['inverse_K_edges'] = 1
if which_alpha in ['directed', '1_directed_ratio']:
x0_alpha = np.array([x0_alpha_val['val']] * len(list(graph.edges)) * 2) #alpha_{i \to j}
bounds_alpha = (-np.inf, +np.inf) #(-10, +np.inf) #(-10, 12)
elif which_alpha == 'undirected':
x0_alpha = np.array([x0_alpha_val['inverse_K_edges']] * len(list(graph.edges))) #alpha_{ij} (such that alpha_{ij} = alpha_{i \to j} = alpha_{j \to i})
bounds_alpha = (-np.inf, +np.inf) #(-4, np.inf)
elif which_alpha in ['nodal', 'nodal_out']:
#choosing (K_edges=1, K_nodes) such that the algo converges (file 'supervised2')
# K = get_Knodes_val_convergence_algo(graph, which_CI)
# print("initial K = {} (K_nodes=K and K_edges=1)".format(K))
# x0_alpha_val['K_nodes'] = K
#choosing (K_edges=1, K_nodes=1) (file 'supervised1' or 'supervised' for some models) + low beta ('supervised4')
print("initial K = {} (K_nodes=1 and K_edges=1)".format(1))
x0_alpha_val['K_nodes'] = 1
x0_alpha = np.array([x0_alpha_val['K_nodes']] * len(list(graph.nodes))) #alpha_i or alpha_j
bounds_alpha = (-np.inf, +np.inf) #(-2, +np.inf)
elif which_alpha == 'uniform':
x0_alpha = np.array([x0_alpha_val['val']]) #alpha
bounds_alpha = (-2, 4) #(0,2) #for CI, alpha is often fitted >2. I allow it to be <0 for the point 1 to be at the center of the bounds (and because sometimes alpha are fitted at ~0, which might be because it's trying to compensate for the loops for which alpha_ij~2 (and not more...), but maybe not only --> allow it and see. (I hope it won't often fit alpha<0 or >2...)
elif which_alpha == 'directed_ratio': #default
x0_alpha = np.array(([x0_alpha_val['K_nodes']] * len(list(graph.nodes))) + ([x0_alpha_val['inverse_K_edges']] * len(list(graph.edges)))) #K_i and inverse_K_ij (such that alpha_ij = K_i / K_ij) #x0_alpha = np.array([x0_alpha_val] * (len(list(graph.edges)) + len(list(graph.nodes)) )) #K_i and inverse_K_ij (such that alpha_ij = K_i / K_ij)
bounds_Knodes = (-np.inf, +np.inf) #(-2, +np.inf)
bounds_inverse_Kedges = (-np.inf, +np.inf) #actually 1/Kedges, not K_edges #(-2, np.inf)
#we concatenate the bounds, using that x0 indicates K_nodes and then K_edges
bounds_alpha = ([bounds_Knodes[0]]*len(list(graph.nodes)) +
[bounds_inverse_Kedges[0]]*len(list(graph.edges)),
[bounds_Knodes[1]]*len(list(graph.nodes)) +
[bounds_inverse_Kedges[1]]*len(list(graph.edges)))
elif which_alpha == 'directed_ratio_directed':
x0_alpha = np.array(([x0_alpha_val['K_nodes']] * len(list(graph.nodes))) + ([x0_alpha_val['inverse_K_edges']] * (len(list(graph.edges)) * 2))) #K_i and K_ij (such that alpha_ij = K_i / K_ij)
bounds_Knodes = (-np.inf, +np.inf)
bounds_inverse_Kedges = (-np.inf, np.inf)
bounds_alpha = ([bounds_Knodes[0]]*len(list(graph.nodes)) +
[bounds_inverse_Kedges[0]]*len(list(graph.edges))*2,
[bounds_Knodes[1]]*len(list(graph.nodes)) +
[bounds_inverse_Kedges[1]]*len(list(graph.edges))*2)
else:
raise NotImplemented #it shouldn't appear (we covered all cases)
else: #which_CI == 'CIbeliefs':
x0_alpha_val = {'val': 0} #x0_alpha_val = 0
bounds_alpha = (-1, 1)
if which_alpha == 'nodal_temporal':
x0_alpha = np.array([x0_alpha_val['val']] * len(list(graph.nodes)) * (k_max - 1)) #alpha = 0 #TODO: have a better starting point: remove the linear effect for k=2, i.e. alpha_{j,2}=sum_i J_ij*J_ji (note that for now we used J_ij=J_ji)
elif which_alpha == 'temporal': #alpha_{j, k} = alpha_k, i.e., alpha[j] are all identical (but are vectors still)
x0_alpha = np.array([x0_alpha_val['val']] * (k_max - 1))
elif which_alpha == 'nodal': #alpha_{j, k} = alpha_j, i.e., alpha[j] = [alpha_j, alpha_j, alpha_j, ...etc]
x0_alpha = np.array([x0_alpha_val['val']] * len(list(graph.nodes)))
elif which_alpha == 'uniform':
x0_alpha = np.array([x0_alpha_val['val']])
else:
print("which_alpha = {} is not supported in function from_vec_to_obj".format(which_alpha))
sys.exit()
else: #which_alpha in ['0', '1']
x0_alpha = np.array([])
bounds_alpha = ([], []) #None
#Starting point for w (if which_w is not None) - keep in mind that w is not a multiplicative coefficient but directly the graph weights
if which_w is not None:
assert which_w in ['undirected', 'directed']
if which_w == 'undirected':
x0_w = np.array([graph.edges[edge]['weight'] for edge in graph.edges]) #taking weights for graph as starting point
elif which_w == 'directed':
x0_w = np.array([graph.edges[edge]['weight'] for edge in get_all_oriented_edges(graph)]) #taking weights for graph as starting point
if which_alpha in ['0', '1', 'nodal', 'undirected', 'directed_ratio', 'directed_ratio_directed']:
#choosing (K_edges=1, K_nodes) such that the algo converges (--> reduces the amplitude of weights)
beta_val = get_beta_val_convergence_algo(graph, which_CI)
print("initial beta = {}".format(beta_val)) #'initial beta = {} (K_nodes=1 and K_edges=1)'
tanh_Jij = 2 * x0_w - 1
tanh_Jtildeij = np.tanh(beta_val * tanh_inverse(tanh_Jij))
x0_w = 1/2 + 1/2 * tanh_Jtildeij
if which_CI == 'rate_network':
bounds_w = (-np.inf, +np.inf)
else: #default
bounds_w = (0, 1)
bounds_w = ([bounds_w[0]] * len(x0_w), [bounds_w[1]] * len(x0_w))
else:
x0_w = np.array([])
bounds_w = ([], []) #None
#Starting point for w_input (if which_Mext is not None)
if which_Mext is not None:
assert which_Mext == 'nodal'
x0_w_input_val = 1 #taking 1 as starting point (as for BP)
x0_w_input = np.array([x0_w_input_val] * len(list(graph.nodes)))
bounds_w_input = (-np.inf, +np.inf)
bounds_w_input = ([bounds_w_input[0]] * len(x0_w_input), [bounds_w_input[1]] * len(x0_w_input))
else:
x0_w_input = np.array([])
bounds_w_input = ([], [])
#Returning a concatenation (alpha, w, and w_input) depending on the case
x0, bounds = concatenate_arr(x0_alpha, x0_w, x0_w_input,
bounds_alpha, bounds_w, bounds_w_input
)
# print("here", len(x0), len(bounds[0]), len(bounds[1]))
# print("what it should be", len(graph) + len(graph.edges))
return x0, bounds
def concatenate_arr(x1, x2, x3, bounds1, bounds2, bounds3):
# if which_w is None:
# return x0_alpha, bounds_alpha
# elif which_alpha in ['0', '1']:
# return x0_w, bounds_w
# else:
# #Concatenating both
# x0 = np.concatenate([x0_alpha, x0_w])
# assert type(bounds_alpha) == tuple
# #create bounds = (list_bounds_inf, list_bounds_sup), by combining bounds_alpha and bounds_w
# if type(bounds_alpha[0]) != list:
# assert type(bounds_alpha[1]) != list
# bounds_alpha = ([bounds_alpha[0]] * len(x0_alpha), [bounds_alpha[1]] * len(x0_alpha))
# else:
# assert len(bounds_alpha[0]) == len(x0_alpha)
# assert len(bounds_alpha[1]) == len(x0_alpha)
# bounds = (bounds_alpha[0] + bounds_w[0], bounds_alpha[1] + bounds_w[1]) #concatenating the bounds
# return x0, bounds
x = np.concatenate([x1, x2, x3])
if type(bounds1[0]) != list: #bounds_alpha
assert type(bounds1[1]) != list
bounds1 = ([bounds1[0]] * len(x1), [bounds1[1]] * len(x1))
else:
assert len(bounds1[0]) in [0, len(x1)]
assert len(bounds1[1]) in [0, len(x1)]
#create bounds = (list_bounds_inf, list_bounds_sup), by combining bounds1, bounds2, bounds3
#concatenating the bounds
# bounds = (bounds1[0] + bounds2[0] + bounds3[0], bounds1[1] + bounds2[1] + bounds3[1])
bounds = (np.concatenate([bounds1[0], bounds2[0], bounds3[0]]), np.concatenate([bounds1[1], bounds2[1], bounds3[1]]))
return x, bounds
def split_arr(arr, n1, n2, n3):
assert len(arr) == n1 + n2 + n3
x1, x2, x3 = arr[:n1], arr[n1: n1 + n2], arr[n1 + n2:]
x1 = x1 if len(x1) > 0 else None
x2 = x2 if len(x2) > 0 else None
x3 = x3 if len(x3) > 0 else None
return x1, x2, x3
def from_vec_to_obj(vec_alpha_w, graph,
which_CI, which_alpha='directed', which_w=None, which_Mext=None,
k_max=None, parallel_CI=False):
"""
Returns the object alpha (containing information about alpha / dict_alpha_impaired / K_nodes, K_edges), based on vec_alpha_w (= vec_alpha and vec_w)
We need K_nodes and K_edges for CIpower (because it determines the weights of the graph and M_ext when class Network is called by run_algo)
"""
# print("len(vec_alpha_w) = {}".format(len(vec_alpha_w)))
assert xor(k_max is None, which_CI == 'CIbeliefs') #k_max is provided for and only for which_CI == 'CIbeliefs'
assert not(which_w is None and which_alpha in ['0', '1'] and which_Mext is None) #otherwise there is nothing to fit
assert which_w in ['undirected', 'directed', None]
if which_w == 'undirected':
n_w_vec = len(graph.edges)
elif which_w == 'directed':
n_w_vec = len(graph.edges) * 2 #= len(get_all_oriented_edges(graph))
elif which_w is None:
n_w_vec = 0
assert which_Mext in ['nodal', None]
if which_Mext == 'nodal':
n_w_input_vec = len(graph.nodes)
elif which_Mext is None:
n_w_input_vec = 0
n_alpha_vec = len(vec_alpha_w) - n_w_vec - n_w_input_vec #instead of looking at which_alpha
vec_alpha, vec_w, vec_w_input = split_arr(vec_alpha_w, n_alpha_vec, n_w_vec, n_w_input_vec)
# print("n_alpha_vec = {}, n_w_vec = {}, n_w_input_vec = {}".format(n_alpha_vec, n_w_vec, n_w_input_vec))
# def len_with_none(arr):
# if arr is None:
# return 0
# else:
# return len(arr)
# print("len(vec_alpha) = {}, len(vec_w) = {}, len(vec_w_input) = {}".format(len_with_none(vec_alpha), len_with_none(vec_w), len_with_none(vec_w_input)))
# if which_w is None:
# vec_alpha = vec_alpha_w
# elif which_alpha in ['0', '1']:
# vec_w = vec_alpha_w
# else:
# assert which_w in ['undirected', 'directed']
# if which_w == 'undirected':
# n_w_vec = len(graph.edges)
# elif which_w == 'directed':
# n_w_vec = len(graph.edges) * 2 #= len(get_all_oriented_edges(graph))
# vec_alpha, vec_w = vec_alpha_w[:-n_w_vec], vec_alpha_w[-n_w_vec:]
# print("len(vec_alpha) = {}, len(vec_w) = {}".format(len(vec_alpha), len(vec_w)))
if which_alpha not in ['0', '1']:
#Initialize the variables
dict_alpha_impaired = None
K_nodes = None
K_edges = None
alpha = None
if which_CI != 'CIbeliefs':
if which_alpha == 'directed': #default
assert 'power' not in which_CI #CIpower with unconstrained alpha is impossible - see CInew instead (no K_i and K_ij but only alpha_ij which can be unconstrained) #{alpha_ij} unconstrained doesn't work, because we need K_i and K_ij to modify M_ext and w_ij . So M_ij = 1/alpha_ji . F(B_i - alpha_ij . M_ji) does not work. (it is not CIpower. However, it corresponds to CInew!!). Or maybe we could take Kedges_{i \to j} in CIpower?
#However, with CInew, alpha_ij can be unconstrained, because there are no changes of M_ext (resp w_ij) depending of K_nodes (resp K_edges): the alpha_ij only appears in the message update equation: M_ij = 1/alpha_ji . F(B_i - alpha_ij . M_ji)
dict_alpha_impaired = dict(zip(get_all_oriented_edges(graph), vec_alpha))
elif which_alpha == 'undirected':
K_edges = dict(zip(list(graph.edges), 1 / vec_alpha)) #careful: 1 / alpha (before: vec_alpha)
elif which_alpha == 'nodal': #alpha_{i \to j} = alpha_i
K_nodes = dict(zip(list(graph.nodes), vec_alpha))
elif which_alpha == 'nodal_out': #alpha_{i \to j} = alpha_j
assert which_CI not in ['CIpower', 'CIpower_approx', 'CInew'] #Impossible to have which_alpha = nodal_out: alpha_ij = K_i / K_ij. Maybe introduce a new model with alpha_ij = K_j / K_ij but K_j is still used for M_ext and K_ij is still used for the transformation of weights
raise NotImplemented #For which_CI not in ['CIpower', 'CInew']. To implement it that, add a field K_nodes_out to Alpha_obj
# corresp = dict(zip(list(graph.nodes), vec_alpha))
# dict_alpha_impaired = {(node1, node2): corresp[node2]
# for (node1, node2) in get_all_oriented_edges(graph)}
elif which_alpha == 'uniform':
assert len(vec_alpha) == 1
if which_CI not in ['CIpower', 'CIpower_approx', 'CInew']:
alpha = vec_alpha[0] #vec_alpha[0] because vec_alpha is a numpy array with one element so we get a float, to be coherent with all other cases
else:
#CIpower and CInew cannot deal with alpha uniform without knowing K_nodes and K_edges. Here we set the uniform case to be uniform K_nodes equal to alpha. On the line below you can find a alternative
K_nodes = dict(zip(list(graph.nodes), repeat(vec_alpha[0]))) #K_ij = 1 and alpha_{i to j} = K_i = alpha
# K_edges = dict(zip(list(graph.edges), repeat(1 / vec_alpha[0]))) #K_i = 1 and alpha_{i to j} = 1 / K_ij = alpha #this is an alternative to what's above
elif which_alpha == 'directed_ratio':
K_nodes = dict(zip(list(graph.nodes), vec_alpha[:len(graph.nodes)]))
K_edges = dict(zip(list(graph.edges), 1 / vec_alpha[len(graph.nodes):])) #changed - before: vec_alpha[len(graph.nodes):]
elif which_alpha == '1_directed_ratio':
assert which_CI != 'CI'
K_edges = dict(zip(get_all_oriented_edges(graph), 1 / vec_alpha))
elif which_alpha == 'directed_ratio_directed':
assert which_CI != 'CI'
K_nodes = dict(zip(list(graph.nodes), vec_alpha[:len(graph.nodes)]))
K_edges = dict(zip(get_all_oriented_edges(graph), 1 / vec_alpha[len(graph.nodes):]))
else:
print("(which_alpha = {}, which_CI = {}) is not supported in function from_vec_to_obj".format(which_alpha, which_CI))
sys.exit()
elif which_CI == 'CIbeliefs':
if which_alpha == 'nodal_temporal':
# length_alpha = int(len(vec_alpha) / len(graph.nodes)) #we recovered k_max - 1 from vec_alpha (but we cannot do that for 'nodal' or 'uniform')
# print(length_alpha)
vec_alpha_all_nodes = list(vec_alpha.reshape(len(graph.nodes), k_max - 1))
dict_alpha_impaired = dict(zip(list(graph.nodes), vec_alpha_all_nodes))
# # print("vec_alpha_optim", vec_alpha_optim)
# # print("of len = ", len(vec_alpha_optim))
elif which_alpha == 'temporal': #alpha_{j, k} = alpha_k, i.e., alpha[j] are all identical (but are vectors still)
dict_alpha_impaired = dict(zip(list(graph.nodes), repeat(vec_alpha)))
elif which_alpha == 'nodal': #alpha_{j, k} = alpha_j, i.e., alpha[j] = [alpha_j, alpha_j, alpha_j, ...etc]
dict_alpha_impaired = dict(zip(list(graph.nodes), np.tile(vec_alpha, (k_max - 1, 1)).T))
elif which_alpha == 'uniform':
dict_alpha_impaired = dict(zip(list(graph.nodes), vec_alpha * np.ones((len(list(graph.nodes)), k_max - 1))))
else:
print("(which_alpha = {}, which_CI = {}) is not supported in function from_vec_to_obj".format(which_alpha, which_CI))
sys.exit()
print("before", vec_alpha)
print("after", dict_alpha_impaired)
# dict_alpha = create_alpha_dict(graph,
# alpha=alpha)#maybe do it only in the cases where dict_alpha_impaired has not been computed? It could make the code less efficient
# return dict_alpha
if parallel_CI == False:
alpha_obj = Alpha_obj(
{'alpha': alpha,
'dict_alpha_impaired': dict_alpha_impaired,
'K_nodes': K_nodes, 'K_edges': K_edges
})
else: #parallel_CI = True
if dict_alpha_impaired is not None:
assert which_CI != 'CIbeliefs'
alpha_matrix = from_dict_to_matrix(dict_alpha_impaired, list(graph.nodes))
alpha_obj = Alpha_obj({'alpha_matrix': alpha_matrix})
else:
if K_nodes is not None:
K_nodes_vector = from_dict_to_vector(K_nodes, list(graph.nodes), default_value=1)
else:
K_nodes_vector = None
if K_edges is not None:
make_symmetrical = which_alpha not in ['1_directed_ratio', 'directed_ratio_directed']
K_edges_matrix = from_dict_to_matrix(K_edges, list(graph.nodes), default_value=1,
make_symmetrical=make_symmetrical)
else:
K_edges_matrix = None
alpha_obj = Alpha_obj(
{'alpha': alpha,
'K_nodes_vector': K_nodes_vector, 'K_edges_matrix': K_edges_matrix
})
else:
if which_CI == 'BP':
alpha_obj = Alpha_obj({'alpha': 1}) #BP --> by definition, alpha = 1 (note that (which_CI='BP',which_alpha='0') means indeed BP, with alpha=1!
else:
alpha_obj = Alpha_obj({'alpha': float(which_alpha)}) #for which_alpha = '1' or '0', for instance
assert which_w in ['undirected', 'directed', None]
if which_w == 'undirected':
# print("vec_w = {}".format(vec_w))
dict_w = dict(zip(list(graph.edges), vec_w))
if parallel_CI == False:
w_obj = Alpha_obj({'K_edges': dict_w}) #K_edges
else:
w_matrix = from_dict_to_matrix(dict_w, list(graph.nodes), default_value=0.5, make_symmetrical=True)
w_obj = Alpha_obj({'alpha_matrix': w_matrix}) #'K_edges_matrix'
elif which_w == 'directed':
dict_w = dict(zip(get_all_oriented_edges(graph), vec_w))
if parallel_CI == False:
w_obj = Alpha_obj({'dict_alpha_impaired': dict_w})
else:
w_matrix = from_dict_to_matrix(dict_w, list(graph.nodes), default_value=0.5)
w_obj = Alpha_obj({'alpha_matrix': w_matrix})
elif which_w is None:
w_obj = None
assert which_Mext in ['nodal', None]
if which_Mext == 'nodal':
if parallel_CI == False:
dict_w_input = dict(zip(list(graph.nodes), vec_w_input))
w_input = dict_w_input
else:
w_input = vec_w_input
elif which_Mext is None:
w_input = None
return alpha_obj, w_obj, w_input #some of them can be None
def diff_CI_true(vec_alpha_w, graph, M_ext, p_1_true,
which_CI='CI', which_alpha='directed', which_w=None, which_Mext=None,
damping=0, k_max=None,
parallel_CI=False, parallel_Mext=False,
which_distance='diff'
):
"""
Function used in the least square minimization
Returns the vector p_estimate(X=1) - p(X=1), with a penalization if the model didn't converge
vec_alpha has size:
- 2*N_edges for CI, where N_edges is the number of unoriented edges of graph
- N_edges + N_nodes for CIpower (because alpha_ij = K_i / K_ij)
- N_nodes*(k_max-1) for CIbeliefs
The output of the function has size N_nodes
Using the function:
# diff = diff_CI_true(vec_alpha_w, graph, M_ext, p_1_true) #diff between p(X=1) and p_estimate(X=1)
# print("max abs diff (CI vs true):", np.max(np.abs(diff)))
# # error_CI = 0.5 * np.sum(y**2)
# # print("error_CI = {}".format(error_CI))
# p_1_CI = diff + np.array(list(p_1_true.values()))
# print("p_1_CI:", p_1_CI)
"""
assert which_distance in ['diff', 'KL']
alpha, w, w_input = from_vec_to_obj(vec_alpha_w, graph,
which_CI, which_alpha, which_w, which_Mext,
k_max,
parallel_CI=parallel_CI)
res = simulate_CI(graph, M_ext,
alpha=alpha, w=w, w_input=w_input,
which_CI=which_CI, damping=damping,
transform_into_dict=True,
parallel_CI=parallel_CI, parallel_Mext=parallel_Mext
)
# res = simulate_CI_with_history(graph, M_ext, alpha=alpha, dict_alpha_impaired=dict_alpha_impaired, which_CI=which_CI, damping=damping) #the history is needed to test convergence #be careful with this: indeed, the result might differ consequently from simulate_CI, because of the discrepancies in the indices (+ the random perturbations to the input, which might lead to convergence to different fixed points between functions simulate_CI_with_history and simulate_CI...)
# print(res.B_CI)
#test the convergence and return a high value if there is no convergence (here a vector of 1: the sign does not matter)
# if test_convergence_dict(res.B_history_CI) == False:
# penalisation = 1.5
# else:
# penalisation = 1
# multiplication_factor = {key: 1 + 2*np.abs(val[-1] - val[-2]) for key,val in res.B_history_CI.items()}
# assert list(res.B_CI.keys()) == list(multiplication_factor.keys())
# multiplication_factor = np.array(list(multiplication_factor.values()))
# return np.array([1]*len(p_1_true)) #try if this helps to fit to a alpha for which there is convergence. Alternative: have a penalization (otherwise the cost function has the same value most of the time)
if parallel_Mext == False:
assert list(p_1_true.keys()) == list(res.B_CI.keys())
# print("p_1_true.keys()", p_1_true.keys())
p_1_CI = sig(np.array(list(res.B_CI.values())))
return p_1_CI - np.array(list(p_1_true.values())) #no penalization
# return (p_1_CI - np.array(list(p_1_true.values()))) * multiplication_factor
# return (p_1_CI - np.array(list(p_1_true.values()))) * penalisation
else: #p_1_true is [{node:p_node for all nodes} for all examples] / B_CI is {node: [B_node for all examples] for all nodes}
assert list(res.B_CI[0].keys()) == list(p_1_true[0].keys())
if which_distance == 'diff':
p_1_CI = [{node: sig(val) for node, val in B_CI_ex.items()} for B_CI_ex in res.B_CI] #p_1_CI is a list of dict: p_1_CI = [{node: p_1_CI_node for all nodes} for all examples] (just like p_1_true)
diff = []
for p_1_true_ex, p_1_CI_ex in zip(p_1_true, p_1_CI):
diff.append({node: p_1_true_ex[node] - p_1_CI_ex[node] for node in graph.nodes})
return [np.array(list(el.values())) for el in diff] #return diff
elif which_distance == 'KL':
#KL-divergence between the marginal distributions: KL(p_true_i(x_i)||p_approx_i(x_i))
#where KL(p_true_i(x_i)||p_approx_i(x_i)) = sum_{x_i} p_true_i(x_i) . log(p_true_i(x_i) / p_approx_i(x_i))
p_1_true_matrix = np.array([list(el.values()) for el in p_1_true])
p_1_approx_matrix = sig(np.array([list(el.values()) for el in res.B_CI]))
# print(p_1_true_matrix.shape, p_1_approx_matrix.shape, KL_divergence(p_1_true_matrix, p_1_approx_matrix).shape) #all are of size (n_examples, n_nodes)
return KL_divergence(p_1_true_matrix, p_1_approx_matrix) #of size (n_examples, n_nodes)
else:
raise NotImplemented
def diff_CI_true_list(vec_alpha_w, graph, X_train, y_train,
which_CI='CI', which_alpha='directed', which_w=None, which_Mext=None,
damping=0, k_max=None,
parallel_CI=True, parallel_Mext=True, which_distance='diff'):
"""
Returns a vector
Using the function:
# diff = diff_CI_true_list(res.x, graph, X, y)
# error_CI = 0.5 * np.sum(diff**2)
# vec_alpha_BP = np.array([1] * len(list(graph.edges)) * 2)
# diff = diff_CI_true_list(vec_alpha_BP, graph, X, y, parallel_CI=False)
# error_BP = 0.5 * np.sum(diff**2)
"""
# alpha, w, w_input = from_vec_to_obj(vec_alpha_w, graph,
# which_CI, which_alpha, which_w, which_Mext,
# k_max,
# parallel_CI=parallel_CI)
# print("alpha = {}".format(alpha))
# print("w = {}".format(w))
# print("w_input = {}".format(w_input))
assert which_distance in ['diff', 'KL']
X_train, y_train = from_df_to_list_of_dict(X_train, y_train)
if parallel_CI == False:
y_all = []
for i in range(len(X_train)):
M_ext = X_train[i]
p_1_true = y_train[i]
y = diff_CI_true(vec_alpha_w, graph, M_ext, p_1_true, which_CI=which_CI,
which_alpha=which_alpha, which_w=which_w, which_Mext=which_Mext,
damping=damping, k_max=k_max,
parallel_CI=parallel_CI, parallel_Mext=parallel_Mext
)
y_all.append(y)
return np.array(y_all).reshape((-1,))
else: #parallel_CI = True
if parallel_Mext == False:
with Pool(n_cpus) as p:
y_all = p.starmap(diff_CI_true,
zip(repeat(vec_alpha_w), repeat(graph), X_train, y_train, repeat(which_CI),
repeat(which_alpha), repeat(which_w), repeat(which_Mext),
repeat(damping), repeat(k_max),
repeat(parallel_CI), repeat(parallel_Mext)
)
)
# print("y_all.shape = {}".format(np.array(y_all).shape))
return np.array(y_all).reshape((-1,))
else:
y_all = diff_CI_true(vec_alpha_w, graph, X_train, y_train, which_CI,
which_alpha, which_w, which_Mext,
damping, k_max, parallel_CI=parallel_CI, parallel_Mext=parallel_Mext,
which_distance=which_distance)
# print("y_all.shape = {}".format(np.array(y_all).shape))
y_all = np.array(y_all).reshape((-1,))
return y_all
# sys.exit()
def get_final_messages_list(vec_alpha_w, graph, list_M_ext,
which_CI='CI', which_alpha='directed', which_w=None, which_Mext=None,
damping=0, k_max=None,
parallel_CI=True, parallel_Mext=True):
# print("vec_alpha_w = {}".format(vec_alpha_w))
list_M_ext = from_df_to_list_of_dict(list_M_ext)
if parallel_CI == True:
if parallel_Mext == False:
with Pool(n_cpus) as p:
alpha, w = from_vec_to_obj(vec_alpha_w, graph, which_CI, which_alpha, which_w, which_Mext,
k_max, parallel_CI=parallel_CI) #should this line be inside the Pool or outside?
M_final_all = p.starmap(get_final_messages,
zip(repeat(graph), list_M_ext, repeat(alpha), repeat(w), repeat(which_CI),
repeat(damping),
repeat(parallel_CI), repeat(parallel_Mext))
)
# print("alpha = {}".format(alpha.to_matrix(graph)))
return np.array(M_final_all).reshape((-1,))
else:
alpha, w = from_vec_to_obj(vec_alpha_w, graph, which_CI, which_alpha, which_w, which_Mext,
k_max, parallel_CI=parallel_CI)
M_final_all = get_final_messages(graph, list_M_ext, alpha, w, which_CI,
damping=damping, parallel_CI=parallel_CI, parallel_Mext=parallel_Mext)
return M_final_all.reshape((-1,))
else:
raise NotImplemented #TODO: implement the non-parallel version (not urgent)
def get_final_messages(graph, M_ext,
alpha, w=None, w_input=None, which_CI='CI',
damping=0,
parallel_CI=True, parallel_Mext=True):
res = simulate_CI(graph, M_ext, alpha=alpha, w=w, w_input=w_input,
which_CI=which_CI, return_final_M=True, damping=damping, transform_into_dict=True,
parallel_CI=parallel_CI, parallel_Mext=parallel_Mext
)
M_final = res.final_M
return np.array(list(M_final.values()))
def learning_unsupervised(graph, X_train,
which_CI, which_alpha='directed', which_w=None, which_Mext=None,
damping=0, eps=None, keep_history_learning=True,
X_val=None, y_val=None, stopping_criterion='stable_validation_loss'
):
"""
Uses a learning rule to minimize E = sum_ij M_ij^2 (or sum_ij (B_i - alpha_ij M_ji)^2)
The learning rule is not exact, but we hope to get nice results anyway (--> check)
Previous name for X_train: list_M_ext
eps is the learning rate
Minimizes E = sum_{ij} Mfinal_{ij}^2 (after convergence of CI) over {alpha_ij} where M_ij = F_ij(B_i - alpha_ij.Mji)
--> dE/d(alpha_ij) = -2*M_ij*F'_ij(B_i-alpha_ij*M_ji)*M_ji
--> dalpha_ij = - eps*dE/dalpha_ij (without the factor 2 from above) to make E decrease
Note that another function to minimize could be E = sum_t sum_{ij} dM_{ij}^2 ---> in this case,
"""
assert which_CI in ['BP', 'CI', 'CIpower', 'CIpower_approx'] #TODO: write code for all other cases
assert which_Mext is None #TODO: think of a formula to fit \hat{\gamma}, i.e. the multiplicative factor in front of M_ext
if which_CI == 'CI':
assert which_alpha in ['uniform', 'nodal', 'undirected', 'directed'] #TODO (?): implement directed_ratio
if 'power' in which_CI:
assert which_alpha in ['nodal', 'undirected', 'directed_ratio', '1_directed_ratio', 'directed_ratio_directed'] #TODO: implement uniform
class Object(object):
pass
res = Object()
if which_CI == 'BP':
res.alpha = Alpha_obj({'alpha': 1})
return res
N = len(X_train)
if eps is None:
eps_edge = 0.03
eps_nodal = 0.003 #0.0003
# eps = 3 * 1/N
# list_examples = X_train #TODO: shuffle + copy examples to have several presentations
# list_examples = X_train*5 #duplicate the training set (without shuffling)
# list_examples = list(chain.from_iterable([random.sample(X_train, N) for _ in range(5)])) #duplicate the training set (with shuffling = sampling N times with replacement) - presenting 5 times each example; 1 block contains each example exactly one time (but shuffled inside the block)
# list_examples = [X_train]*5000
list_examples = [random.sample(X_train, 50) for _ in range(2000)] #doing batch learning
parallel_CI = (which_CI in ['BP', 'CI', 'CIpower', 'CIpower_approx', 'CInew']) and ('weight' in graph.edges[list(graph.edges)[0]].keys())
if parallel_CI == True:
w_matrix = get_w_matrix(graph)
W_matrix = 2 * get_w_matrix(graph) - 1
#initialize dict_alpha
if which_alpha == 'directed':
dict_alpha = {edge: np.random.uniform(0.8, 1.2) for edge in get_all_oriented_edges(graph)} #both (i,j) and (j,i)
if parallel_CI == False:
alpha_obj = Alpha_obj({'dict_alpha_impaired': dict_alpha})
else:
alpha_matrix = from_dict_to_matrix(dict_alpha, list(graph.nodes))
alpha_obj = Alpha_obj({'alpha_matrix': alpha_matrix})
elif which_alpha == 'uniform':
alpha = np.random.uniform(0.8, 1.2)
alpha_obj = Alpha_obj({'alpha': alpha})
elif which_alpha == 'undirected':
K_edges = {edge: np.random.uniform(0.8, 1.2) for edge in graph.edges} #undirected edges (i,j)
if parallel_CI == False:
alpha_obj = Alpha_obj({'K_edges': K_edges})
else:
K_edges_matrix = from_dict_to_matrix(K_edges, list(graph.nodes), make_symmetrical=True)
alpha_obj = Alpha_obj({'K_edges_matrix': K_edges_matrix})
elif which_alpha == 'nodal':
K_nodes = {node: np.random.uniform(0.8, 1.2) for node in graph.nodes} #alpha is associated to a node: alpha_ij = alpha_i
if parallel_CI == False:
alpha_obj = Alpha_obj({'K_nodes': K_nodes})
else:
K_nodes_vector = from_dict_to_vector(K_nodes, list(graph.nodes))
alpha_obj = Alpha_obj({'K_nodes_vector': K_nodes_vector})