forked from banilo/nips2015
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nips3mm.py
executable file
·1113 lines (979 loc) · 40.4 KB
/
nips3mm.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
"""
HCP: Semi-supervised network decomposition by low-rank logistic regression
"""
print __doc__
import os
import os.path as op
import numpy as np
import glob
from scipy.linalg import norm
import nibabel as nib
from sklearn.grid_search import RandomizedSearchCV
from sklearn.base import BaseEstimator
from sklearn.preprocessing import StandardScaler
from nilearn.input_data import NiftiMasker
from sklearn.metrics import precision_recall_fscore_support
from sklearn.metrics import confusion_matrix
import theano
import theano.tensor as T
from matplotlib import pylab as plt
print('Running THEANO on %s' % theano.config.device)
from nilearn.image import concat_imgs
import joblib
import time
RES_NAME = 'nips3mm'
WRITE_DIR = op.join(os.getcwd(), RES_NAME)
if not op.exists(WRITE_DIR):
os.mkdir(WRITE_DIR)
##############################################################################
# load+preprocess data
##############################################################################
mask_img = 'grey10_icbm_3mm_bin.nii.gz'
nifti_masker = NiftiMasker(mask_img=mask_img, smoothing_fwhm=False,
standardize=False)
nifti_masker.fit()
mask_nvox = nifti_masker.mask_img_.get_data().sum()
print('Loading data...')
# ARCHI task
X_task, labels = joblib.load('preload_HT_3mm')
labels = np.int32(labels)
# contrasts are IN ORDER -> shuffle!
new_inds = np.arange(0, X_task.shape[0])
np.random.shuffle(new_inds)
X_task = X_task[new_inds]
labels = labels[new_inds]
# subs = subs[new_inds]
# rest
# X_rest = nifti_masker.transform('preload_HR20persub_10mm_ero2.nii')
# X_rest = nifti_masker.transform('dump_rs_spca_s12_tmp')
rs_spca_data = joblib.load('dump_rs_spca_s12_tmp')
rs_spca_niis = nib.Nifti1Image(rs_spca_data,
nifti_masker.mask_img_.get_affine())
X_rest = nifti_masker.transform(rs_spca_niis)
del rs_spca_niis
del rs_spca_data
X_task = StandardScaler().fit_transform(X_task)
X_rest = StandardScaler().fit_transform(X_rest)
# ARCHI task
AT_niis, AT_labels, AT_subs = joblib.load('preload_AT_3mm')
AT_X = nifti_masker.transform(AT_niis)
AT_X = StandardScaler().fit_transform(AT_X)
print('done :)')
##############################################################################
# define computation graph
##############################################################################
class SSEncoder(BaseEstimator):
def __init__(self, n_hidden, gain1, learning_rate, max_epochs=100,
l1=0.1, l2=0.1, lambda_param=.5):
"""
Parameters
----------
lambda : float
Mediates between AE and LR. lambda==1 equates with LR only.
"""
self.n_hidden = n_hidden
self.gain1 = gain1
self.max_epochs = max_epochs
self.learning_rate = np.float32(learning_rate)
self.penalty_l1 = np.float32(l1)
self.penalty_l2 = np.float32(l2)
self.lambda_param = np.float32(lambda_param)
# def rectify(X):
# return T.maximum(0., X)
from theano.tensor.shared_randomstreams import RandomStreams
def RMSprop(self, cost, params, lr=0.001, rho=0.9, epsilon=1e-6):
grads = T.grad(cost=cost, wrt=params)
updates = []
for p, g in zip(params, grads):
acc = theano.shared(p.get_value() * 0.)
acc_new = rho * acc + (1 - rho) * g ** 2
gradient_scaling = T.sqrt(acc_new + epsilon)
g = g / gradient_scaling
updates.append((acc, acc_new))
updates.append((p, p - lr * g))
return updates
def get_param_pool(self):
cur_params = (
self.V1s, self.bV0, self.bV1,
self.W0s, self.W1s, self.bW0s, self.bW1s
)
return cur_params
def test_performance_in_other_dataset(self):
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import StratifiedShuffleSplit
compr_matrix = self.W0s.get_value().T # currently best compression
AT_X_compr = np.dot(compr_matrix, AT_X.T).T
clf = LogisticRegression(penalty='l1')
folder = StratifiedShuffleSplit(y=AT_labels, n_iter=5, test_size=0.2,
random_state=42)
acc_list = []
prfs_list = []
for (train_inds, test_inds) in folder:
clf.fit(AT_X_compr[train_inds, :], AT_labels[train_inds])
pred_y = clf.predict(AT_X_compr[test_inds, :])
acc = (pred_y == AT_labels[test_inds]).mean()
prfs_list.append(precision_recall_fscore_support(
AT_labels[test_inds], pred_y))
acc_list.append(acc)
compr_mean_acc = np.mean(acc_list)
prfs = np.asarray(prfs_list).mean(axis=0)
return compr_mean_acc, prfs
def fit(self, X_rest, X_task, y):
DEBUG_FLAG = True
# self.max_epochs = 333
self.batch_size = 100
n_input = X_rest.shape[1] # sklearn-like structure
n_output = n_input
rng = np.random.RandomState(42)
self.input_taskdata = T.matrix(dtype='float32', name='input_taskdata')
self.input_restdata = T.matrix(dtype='float32', name='input_restdata')
self.params_from_last_iters = []
index = T.iscalar(name='index')
# prepare data for theano computation
if not DEBUG_FLAG:
X_train_s = theano.shared(
value=np.float32(X_task), name='X_train_s')
y_train_s = theano.shared(
value=np.int32(y), name='y_train_s')
lr_train_samples = len(X_task)
else:
from sklearn.cross_validation import StratifiedShuffleSplit
folder = StratifiedShuffleSplit(y, n_iter=1, test_size=0.20)
new_trains, inds_val = iter(folder).next()
X_train, X_val = X_task[new_trains], X_task[inds_val]
y_train, y_val = y[new_trains], y[inds_val]
X_train_s = theano.shared(value=np.float32(X_train),
name='X_train_s', borrow=False)
y_train_s = theano.shared(value=np.int32(y_train),
name='y_train_s', borrow=False)
# X_val_s = theano.shared(value=np.float32(X_val),
# name='X_train_s', borrow=False)
# y_val_s = theano.shared(value=np.int32(y_val),
# name='y_cal_s', borrow=False)
lr_train_samples = len(X_train)
self.dbg_epochs_ = list()
self.dbg_acc_train_ = list()
self.dbg_acc_val_ = list()
self.dbg_ae_cost_ = list()
self.dbg_lr_cost_ = list()
self.dbg_ae_nonimprovesteps = list()
self.dbg_acc_other_ds_ = list()
self.dbg_combined_cost_ = list()
self.dbg_prfs_ = list()
self.dbg_prfs_other_ds_ = list()
X_rest_s = theano.shared(value=np.float32(X_rest), name='X_rest_s')
ae_train_samples = len(X_rest)
# V -> supervised / logistic regression
# W -> unsupervised / auto-encoder
# computational graph: auto-encoder
W0_vals = rng.randn(n_input, self.n_hidden).astype(np.float32) * self.gain1
self.W0s = theano.shared(W0_vals)
self.W1s = self.W0s.T # tied
bW0_vals = np.zeros(self.n_hidden).astype(np.float32)
self.bW0s = theano.shared(value=bW0_vals, name='bW0')
bW1_vals = np.zeros(n_output).astype(np.float32)
self.bW1s = theano.shared(value=bW1_vals, name='bW1')
givens_ae = {
self.input_restdata: X_rest_s[
index * self.batch_size:(index + 1) * self.batch_size]
}
encoding = (self.input_restdata.dot(self.W0s) + self.bW0s).dot(self.W1s) + self.bW1s
self.ae_loss = T.sum((self.input_restdata - encoding) ** 2, axis=1)
self.ae_cost = (
T.mean(self.ae_loss) / n_input
)
# params1 = [self.W0s, self.bW0s, self.bW1s]
# gparams1 = [T.grad(cost=self.ae_cost, wrt=param1) for param1 in params1]
#
# lr = self.learning_rate
# updates = self.RMSprop(cost=self.ae_cost, params=params1,
# lr=self.learning_rate)
# f_train_ae = theano.function(
# [index],
# [self.ae_cost],
# givens=givens_ae,
# updates=updates)
# computation graph: logistic regression
clf_n_output = 18 # number of labels
my_y = T.ivector(name='y')
bV0_vals = np.zeros(self.n_hidden).astype(np.float32)
self.bV0 = theano.shared(value=bV0_vals, name='bV0')
bV1_vals = np.zeros(clf_n_output).astype(np.float32)
self.bV1 = theano.shared(value=bV1_vals, name='bV1')
# V0_vals = rng.randn(n_input, self.n_hidden).astype(np.float32) * self.gain1
V1_vals = rng.randn(self.n_hidden, clf_n_output).astype(np.float32) * self.gain1
# self.V0s = theano.shared(V0_vals)
self.V1s = theano.shared(V1_vals)
self.p_y_given_x = T.nnet.softmax(
# T.dot(T.dot(self.input_taskdata, self.V0s) + self.bV0, self.V1s) + self.bV1
T.dot(T.dot(self.input_taskdata, self.W0s) + self.bV0, self.V1s) + self.bV1
)
self.lr_cost = -T.mean(T.log(self.p_y_given_x)[T.arange(my_y.shape[0]), my_y])
self.lr_cost = (
self.lr_cost +
T.mean(abs(self.W0s)) * self.penalty_l1 +
# T.mean(abs(self.V0s)) * self.penalty_l1 +
T.mean(abs(self.bV0)) * self.penalty_l1 +
T.mean(abs(self.V1s)) * self.penalty_l1 +
T.mean(abs(self.bV1)) * self.penalty_l1 +
T.mean((self.W0s ** np.float32(2))) * self.penalty_l2 +
# T.mean((self.V0s ** 2)) * self.penalty_l2 +
T.mean((self.bV0 ** np.float32(2))) * self.penalty_l2 +
T.mean((self.V1s ** np.float32(2))) * self.penalty_l2 +
T.mean((self.bV1 ** np.float32(2))) * self.penalty_l2
)
self.y_pred = T.argmax(self.p_y_given_x, axis=1)
givens_lr = {
self.input_taskdata: X_train_s[index * self.batch_size:(index + 1) * self.batch_size],
my_y: y_train_s[index * self.batch_size:(index + 1) * self.batch_size]
}
# params2 = [self.V0s, self.bV0, self.V1s, self.bV1]
# params2 = [self.W0s, self.bV0, self.V1s, self.bV1]
# updates2 = self.RMSprop(cost=self.lr_cost, params=params2,
# lr=self.learning_rate)
# f_train_lr = theano.function(
# [index],
# [self.lr_cost],
# givens=givens_lr,
# updates=updates2)
# combined loss for AE and LR
combined_params = [self.W0s, self.bW0s, self.bW1s,
# self.V0s, self.V1s, self.bV0, self.bV1]
self.V1s, self.bV0, self.bV1]
self.combined_cost = (
(np.float32(1) - self.lambda_param) * self.ae_cost +
self.lambda_param * self.lr_cost
)
combined_updates = self.RMSprop(
cost=self.combined_cost,
params=combined_params,
lr=self.learning_rate)
givens_combined = {
self.input_restdata: X_rest_s[index * self.batch_size:(index + 1) * self.batch_size],
self.input_taskdata: X_train_s[index * self.batch_size:(index + 1) * self.batch_size],
my_y: y_train_s[index * self.batch_size:(index + 1) * self.batch_size]
}
f_train_combined = theano.function(
[index],
[self.combined_cost, self.ae_cost, self.lr_cost],
givens=givens_combined,
updates=combined_updates, allow_input_downcast=True)
# optimization loop
start_time = time.time()
ae_last_cost = np.inf
lr_last_cost = np.inf
no_improve_steps = 0
acc_train, acc_val = 0., 0.
for i_epoch in range(self.max_epochs):
if i_epoch == 1:
epoch_dur = time.time() - start_time
total_mins = (epoch_dur * self.max_epochs) / 60
hs, mins = divmod(total_mins, 60)
print("Max estimated duration: %i hours and %i minutes" % (hs, mins))
# AE
# if i_epoch % 2 == 0: # every second time
#if False:
# auto-encoder
ae_n_batches = ae_train_samples // self.batch_size
lr_n_batches = lr_train_samples // self.batch_size
# for i in range(lr_n_batches):
# for i in range(max(ae_n_batches, lr_n_batches)):
# if i < ae_n_batches:
# ae_cur_cost = float(f_train_ae(i)[0])
# ae_cur_cost = 0
# if i < lr_n_batches:
# lr_cur_cost = float(f_train_lr(i)[0])
# for i in range(lr_n_batches):
for i in range(min(ae_n_batches, lr_n_batches)):
# lr_cur_cost = f_train_lr(i)[0]
# ae_cur_cost = lr_cur_cost
combined_cost, ae_cur_cost, lr_cur_cost = f_train_combined(i)
# evaluate epoch cost
if ae_last_cost - ae_cur_cost < 0.1:
no_improve_steps += 1
else:
ae_last_cost = ae_cur_cost
no_improve_steps = 0
# logistic
lr_last_cost = lr_cur_cost
acc_train = self.score(X_train, y_train)
acc_val, prfs_val = self.score(X_val, y_val, return_prfs=True)
print('E:%i, ae_cost:%.4f, lr_cost:%.4f, train_score:%.2f, vald_score:%.2f, ae_badsteps:%i' % (
i_epoch + 1, ae_cur_cost, lr_cur_cost, acc_train, acc_val, no_improve_steps))
if (i_epoch % 10 == 0):
self.dbg_ae_cost_.append(ae_cur_cost)
self.dbg_lr_cost_.append(lr_cur_cost)
self.dbg_combined_cost_.append(combined_cost)
self.dbg_epochs_.append(i_epoch + 1)
self.dbg_ae_nonimprovesteps.append(no_improve_steps)
self.dbg_acc_train_.append(acc_train)
self.dbg_acc_val_.append(acc_val)
self.dbg_prfs_.append(prfs_val)
# test out-of-dataset performance
od_acc, prfs_other = self.test_performance_in_other_dataset()
self.dbg_acc_other_ds_.append(od_acc)
self.dbg_prfs_other_ds_.append(prfs_other)
print('out-of-dataset acc: %.2f' % od_acc)
# save paramters from last 100 iterations
if i_epoch > (self.max_epochs - 100):
print('Param pool!')
param_pool = self.get_param_pool()
self.params_from_last_iters.append(param_pool)
total_mins = (time.time() - start_time) / 60
hs, mins = divmod(total_mins, 60)
print("Final duration: %i hours and %i minutes" % (hs, mins))
return self
def predict(self, X):
X_test_s = theano.shared(value=np.float32(X), name='X_test_s', borrow=True)
givens_te = {
self.input_taskdata: X_test_s
}
f_test = theano.function(
[],
[self.y_pred],
givens=givens_te)
predictions = f_test()
del X_test_s
del givens_te
return predictions[0]
def score(self, X, y, return_prfs=False):
pred_y = self.predict(X)
acc = np.mean(pred_y == y)
prfs = precision_recall_fscore_support(pred_y, y)
if return_prfs:
return acc, prfs
else:
return acc
##############################################################################
# plot figures
##############################################################################
def dump_comps(masker, compressor, components, threshold=2, fwhm=None,
perc=None):
from scipy.stats import zscore
from nilearn.plotting import plot_stat_map
from nilearn.image import smooth_img
from scipy.stats import scoreatpercentile
if isinstance(compressor, basestring):
comp_name = compressor
else:
comp_name = compressor.__str__().split('(')[0]
for i_c, comp in enumerate(components):
path_mask = op.join(WRITE_DIR, '%s_%i-%i' % (comp_name,
n_comp, i_c + 1))
nii_raw = masker.inverse_transform(comp)
nii_raw.to_filename(path_mask + '.nii.gz')
comp_z = zscore(comp)
if perc is not None:
cur_thresh = scoreatpercentile(np.abs(comp_z), per=perc)
path_mask += '_perc%i' % perc
print('Applying percentile %.2f (threshold: %.2f)' % (perc, cur_thresh))
else:
cur_thresh = threshold
path_mask += '_thr%.2f' % cur_thresh
print('Applying threshold: %.2f' % cur_thresh)
nii_z = masker.inverse_transform(comp_z)
gz_path = path_mask + '_zmap.nii.gz'
nii_z.to_filename(gz_path)
plot_stat_map(gz_path, bg_img='colin.nii', threshold=cur_thresh,
cut_coords=(0, -2, 0), draw_cross=False,
output_file=path_mask + 'zmap.png')
# optional: do smoothing
if fwhm is not None:
nii_z_fwhm = smooth_img(nii_z, fwhm=fwhm)
plot_stat_map(nii_z_fwhm, bg_img='colin.nii', threshold=cur_thresh,
cut_coords=(0, -2, 0), draw_cross=False,
output_file=path_mask +
('zmap_%imm.png' % fwhm))
n_comps = [20]
# n_comps = [40, 30, 20, 10, 5]
for n_comp in n_comps:
# for lambda_param in [0]:
for lambda_param in [0.50]:
l1 = 0.1
l2 = 0.1
my_title = r'Low-rank LR + AE (combined loss, shared decomp): n_comp=%i L1=%.1f L2=%.1f lambda=%.2f res=3mm spca20RS' % (
n_comp, l1, l2, lambda_param
)
print(my_title)
estimator = SSEncoder(
n_hidden=n_comp,
gain1=0.004, # empirically determined by CV
learning_rate = np.float32(0.00001), # empirically determined by CV,
max_epochs=500, l1=l1, l2=l2, lambda_param=lambda_param)
estimator.fit(X_rest, X_task, labels)
fname = my_title.replace(' ', '_').replace('+', '').replace(':', '').replace('__', '_').replace('%', '')
cur_path = op.join(WRITE_DIR, fname)
joblib.dump(estimator, cur_path)
# estimator = joblib.load(cur_path)
# plt.savefig(cur_path + '_SUMMARY.png', dpi=200)
# dump data also as numpy array
np.save(cur_path + 'dbg_epochs_', np.array(estimator.dbg_epochs_))
np.save(cur_path + 'dbg_acc_train_', np.array(estimator.dbg_acc_train_))
np.save(cur_path + 'dbg_acc_val_', np.array(estimator.dbg_acc_val_))
np.save(cur_path + 'dbg_ae_cost_', np.array(estimator.dbg_ae_cost_))
np.save(cur_path + 'dbg_lr_cost_', np.array(estimator.dbg_lr_cost_))
np.save(cur_path + 'dbg_ae_nonimprovesteps', np.array(estimator.dbg_ae_nonimprovesteps))
np.save(cur_path + 'dbg_acc_other_ds_', np.array(estimator.dbg_acc_other_ds_))
np.save(cur_path + 'dbg_combined_cost_', np.array(estimator.dbg_combined_cost_))
np.save(cur_path + 'dbg_prfs_', np.array(estimator.dbg_prfs_))
np.save(cur_path + 'dbg_prfs_other_ds_', np.array(estimator.dbg_prfs_other_ds_))
W0_mat = estimator.W0s.get_value().T
np.save(cur_path + 'W0comps', W0_mat)
V1_mat = estimator.V1s.get_value().T
np.save(cur_path + 'V1comps', V1_mat)
# dump_comps(nifti_masker, fname, comps, threshold=0.5)
STOP_CALCULATION
# equally scaled plots
import re
pkgs = glob.glob(RES_NAME + '/*dbg_epochs*.npy')
dbg_epochs_ = np.load(pkgs[0])
dbg_epochs_ = np.load(pkgs[0])
d = {
'training accuracy': '/*dbg_acc_train*.npy',
'accuracy val': '/*dbg_acc_val_*.npy',
'accuracy other ds': '/*dbg_acc_other_ds_*.npy',
'loss ae': '/*dbg_ae_cost_*.npy',
'loss lr': '/*dbg_lr_cost_*.npy',
'loss combined': '/*dbg_combined_cost_*.npy'
}
n_comps = [20]
path_vanilla = 'nips3mm_vanilla'
for k, v in d.iteritems():
pkgs = glob.glob(RES_NAME + v)
for n_comp in n_comps:
plt.figure()
for p in pkgs:
lambda_param = np.float(re.search('lambda=(.{4})', p).group(1))
# n_hidden = int(re.search('comp=(?P<comp>.{1,2,3})_', p).group('comp'))
n_hidden = int(re.search('comp=(.{1,3})_', p).group(1))
if n_comp != n_hidden:
continue
dbg_acc_train_ = np.load(p)
cur_label = 'n_comp=%i' % n_hidden
cur_label += '/'
cur_label += 'lambda=%.2f' % lambda_param
cur_label += '/'
if not '_AE' in p:
cur_label += 'LR only!'
elif 'subRS' in p:
cur_label += 'RSnormal'
elif 'spca20RS' in p:
cur_label += 'RSspca20'
elif 'pca20RS' in p:
cur_label += 'RSpca20'
cur_label += '/'
cur_label += 'separate decomp.' if 'decomp_separate' in p else 'joint decomp.'
cur_label += '' if '_AE' in p else '/LR only!'
plt.plot(
dbg_epochs_,
dbg_acc_train_,
label=cur_label)
if k == 'training accuracy' or k == 'accuracy val':
van_pkgs = glob.glob(path_vanilla + v)
vanilla_values = np.load(van_pkgs[0])
plt.plot(
dbg_epochs_,
vanilla_values,
label='LR')
plt.title('Low-rank LR+AE L1=0.1 L2=0.1 res=3mm combined-loss')
plt.legend(loc='lower right', fontsize=9)
plt.yticks(np.linspace(0., 1., 11))
plt.ylabel(k)
plt.xlabel('epochs')
plt.ylim(0., 1.05)
plt.grid(True)
plt.show()
plt.savefig(op.join(WRITE_DIR,
k.replace(' ', '_') + '_%icomps.png' % n_comp))
pkgs = glob.glob(RES_NAME + '/*dbg_acc_val_*.npy')
for n_comp in n_comps: #
plt.figure()
for p in pkgs:
lambda_param = np.float(re.search('lambda=(.{4})', p).group(1))
# n_hidden = int(re.search('comp=(?P<comp>.{1,2,3})_', p).group('comp'))
n_hidden = int(re.search('comp=(.{1,3})_', p).group(1))
if n_comp != n_hidden:
continue
dbg_acc_val_ = np.load(p)
cur_label = 'n_comp=%i' % n_hidden
cur_label += '/'
cur_label += 'lambda=%.2f' % lambda_param
cur_label += '/'
if not '_AE' in p:
cur_label += 'LR only!'
elif 'subRS' in p:
cur_label += 'RSnormal'
elif 'pca20RS' in p:
cur_label += 'RSpca20'
cur_label += '/'
cur_label += 'separate decomp.' if 'decomp_separate' in p else 'joint decomp.'
plt.plot(
dbg_epochs_,
dbg_acc_val_,
label=cur_label)
plt.title('Low-rank LR+AE L1=0.1 L2=0.1 res=3mm combined-loss')
plt.legend(loc='lower right', fontsize=9)
plt.yticks(np.linspace(0., 1., 11))
plt.ylabel('validation set accuracy')
plt.ylim(0., 1.05)
plt.xlabel('epochs')
plt.grid(True)
plt.show()
plt.savefig(op.join(WRITE_DIR, 'accuracy_val_%icomps.png' % n_comp))
pkgs = glob.glob(RES_NAME + '/*dbg_acc_other_ds_*.npy')
for n_comp in n_comps: #
plt.figure()
for p in pkgs:
lambda_param = np.float(re.search('lambda=(.{4})', p).group(1))
n_hidden = int(re.search('comp=(.{1,3})_', p).group(1))
if n_comp != n_hidden:
continue
dbg_acc_other_ds_ = np.load(p)
cur_label = 'n_comp=%i' % n_hidden
cur_label += '/'
cur_label += 'lambda=%.2f' % lambda_param
cur_label += '/'
if not '_AE' in p:
cur_label += 'LR only!'
elif 'subRS' in p:
cur_label += 'RSnormal'
elif 'pca20RS' in p:
cur_label += 'RSpca20'
cur_label += '/'
cur_label += 'separate decomp.' if 'decomp_separate' in p else 'joint decomp.'
plt.plot(
dbg_epochs_,
dbg_acc_other_ds_,
label=cur_label)
plt.title('Low-rank LR+AE L1=0.1 L2=0.1 res=3mm combined-loss')
plt.legend(loc='lower right', fontsize=9)
plt.yticks(np.linspace(0., 1., 11))
plt.ylabel('ARCHI dataset accuracy')
plt.ylim(0., 1.05)
plt.xlabel('epochs')
plt.grid(True)
plt.show()
plt.savefig(op.join(WRITE_DIR, 'accuracy_archi_%icomps.png' % n_comp))
pkgs = glob.glob(RES_NAME + '/*dbg_ae_cost_*.npy')
for n_comp in n_comps: # AE
plt.figure()
for p in pkgs:
lambda_param = np.float(re.search('lambda=(.{4})', p).group(1))
n_hidden = int(re.search('comp=(.{1,3})_', p).group(1))
if n_comp != n_hidden:
continue
dbg_ae_cost_ = np.load(p)
cur_label = 'n_comp=%i' % n_hidden
cur_label += '/'
cur_label += 'lambda=%.2f' % lambda_param
cur_label += '/'
if not '_AE' in p:
cur_label += 'LR only!'
elif 'subRS' in p:
cur_label += 'RSnormal'
elif 'pca20RS' in p:
cur_label += 'RSpca20'
cur_label += '/'
cur_label += 'separate decomp.' if 'decomp_separate' in p else 'joint decomp.'
plt.plot(
dbg_epochs_,
dbg_ae_cost_,
label=cur_label)
plt.title('Low-rank LR+AE L1=0.1 L2=0.1 res=3mm combined-loss')
plt.legend(loc='lower right', fontsize=9)
# plt.yticks(np.linspace(0., 1., 11))
plt.ylabel('AE loss')
plt.xlabel('epochs')
plt.grid(True)
plt.show()
plt.savefig(op.join(WRITE_DIR, 'loss_ae_%icomps.png' % n_comp))
pkgs = glob.glob(RES_NAME + '/*dbg_lr_cost_*.npy') # LR cost
for n_comp in n_comps: # AE
plt.figure()
for p in pkgs:
lambda_param = np.float(re.search('lambda=(.{4})', p).group(1))
n_hidden = int(re.search('comp=(.{1,3})_', p).group(1))
if n_comp != n_hidden:
continue
dbg_lr_cost_ = np.load(p)
cur_label = 'n_comp=%i' % n_hidden
cur_label += '/'
cur_label += 'lambda=%.2f' % lambda_param
cur_label += '/'
if not '_AE' in p:
cur_label += 'LR only!'
elif 'subRS' in p:
cur_label += 'RSnormal'
elif 'pca20RS' in p:
cur_label += 'RSpca20'
cur_label += '/'
cur_label += 'separate decomp.' if 'decomp_separate' in p else 'joint decomp.'
plt.plot(
dbg_epochs_,
dbg_lr_cost_,
label=cur_label)
plt.title('Low-rank LR+AE L1=0.1 L2=0.1 res=3mm combined-loss')
plt.legend(loc='lower right', fontsize=9)
# plt.yticks(np.linspace(0., 1., 11))
plt.ylabel('LR loss')
plt.xlabel('epochs')
plt.grid(True)
plt.show()
plt.savefig(op.join(WRITE_DIR, 'loss_lr_%icomps.png' % n_comp))
pkgs = glob.glob(RES_NAME + '/*dbg_combined_cost_*.npy') # combined loss
for n_comp in n_comps: # AE
plt.figure()
for p in pkgs:
lambda_param = np.float(re.search('lambda=(.{4})', p).group(1))
n_hidden = int(re.search('comp=(.{1,3})_', p).group(1))
if n_comp != n_hidden:
continue
dbg_combined_cost_ = np.load(p)
cur_label = 'n_comp=%i' % n_hidden
cur_label += '/'
cur_label += 'lambda=%.2f' % lambda_param
cur_label += '/'
if not '_AE' in p:
cur_label += 'LR only!'
elif 'subRS' in p:
cur_label += 'RSnormal'
elif 'pca20RS' in p:
cur_label += 'RSpca20'
cur_label += '/'
cur_label += 'separate decomp.' if 'decomp_separate' in p else 'joint decomp.'
plt.plot(
dbg_epochs_,
dbg_combined_cost_,
label=cur_label)
plt.title('Low-rank LR+AE L1=0.1 L2=0.1 res=3mm combined-loss')
plt.legend(loc='lower right', fontsize=9)
# plt.yticks(np.linspace(0., 1., 11))
plt.ylabel('combined loss')
plt.xlabel('epochs')
plt.grid(True)
plt.show()
plt.savefig(op.join(WRITE_DIR, 'loss_combined_%icomps.png' % n_comp))
# precision / recall / f1
target_lambda = 0.5
pkgs = glob.glob(RES_NAME + '/*lambda=%.2f*dbg_prfs_.npy' % target_lambda)
for n_comp in n_comps:
plt.figure()
for p in pkgs:
lambda_param = np.float(re.search('lambda=(.{4})', p).group(1))
n_hidden = int(re.search('comp=(?P<comp>.{1,3})_', p).group('comp'))
if n_comp != n_hidden:
continue
dbg_prfs_ = np.load(p)
cur_label = 'n_comp=%i' % n_hidden
cur_label += '/'
cur_label += 'lambda=%.2f' % lambda_param
cur_label += '/'
if not '_AE' in p:
cur_label += 'LR only!'
elif 'subRS' in p:
cur_label += 'RSnormal'
elif 'pca20RS' in p:
cur_label += 'RSpca20'
cur_label += '/'
cur_label += 'separate decomp.' if 'decomp_separate' in p else 'joint decomp.'
for i in np.arange(18):
plt.plot(
dbg_epochs_,
np.array(dbg_prfs_)[:, 0, i],
label='task %i' % (i + 1))
plt.title('Low-rank LR+AE L1=0.1 L2=0.1 res=3mm combined-loss lambda=%.2f' %
target_lambda)
plt.legend(loc='lower right', fontsize=9)
# plt.yticks(np.linspace(0., 1., 11))
plt.ylabel('in-dataset precisions')
plt.ylim(0., 1.05)
plt.xlabel('epochs')
plt.grid(True)
plt.show()
plt.savefig(op.join(WRITE_DIR, 'prec_inds_lambda=%0.2f_%icomps.png' %
(target_lambda, n_comp)))
# in-dataset recall at lambda=0.5
pkgs = glob.glob(RES_NAME + '/*lambda=%.2f*dbg_prfs_.npy' % target_lambda)
for n_comp in n_comps:
plt.figure()
for p in pkgs:
lambda_param = np.float(re.search('lambda=(.{4})', p).group(1))
n_hidden = int(re.search('comp=(?P<comp>.{1,3})_', p).group('comp'))
if n_comp != n_hidden:
continue
dbg_prfs_ = np.load(p)
dbg_prfs_ = np.load(p)
cur_label = 'n_comp=%i' % n_hidden
cur_label += '/'
cur_label += 'lambda=%.2f' % lambda_param
cur_label += '/'
if not '_AE' in p:
cur_label += 'LR only!'
elif 'subRS' in p:
cur_label += 'RSnormal'
elif 'pca20RS' in p:
cur_label += 'RSpca20'
cur_label += '/'
cur_label += 'separate decomp.' if 'decomp_separate' in p else 'joint decomp.'
for i in np.arange(18):
plt.plot(
dbg_epochs_,
np.array(dbg_prfs_)[:, 1, i],
label='task %i' % (i + 1))
plt.title('Low-rank LR+AE L1=0.1 L2=0.1 res=3mm combined-loss lambda=%.2f' %
target_lambda)
plt.legend(loc='lower right', fontsize=9)
# plt.yticks(np.linspace(0., 1., 11))
plt.ylabel('in-dataset recall')
plt.ylim(0., 1.05)
plt.xlabel('epochs')
plt.grid(True)
plt.show()
plt.savefig(op.join(WRITE_DIR, 'rec_inds_lambda=%0.2f_%icomps.png' %
(target_lambda, n_comp)))
# in-dataset f1 at lambda=0.5
pkgs = glob.glob(RES_NAME + '/*lambda=%.2f*dbg_prfs_.npy' % target_lambda)
for n_comp in n_comps:
plt.figure()
for p in pkgs:
lambda_param = np.float(re.search('lambda=(.{4})', p).group(1))
n_hidden = int(re.search('comp=(?P<comp>.{1,3})_', p).group('comp'))
if n_comp != n_hidden:
continue
dbg_prfs_ = np.load(p)
cur_label = 'n_comp=%i' % n_hidden
cur_label += '/'
cur_label += 'lambda=%.2f' % lambda_param
cur_label += '/'
if not '_AE' in p:
cur_label += 'LR only!'
elif 'subRS' in p:
cur_label += 'RSnormal'
elif 'pca20RS' in p:
cur_label += 'RSpca20'
cur_label += '/'
cur_label += 'separate decomp.' if 'decomp_separate' in p else 'joint decomp.'
for i in np.arange(18):
plt.plot(
dbg_epochs_,
np.array(dbg_prfs_)[:, 2, i],
label='task %i' % (i + 1))
plt.title('Low-rank LR+AE L1=0.1 L2=0.1 res=3mm combined-loss lambda=%.2f' %
target_lambda)
plt.legend(loc='lower right', fontsize=9)
# plt.yticks(np.linspace(0., 1., 11))
plt.ylabel('in-dataset f1 score')
plt.ylim(0., 1.05)
plt.xlabel('epochs')
plt.grid(True)
plt.show()
plt.savefig(op.join(WRITE_DIR, 'f1_inds_lambda=%0.2f_%icomps.png' %
(target_lambda, n_comp)))
# out-of-dataset precision at lambda=0.5
pkgs = glob.glob(RES_NAME + '/*lambda=%.2f*dbg_prfs_other_ds_.npy' % target_lambda)
for n_comp in n_comps:
plt.figure()
for p in pkgs:
lambda_param = np.float(re.search('lambda=(.{4})', p).group(1))
n_hidden = int(re.search('comp=(?P<comp>.{1,3})_', p).group('comp'))
if n_comp != n_hidden:
continue
dbg_prfs_other_ds_ = np.load(p)
cur_label = 'n_comp=%i' % n_hidden
cur_label += '/'
cur_label += 'lambda=%.2f' % lambda_param
cur_label += '/'
if not '_AE' in p:
cur_label += 'LR only!'
elif 'subRS' in p:
cur_label += 'RSnormal'
elif 'pca20RS' in p:
cur_label += 'RSpca20'
cur_label += '/'
cur_label += 'separate decomp.' if 'decomp_separate' in p else 'joint decomp.'
for i in np.arange(18):
plt.plot(
dbg_epochs_,
np.array(dbg_prfs_other_ds_)[:, 0, i],
label='task %i' % (i + 1))
plt.title('Low-rank LR+AE L1=0.1 L2=0.1 res=3mm combined-loss lambda=%.2f' %
target_lambda)
plt.legend(loc='lower right', fontsize=9)
# plt.yticks(np.linspace(0., 1., 11))
plt.ylabel('out-of-dataset precisions')
plt.ylim(0., 1.05)
plt.xlabel('epochs')
plt.grid(True)
plt.show()
plt.savefig(op.join(WRITE_DIR, 'prec_oods_lambda=%0.2f_%icomps.png' %
(target_lambda, n_comp)))
# out-of-dataset recall at lambda=0.5
pkgs = glob.glob(RES_NAME + '/*lambda=%.2f*dbg_prfs_other_ds_.npy' % target_lambda)
for n_comp in n_comps:
plt.figure()
for p in pkgs:
lambda_param = np.float(re.search('lambda=(.{4})', p).group(1))
n_hidden = int(re.search('comp=(?P<comp>.{1,3})_', p).group('comp'))
if n_comp != n_hidden:
continue
dbg_prfs_other_ds_ = np.load(p)
cur_label = 'n_comp=%i' % n_hidden
cur_label += '/'
cur_label += 'lambda=%.2f' % lambda_param
cur_label += '/'
if not '_AE' in p:
cur_label += 'LR only!'
elif 'subRS' in p:
cur_label += 'RSnormal'
elif 'pca20RS' in p:
cur_label += 'RSpca20'
cur_label += '/'
cur_label += 'separate decomp.' if 'decomp_separate' in p else 'joint decomp.'
for i in np.arange(18):
plt.plot(
dbg_epochs_,
np.array(dbg_prfs_other_ds_)[:, 1, i],
label='task %i' % (i + 1))
plt.title('Low-rank LR+AE L1=0.1 L2=0.1 res=3mm combined-loss lambda=%.2f' %
target_lambda)
plt.legend(loc='lower right', fontsize=9)
# plt.yticks(np.linspace(0., 1., 11))
plt.ylabel('out-of-dataset recall')
plt.ylim(0., 1.05)
plt.xlabel('epochs')
plt.grid(True)
plt.show()
plt.savefig(op.join(WRITE_DIR, 'rec_oods_lambda=%0.2f_%icomps.png' %
(target_lambda, n_comp)))
# out-of-dataset f1 at lambda=0.5
pkgs = glob.glob(RES_NAME + '/*lambda=%.2f*dbg_prfs_other_ds_.npy' % target_lambda)
for n_comp in n_comps:
plt.figure()
for p in pkgs:
lambda_param = np.float(re.search('lambda=(.{4})', p).group(1))
n_hidden = int(re.search('comp=(?P<comp>.{1,3})_', p).group('comp'))
if n_comp != n_hidden:
continue
dbg_prfs_other_ds_ = np.load(p)
cur_label = 'n_comp=%i' % n_hidden
cur_label += '/'
cur_label += 'lambda=%.2f' % lambda_param
cur_label += '/'
if not '_AE' in p:
cur_label += 'LR only!'
elif 'subRS' in p:
cur_label += 'RSnormal'
elif 'pca20RS' in p:
cur_label += 'RSpca20'
cur_label += '/'
cur_label += 'separate decomp.' if 'decomp_separate' in p else 'joint decomp.'
for i in np.arange(18):
plt.plot(
dbg_epochs_,
np.array(dbg_prfs_other_ds_)[:, 2, i],
label='task %i' % (i + 1))
plt.title('Low-rank LR+AE L1=0.1 L2=0.1 res=3mm combined-loss lambda=%.2f' %
target_lambda)
plt.legend(loc='lower right', fontsize=9)
# plt.yticks(np.linspace(0., 1., 11))
plt.ylabel('out-of-dataset f1 score')
plt.ylim(0., 1.05)
plt.xlabel('epochs')
plt.grid(True)