-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfigures_paper.py
2097 lines (1877 loc) · 98.6 KB
/
figures_paper.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
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ['TF_CPP_MIN_LOG_LEVEL'] = "3"
from collections import defaultdict
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import gridspec
import data
import utils
import models
import unit_metric_computers as umc
plt.rcParams.update({'font.size': 22, })
output_layers_2_levels = {
"vgg16": {
"block2_pool": "Early (block2_pool)",
"block4_pool": "Mid (block4_pool)",
"block5_pool": "Late (block5_pool)",
"fc2": "Penultimate (fc2)",
},
"vgg16_untrained": {
"block2_pool": "Early (block2_pool)",
"block4_pool": "Mid (block4_pool)",
"block5_pool": "Late (block5_pool)",
"fc2": "Penultimate (fc2)",
},
"resnet50": {
"conv2_block3_out": "Early (conv2_block3_out)",
"conv4_block6_out": "Mid (conv4_block6_out)",
"conv5_block2_out": "Late (conv5_block2_out)",
"avg_pool": "Penultimate (avg_pool)",
},
"resnet50_untrained": {
"conv2_block3_out": "Early (conv2_block3_out)",
"conv4_block6_out": "Mid (conv4_block6_out)",
"conv5_block2_out": "Late (conv5_block2_out)",
"avg_pool": "Penultimate (avg_pool)",
},
"vit_b16": {
"layer_3": "Early (layer_3)",
"layer_6": "Mid (layer_6)",
"layer_9": "Late (layer_9)",
"layer_12": "Penultimate (layer_12)",
},
"vit_b16_untrained": {
"layer_3": "Early (layer_3)",
"layer_6": "Mid (layer_6)",
"layer_9": "Late (layer_9)",
"layer_12": "Penultimate (layer_12)",
},
}
model_names_2_pretty_names = {
"vgg16": "VGG-16",
"vgg16_untrained": "VGG-16 (untrained)",
"resnet50": "ResNet-50",
"resnet50_untrained": "ResNet-50 (untrained)",
"vit_b16": "ViT-B/16",
"vit_b16_untrained": "ViT-B/16 (untrained)",
}
def _convert_mse_to_physical_unit(mse, error_type, normalized=True):
"""
Convert MSE error back to physical sense (Unity units or degree).
For location and distance error, we first take the square root of MSE,
which results in 'how far off the prediction is from truth' in terms of
the relative coordinate system where the targets are defined (from -5 to 5
on each axis). We then convert this error to Unity units. In Unity, the length
of the moving area is 2, which means a wall with length=10 in the relative
coordinate system is 2 in Unity. Therefore, the square root of MSE needs
further scaled down by 5 to map error back to Unity units.
For rotation error, we map the error back to degree by first
taking the square root of MSE, which gives 'how many intervals'
is the prediction off, and since we have 24 intervals out of 360 degrees,
we can map the error back to degree by multiplying the square root of MSE
by 360/24.
If `normalized=True`, we further normalize the error by dividing it by the
maximum possible error, which is 2 for location and distance error, and 180
for rotation error.
`normalized` can be set by `normalize_error` in the global scope.
"""
coordinate_system_to_unity_scale = 2 / 10
if error_type == 'loc' or error_type == 'dist':
if normalized:
return np.sqrt(mse) * coordinate_system_to_unity_scale / 2
return np.sqrt(mse) * coordinate_system_to_unity_scale
elif error_type == 'rot':
if normalized:
return np.sqrt(mse) * 360/24 / 180
return np.sqrt(mse) * 360/24
else:
raise ValueError(f"Unknown error type: {error_type}")
def decoding_each_model_across_layers_and_sr():
envs = ['env28_r24']
env = envs[0]
movement_mode = '2d'
sampling_rates = [0.1, 0.2, 0.3, 0.4, 0.5]
random_seeds = [42]
model_names = [
'vgg16',
'vgg16_untrained',
'resnet50', 'resnet50_untrained',
'vit_b16', 'vit_b16_untrained'
]
moving_trajectory = 'uniform'
decoding_model_choice = {'name': 'ridge_regression', 'hparams': 1.0}
decoding_model_name = decoding_model_choice['name']
decoding_model_hparams = decoding_model_choice['hparams']
feature_selection = 'l2'
error_types = ['loc', 'rot', 'dist']
tracked_metrics = ['mse', 'ci', 'baseline_predict_mid_mse', 'baseline_predict_random_mse']
for model_name in model_names:
output_layers = data.load_model_layers(model_name)
results_collector = \
defaultdict( # key - error_type
lambda: defaultdict( # key - output_layer
lambda: defaultdict(list) # key - metric
)
)
for error_type in error_types:
if 'loc' in error_type or 'rot' in error_type:
experiment = 'loc_n_rot'
elif 'dist' in error_type:
experiment = 'border_dist'
for output_layer in output_layers:
for sampling_rate in sampling_rates:
# sampling rate would be the base dimension where
# we accumulate results in a list to plot at once.
to_average_over_seeds = defaultdict(list)
for random_seed in random_seeds:
results_path = \
f'results/{env}/{movement_mode}/{moving_trajectory}/'\
f'{model_name}/{experiment}/{feature_selection}/'\
f'{decoding_model_name}_{decoding_model_hparams}/'\
f'{output_layer}/sr{sampling_rate}/seed{random_seed}'
results = np.load(f'{results_path}/res.npy', allow_pickle=True).item()[error_type]
for metric in tracked_metrics:
to_average_over_seeds[metric].append(results[metric])
# per metric per output layer
# across sampling rates averaged over seeds
for metric in tracked_metrics:
# a special case is when metric=='ci' where
# ..res[metric] is a list of 2 elements
# so we need to average wrt each element across seeds
# and save them back as 2 elements for later plotting.
if metric == 'ci':
ci_low_avg = np.mean(
[ci[0] for ci in to_average_over_seeds[metric]])
ci_high_avg = np.mean(
[ci[1] for ci in to_average_over_seeds[metric]])
avg_res = [ci_low_avg, ci_high_avg]
else:
avg_res = np.mean(to_average_over_seeds[metric])
results_collector[error_type][output_layer][metric].append(avg_res)
# plot collected results.
fig, axes = plt.subplots(1, len(error_types), figsize=(18, 5))
for i, error_type in enumerate(error_types):
for output_layer in output_layers:
for metric in tracked_metrics:
# when metric is about confidence interval,
# instead of plot, we fill_between
if metric == 'ci':
ci_low = np.array(
results_collector[error_type][output_layer][metric])[:, 0]
ci_high = np.array(
results_collector[error_type][output_layer][metric])[:, 1]
# TEMP
ci_low = _convert_mse_to_physical_unit(ci_low, error_type, normalized=normalize_error)
ci_high = _convert_mse_to_physical_unit(ci_high, error_type, normalized=normalize_error)
axes[i].fill_between(
sampling_rates,
ci_low,
ci_high,
alpha=1,
color='#DADADA',
)
else:
if 'baseline' in metric:
# no need to label baseline for each layer
# we only going to label baseline when we plot
# the last layer.
if output_layer == output_layers[-1]:
if 'mid' in metric:
label = 'baseline: center'
else:
label = 'baseline: random'
else:
label = None
if 'mid' in metric:
color = '#8B9FA5'
else:
color = '#9ABA79'
else:
# for non-baseline layer performance,
# we label each layer and use layer-specific color.
label = output_layers_2_levels[model_name][output_layer]
if "predictions" in label: label = "logits"
color = data.load_envs_dict(model_name, envs)[
f'{envs[0]}_{movement_mode}_{model_name}_{output_layer}']['color']
# either baseline or non-baseline layer performance,
# we always plot them.
axes[i].plot(
sampling_rates,
# results_collector[error_type][output_layer][metric],
# TEMP
_convert_mse_to_physical_unit(
np.array(results_collector[error_type][output_layer][metric]),
error_type,
normalized=normalize_error,
),
label=label,
color=color,
marker='o',
)
axes[i].set_xlabel('Sampling rate')
axes[i].set_xticks(sampling_rates)
axes[i].set_xticklabels(sampling_rates)
if normalize_error is True:
ax_label = 'Normalized Error'
elif normalize_error is False:
ax_label = 'Error (physical)'
else:
raise ValueError(f"Unknown value for normalize_error: {normalize_error}")
if error_type == 'loc':
title = 'Location Decoding'
axes[i].set_ylabel(ax_label)
elif error_type == 'rot':
title = 'Direction Decoding'
axes[i].set_ylabel(ax_label)
elif error_type == 'dist':
title = 'Nearest Border Decoding'
axes [i].set_ylabel(ax_label)
axes[i].set_title(title)
axes[i].spines.right.set_visible(False)
axes[i].spines.top.set_visible(False)
plt.subplots_adjust(right=0.8)
plt.legend(fontsize=22, loc='upper left', bbox_to_anchor=(1, 1))
plt.tight_layout()
if normalize_error is True:
plt.savefig(f'figs/paper/decoding_{model_name}.png')
plt.savefig(f'figs/paper/decoding_{model_name}.svg')
elif normalize_error is False:
plt.savefig(f'figs/paper/decoding_{model_name}_unnorm.png')
plt.savefig(f'figs/paper/decoding_{model_name}_unnorm.svg')
else:
raise ValueError(f"Unknown value for normalize_error: {normalize_error}")
plt.close()
def TEMP__decoding_each_model_across_layers_and_sr_V2():
envs = ['env28_r24']
env = envs[0]
movement_mode = '2d'
sampling_rates = [0.1, 0.2, 0.3, 0.4, 0.5]
random_seeds = [42]
model_names = ['vgg16', 'vgg16_untrained',
'resnet50', 'resnet50_untrained',
'vit_b16', 'vit_b16_untrained']
moving_trajectory = 'uniform'
decoding_model_choice = {'name': 'ridge_regression', 'hparams': 1.0}
decoding_model_name = decoding_model_choice['name']
decoding_model_hparams = decoding_model_choice['hparams']
feature_selection = 'l2'
error_types = ['loc', 'rot', 'dist']
tracked_metrics = ['mse', 'ci', 'baseline_predict_mid_mse', 'baseline_predict_random_mse']
for model_name in model_names:
output_layers = data.load_model_layers(model_name)
results_collector = \
defaultdict( # key - error_type
lambda: defaultdict( # key - output_layer
lambda: defaultdict(list) # key - metric
)
)
for error_type in error_types:
if 'loc' in error_type or 'rot' in error_type:
experiment = 'loc_n_rot'
elif 'dist' in error_type:
experiment = 'border_dist'
for output_layer in output_layers:
for sampling_rate in sampling_rates:
# sampling rate would be the base dimension where
# we accumulate results in a list to plot at once.
to_average_over_seeds = defaultdict(list)
for random_seed in random_seeds:
results_path = \
f'results/{env}/{movement_mode}/{moving_trajectory}/'\
f'{model_name}/{experiment}/{feature_selection}/'\
f'{decoding_model_name}_{decoding_model_hparams}/'\
f'{output_layer}/sr{sampling_rate}/seed{random_seed}'
results = np.load(f'{results_path}/res.npy', allow_pickle=True).item()[error_type]
for metric in tracked_metrics:
to_average_over_seeds[metric].append(results[metric])
# per metric per output layer
# across sampling rates averaged over seeds
for metric in tracked_metrics:
# a special case is when metric=='ci' where
# ..res[metric] is a list of 2 elements
# so we need to average wrt each element across seeds
# and save them back as 2 elements for later plotting.
if metric == 'ci':
ci_low_avg = np.mean(
[ci[0] for ci in to_average_over_seeds[metric]])
ci_high_avg = np.mean(
[ci[1] for ci in to_average_over_seeds[metric]])
avg_res = [ci_low_avg, ci_high_avg]
else:
avg_res = np.mean(to_average_over_seeds[metric])
results_collector[error_type][output_layer][metric].append(avg_res)
# plot collected results.
# fig, axes = plt.subplots(1, len(error_types), figsize=(15, 5))
fig, (axes_row1, axes_row2) = plt.subplots(2, len(error_types), figsize=(12, 8))
for i, error_type in enumerate(error_types):
for output_layer in output_layers:
for metric in tracked_metrics:
# when metric is about confidence interval,
# instead of plot, we fill_between
if metric == 'ci':
ci_low = np.array(
results_collector[error_type][output_layer][metric])[:, 0]
ci_high = np.array(
results_collector[error_type][output_layer][metric])[:, 1]
# TEMP
ci_low = _convert_mse_to_physical_unit(ci_low, error_type, normalized=normalize_error)
ci_high = _convert_mse_to_physical_unit(ci_high, error_type, normalized=normalize_error)
axes_row2[i].fill_between(
sampling_rates,
ci_low,
ci_high,
alpha=1,
color='#DADADA',
)
else:
if 'baseline' in metric:
# no need to label baseline for each layer
# we only going to label baseline when we plot
# the last layer.
if output_layer == output_layers[-1]:
if 'mid' in metric:
label = 'baseline: center'
else:
label = 'baseline: random'
else:
label = None
if 'mid' in metric:
color = '#8B9FA5'
else:
color = '#9ABA79'
ax_to_plot = axes_row1[i]
else:
# for non-baseline layer performance,
# we label each layer and use layer-specific color.
label = output_layer
if "predictions" in label: label = "logits"
color = data.load_envs_dict(model_name, envs)[
f'{envs[0]}_{movement_mode}_{model_name}_{output_layer}']['color']
ax_to_plot = axes_row2[i]
# either baseline or non-baseline layer performance,
# we always plot them.
ax_to_plot.plot(
sampling_rates,
# results_collector[error_type][output_layer][metric],
# TEMP
_convert_mse_to_physical_unit(
np.array(results_collector[error_type][output_layer][metric]),
error_type,
normalized=normalize_error,
),
label=label,
color=color,
marker='o',
)
if error_type == 'loc':
title = 'Location Decoding'
axes_row1[i].set_ylabel("Normalized Error")
axes_row2[i].set_ylabel("Normalized Error")
elif error_type == 'rot':
title = 'Direction Decoding'
axes_row1[i].set_ylabel("Normalized Error")
axes_row2[i].set_ylabel("Normalized Error")
elif error_type == 'dist':
title = 'Nearest Border Decoding'
axes_row1[i].set_ylabel("Normalized Error")
axes_row2[i].set_ylabel("Normalized Error")
axes_row2[i].set_xlabel('Sampling rate')
axes_row2[i].set_xticks(sampling_rates)
axes_row2[i].set_xticklabels(sampling_rates)
axes_row1[i].spines['bottom'].set_visible(False)
axes_row1[i].spines['top'].set_visible(False)
axes_row1[i].spines['right'].set_visible(False)
axes_row2[i].spines['right'].set_visible(False)
axes_row2[i].spines['top'].set_visible(False)
axes_row1[i].set_xticks([])
axes_row1[i].set_title(title)
if i == 0: subplot_label = 'A'
elif i == 1: subplot_label = 'B'
elif i == 2: subplot_label = 'C'
axes_row1[i].text(-0.2, 1.1, subplot_label, fontsize=14, fontweight='bold',
transform=axes_row1[i].transAxes, va='top', ha='left')
# Add diagonal lines to connect the subplots
d = 0.015 # How big to make the diagonal lines in axes coordinates
kwargs = dict(transform=axes_row1[i].transAxes, color='k', clip_on=False)
axes_row1[i].plot((-d, +d), (-d, +d), **kwargs) # top-left diagonal line
kwargs.update(transform=axes_row2[i].transAxes) # switch to the bottom subplot
axes_row2[i].plot((-d, +d), (1 - d, 1 + d), **kwargs) # bottom-left diagonal line
axes_row1[-1].legend(loc='upper right')
axes_row2[-1].legend(loc='upper right')
# fig.supylabel('Virtual environment units')
fig.tight_layout(rect=[0, 0.0, 1, 0.99])
plt.savefig(f'figs/paper/decoding_{model_name}.png')
plt.close()
def decoding_all_models_one_layer_one_sr_V1():
envs = ['env28_r24']
env = envs[0]
movement_mode = '2d'
sampling_rates = [0.3]
random_seeds = [42]
model_names = ['vgg16', 'vgg16_untrained',
'resnet50', 'resnet50_untrained',
'vit_b16', 'vit_b16_untrained']
moving_trajectory = 'uniform'
decoding_model_choice = {'name': 'ridge_regression', 'hparams': 1.0}
decoding_model_name = decoding_model_choice['name']
decoding_model_hparams = decoding_model_choice['hparams']
feature_selection = 'l2'
error_types = ['loc', 'rot', 'dist']
tracked_metrics = ['mse', 'ci', 'baseline_predict_mid_mse', 'baseline_predict_random_mse']
results_collector = \
defaultdict( # key - error_type
lambda: defaultdict( # key - model_name
lambda: defaultdict( # key - output_layer
lambda: defaultdict(list) # key - metric
)
)
)
for error_type in error_types:
if 'loc' in error_type or 'rot' in error_type:
experiment = 'loc_n_rot'
elif 'dist' in error_type:
experiment = 'border_dist'
for model_name in model_names:
if 'vgg16' in model_name: output_layer = 'block5_pool'
elif 'resnet50' in model_name: output_layer = 'avg_pool'
elif 'vit' in model_name: output_layer = 'layer_12'
for sampling_rate in sampling_rates:
# sampling rate would be the base dimension where
# we accumulate results in a list to plot at once.
to_average_over_seeds = defaultdict(list)
for random_seed in random_seeds:
results_path = \
f'results/{env}/{movement_mode}/{moving_trajectory}/'\
f'{model_name}/{experiment}/{feature_selection}/'\
f'{decoding_model_name}_{decoding_model_hparams}/'\
f'{output_layer}/sr{sampling_rate}/seed{random_seed}'
results = np.load(f'{results_path}/res.npy', allow_pickle=True).item()[error_type]
for metric in tracked_metrics:
to_average_over_seeds[metric].append(results[metric])
# per metric per output layer
# across sampling rates averaged over seeds
for metric in tracked_metrics:
# a special case is when metric=='ci' where
# ..res[metric] is a list of 2 elements
# so we need to average wrt each element across seeds
# and save them back as 2 elements for later plotting.
if metric == 'ci':
ci_low_avg = np.mean(
[ci[0] for ci in to_average_over_seeds[metric]])
ci_high_avg = np.mean(
[ci[1] for ci in to_average_over_seeds[metric]])
avg_res = [ci_low_avg, ci_high_avg]
else:
avg_res = np.mean(to_average_over_seeds[metric])
results_collector[error_type][model_name][output_layer][metric].append(avg_res)
# plot collected results.
fig, axes = plt.subplots(1, len(error_types), figsize=(15, 5))
for i, error_type in enumerate(error_types):
for x_i, model_name in enumerate(model_names):
model_name = model_names[x_i]
if 'vgg16' in model_name: output_layer = 'block5_pool'
elif 'resnet50' in model_name: output_layer = 'avg_pool'
elif 'vit' in model_name: output_layer = 'layer_12'
mse = np.array(
results_collector[error_type][model_name][output_layer]['mse'])
ci_low = np.array(
results_collector[error_type][model_name][output_layer]['ci'])[:, 0]
ci_high = np.array(
results_collector[error_type][model_name][output_layer]['ci'])[:, 1]
axes[i].errorbar(
x_i,
mse,
yerr=[mse-ci_low, ci_high-mse],
label=model_name,
marker='o',
capsize=5,
)
# only highlight if the model is trained
# using axvspan
if 'untrained' not in model_name:
axes[i].axvspan(x_i-0.5, x_i+0.5, facecolor='grey', alpha=0.3)
# baselines are the same for all models
# so we only plot them once as plot
baseline_predict_mid_mse = np.array(
results_collector[error_type][model_name][output_layer]['baseline_predict_mid_mse'])
axes[i].plot(
range(len(model_names)),
baseline_predict_mid_mse.repeat(len(model_names)),
label='baseline: center',
color='cyan',
)
baseline_predict_random_mse = np.array(
results_collector[error_type][model_name][output_layer]['baseline_predict_random_mse'])
axes[i].plot(
range(len(model_names)),
baseline_predict_random_mse.repeat(len(model_names)),
label='baseline: random',
color='blue',
)
# axes[i].set_xlabel('Model')
axes[i].set_ylabel('Decoding error (MSE)')
axes[i].set_xticks(range(len(model_names)))
axes[i].set_xticklabels(model_names, rotation=90)
if error_type == 'loc': title = 'Location Decoding'
elif error_type == 'rot': title = 'Direction Decoding'
elif error_type == 'dist': title = 'Distance to Nearest Border Decoding'
axes[i].set_title(title)
axes[i].spines.right.set_visible(False)
axes[i].spines.top.set_visible(False)
plt.tight_layout()
plt.legend(loc='upper right')
plt.savefig(f'figs/paper/decoding_across_models.png')
plt.close()
def decoding_all_models_one_layer_one_sr():
"""
ref:
https://stackoverflow.com/questions/5656798/is-there-a-way-to-make-a-discontinuous-axis-in-matplotlib
"""
envs = ['env28_r24']
env = envs[0]
movement_mode = '2d'
sampling_rates = [0.3]
random_seeds = [42]
model_names = [
'vgg16',
'vgg16_untrained',
'resnet50', 'resnet50_untrained',
'vit_b16', 'vit_b16_untrained'
]
moving_trajectory = 'uniform'
decoding_model_choice = {'name': 'ridge_regression', 'hparams': 1.0}
decoding_model_name = decoding_model_choice['name']
decoding_model_hparams = decoding_model_choice['hparams']
feature_selection = 'l2'
error_types = ['loc', 'rot', 'dist']
tracked_metrics = ['mse', 'ci', 'baseline_predict_mid_mse', 'baseline_predict_random_mse']
results_collector = \
defaultdict( # key - error_type
lambda: defaultdict( # key - model_name
lambda: defaultdict( # key - output_layer
lambda: defaultdict(list) # key - metric
)
)
)
for error_type in error_types:
if 'loc' in error_type or 'rot' in error_type:
experiment = 'loc_n_rot'
elif 'dist' in error_type:
experiment = 'border_dist'
for model_name in model_names:
if 'vgg16' in model_name: output_layer = 'block5_pool'
elif 'resnet50' in model_name: output_layer = 'avg_pool'
elif 'vit' in model_name: output_layer = 'layer_12'
for sampling_rate in sampling_rates:
# sampling rate would be the base dimension where
# we accumulate results in a list to plot at once.
to_average_over_seeds = defaultdict(list)
for random_seed in random_seeds:
results_path = \
f'results/{env}/{movement_mode}/{moving_trajectory}/'\
f'{model_name}/{experiment}/{feature_selection}/'\
f'{decoding_model_name}_{decoding_model_hparams}/'\
f'{output_layer}/sr{sampling_rate}/seed{random_seed}'
results = np.load(f'{results_path}/res.npy', allow_pickle=True).item()[error_type]
for metric in tracked_metrics:
to_average_over_seeds[metric].append(results[metric])
# per metric per output layer
# across sampling rates averaged over seeds
for metric in tracked_metrics:
# a special case is when metric=='ci' where
# ..res[metric] is a list of 2 elements
# so we need to average wrt each element across seeds
# and save them back as 2 elements for later plotting.
if metric == 'ci':
ci_low_avg = np.mean(
[ci[0] for ci in to_average_over_seeds[metric]])
ci_high_avg = np.mean(
[ci[1] for ci in to_average_over_seeds[metric]])
avg_res = [ci_low_avg, ci_high_avg]
else:
avg_res = np.mean(to_average_over_seeds[metric])
results_collector[error_type][model_name][output_layer][metric].append(avg_res)
# plot collected results.
fig, (axes_row1, axes_row2) = plt.subplots(2, len(error_types), figsize=(18, 5))
for i, error_type in enumerate(error_types):
for x_i, model_name in enumerate(model_names):
model_name = model_names[x_i]
if 'vgg16' in model_name:
output_layer = 'block5_pool'
fillcolor = '#33539E'
elif 'resnet50' in model_name:
output_layer = 'avg_pool'
fillcolor = '#BFBBDA'
elif 'vit' in model_name:
output_layer = 'layer_12'
fillcolor = '#A5678E'
mse = np.array(
results_collector[error_type][model_name][output_layer]['mse'])
ci_low = np.array(
results_collector[error_type][model_name][output_layer]['ci'])[:, 0]
ci_high = np.array(
results_collector[error_type][model_name][output_layer]['ci'])[:, 1]
# TEMP
mse = _convert_mse_to_physical_unit(mse, error_type, normalized=normalize_error)
ci_low = _convert_mse_to_physical_unit(ci_low, error_type, normalized=normalize_error)
ci_high = _convert_mse_to_physical_unit(ci_high, error_type, normalized=normalize_error)
if 'untrained' in model_name:
edgecolor = fillcolor
fillcolor = 'white'
else:
edgecolor = None
# plot barplot with error bars
axes_row2[i].bar(
x_i,
mse,
yerr=[mse-ci_low, ci_high-mse],
label=model_name,
color=fillcolor,
edgecolor=edgecolor,
capsize=5,
)
# baselines are the same for all models
# so we only plot them once as plot
baseline_predict_mid_mse = np.array(
results_collector[error_type][model_name][output_layer]['baseline_predict_mid_mse'])
# TEMP
baseline_predict_mid_mse = _convert_mse_to_physical_unit(
baseline_predict_mid_mse, error_type, normalized=normalize_error
)
axes_row1[i].plot(
range(len(model_names)),
baseline_predict_mid_mse.repeat(len(model_names)),
label='baseline: center',
color='#8B9FA5',
)
baseline_predict_random_mse = np.array(
results_collector[error_type][model_name][output_layer]['baseline_predict_random_mse'])
# TEMP
baseline_predict_random_mse = _convert_mse_to_physical_unit(
baseline_predict_random_mse, error_type, normalized=normalize_error
)
axes_row1[i].plot(
range(len(model_names)),
baseline_predict_random_mse.repeat(len(model_names)),
label='baseline: random',
color='#9ABA79',
)
# set ylim with a bit of margin
# two baselines can be different magnitude,
# so the upper bound is the max of the two with margin,
# and the lower bound is the min of the two with margin.
max_of_two_baseline = np.max(
np.concatenate([baseline_predict_mid_mse, baseline_predict_random_mse])
)
min_of_two_baseline = np.min(
np.concatenate([baseline_predict_mid_mse, baseline_predict_random_mse])
)
axes_row1[i].set_ylim(
min_of_two_baseline-1,
max_of_two_baseline+1
)
if normalize_error is True:
ax_label = 'Normalized Error'
elif normalize_error is False:
ax_label = 'Error (physical)'
else:
raise ValueError(f"Unknown value for normalize_error: {normalize_error}")
if error_type == 'loc':
title = 'Location Decoding'
axes_row2[i].set_ylabel(' '*14+ax_label)
axes_row1[i].set_ylim(0.2, 1.05)
elif error_type == 'rot':
title = 'Direction Decoding'
axes_row2[i].set_ylabel(' '*14+ax_label, labelpad=10)
elif error_type == 'dist':
title = 'Nearest Border Decoding'
axes_row2[i].set_ylabel(' '*14+ax_label)
axes_row1[i].set_ylim(0.2, 1.05)
axes_row1[i].set_title(title)
axes_row1[i].spines['bottom'].set_visible(False)
axes_row1[i].spines['top'].set_visible(False)
axes_row1[i].spines['right'].set_visible(False)
axes_row2[i].spines['right'].set_visible(False)
axes_row2[i].spines['top'].set_visible(False)
axes_row1[i].set_xticks([])
axes_row2[i].set_xticks(range(len(model_names)))
# pretty model names
pretty_model_names = []
for model_name in model_names:
if model_name == 'vgg16': pretty_model_names.append('VGG-16')
if model_name == 'vgg16_untrained': pretty_model_names.append('VGG-16\n(untrained)')
if model_name == 'resnet50': pretty_model_names.append('ResNet-50')
if model_name == 'resnet50_untrained': pretty_model_names.append('ResNet-50\n(untrained)')
if model_name == 'vit_b16': pretty_model_names.append('ViT-B/16')
if model_name == 'vit_b16_untrained': pretty_model_names.append('ViT-B/16\n(untrained)')
# if there is untrained in model_name, make the label font color grey
# otherwise use the default black.
axes_row2[i].set_xticklabels(pretty_model_names, rotation=90)
for x_i, model_name in enumerate(model_names):
if 'untrained' in model_name:
axes_row2[i].get_xticklabels()[x_i].set_color('grey')
# Add diagonal lines to connect the subplots
d = 0.015 # How big to make the diagonal lines in axes coordinates
kwargs = dict(transform=axes_row1[i].transAxes, color='k', clip_on=False)
axes_row1[i].plot((-d, +d), (-d, +d), **kwargs) # top-left diagonal line
kwargs.update(transform=axes_row2[i].transAxes) # switch to the bottom subplot
axes_row2[i].plot((-d, +d), (1 - d, 1 + d), **kwargs) # bottom-left diagonal line
fig.tight_layout(rect=(0.02, 0, 1, 0.99))
if normalize_error is True:
plt.savefig(f'figs/paper/decoding_across_models.svg')
plt.savefig(f'figs/paper/decoding_across_models.pdf')
elif normalize_error is False:
plt.savefig(f'figs/paper/decoding_across_models_unnorm.svg')
plt.savefig(f'figs/paper/decoding_across_models_unnorm.pdf')
else:
raise ValueError(f"Unknown value for normalize_error: {normalize_error}")
plt.close()
def unit_chart_type_against_coef_each_model_across_layers():
experiment = 'unit_chart_by_coef'
envs = ['env28_r24']
movement_mode = '2d'
sampling_rate = 0.3
random_seed = 42
model_names = ['vgg16', 'resnet50', 'vit_b16']
moving_trajectory = 'uniform'
decoding_model_choice = {'name': 'ridge_regression', 'hparams': 1.0}
feature_selection = 'l2'
filterings = [
{'filtering_order': 'top_n', 'n_units_filtering': None, 'p_units_filtering': 0.1},
{'filtering_order': 'random_n', 'n_units_filtering': None, 'p_units_filtering': 0.1},
{'filtering_order': 'mid_n', 'n_units_filtering': None, 'p_units_filtering': 0.1},
]
unit_type_to_column_index_in_unit_chart = {
'place_cell_1': {
'num_clusters': 1,
},
'place_cell_2': {
'max_value_in_clusters': 3,
},
'border_cell': {
'borderness': 9,
},
'direction_cell': {
'mean_vector_length': 10,
},
}
for model_name in model_names:
output_layers = data.load_model_layers(model_name)
# each model has a figure,
# each row of a figure is a model layer
# each column of a figure is a unit type (assoc. task)
# e.g. axes[output_layer_i, metric_i]
fig, axes = plt.subplots(
len(output_layers), len(unit_type_to_column_index_in_unit_chart),
figsize=(5*len(unit_type_to_column_index_in_unit_chart), 5*len(output_layers))
)
envs_dict = data.load_envs_dict(model_name, envs)
config_versions=list(envs_dict.keys())
# ken: suboptimal but each config_version is unique assoc. with a layer.
for output_layer_i, config_version in enumerate(config_versions):
output_layer = envs_dict[config_version]['output_layer']
for unit_type_i, unit_type in enumerate(unit_type_to_column_index_in_unit_chart.keys()):
metric = list(unit_type_to_column_index_in_unit_chart[unit_type].keys())[0]
print(
f'[Plotting] {model_name} {output_layer} {unit_type} {metric} {config_version}'
)
if 'place_cell' in unit_type:
reference_experiment = 'loc_n_rot'
target = 'loc'
elif unit_type == 'direction_cell':
reference_experiment = 'loc_n_rot'
target = 'rot'
elif unit_type == 'border_cell':
reference_experiment = 'border_dist'
target = 'border_dist'
# load presaved unit_chart info sorted by coef
# using top, random, or mid filtering.
# the unit_chart_info to be loaded needs to be
# first computed by `inspect_model_units.py`
config = utils.load_config(config_version)
results_path = utils.load_results_path(
config=config,
experiment=experiment,
reference_experiment=reference_experiment,
feature_selection=feature_selection,
decoding_model_choice=decoding_model_choice,
sampling_rate=sampling_rate,
moving_trajectory=moving_trajectory,
random_seed=random_seed,
)
for filtering in filterings:
p_units_filtering = filtering['p_units_filtering']
filtering_order = filtering['filtering_order']
unit_chart_info = np.load(
f'{results_path}/unit_chart_{target}_{filtering_order}_{p_units_filtering}.npy',
allow_pickle=True
)
# plot distribution of metric and coef based on filtering_order
# `type_id` is the column index in unit_chart_info
type_id = unit_type_to_column_index_in_unit_chart[unit_type][metric]
# NOTE: not every type_id has the same data structure,
# e.g. for per unit place fields info, some columns might be ndarray
# such as num_pixels_in_clusters where if the unit has multiple clusters,
# the entry for that unit for that column, will be an ndarray.
# So for plotting, we need to unpack these arrays.
unit_chart_info_unpacked = []
for x in unit_chart_info[:, type_id]:
if isinstance(x, np.ndarray):
unit_chart_info_unpacked.extend(x)
else:
unit_chart_info_unpacked.append(x)
if 'top' in filtering_order:
label = f'top {int(p_units_filtering*100):,}%'
color = 'green'
elif 'random' in filtering_order:
label = f'random {int(p_units_filtering*100):,}%'
color = 'purple'
elif 'mid' in filtering_order:
label = f'middle {int(p_units_filtering*100):,}%'
color = 'orange'
sns.kdeplot(
unit_chart_info_unpacked,
label=label,
color=color,
alpha=0.2,
fill=True,
ax=axes[output_layer_i, unit_type_i],
)
if metric == 'num_clusters':
title = 'Place Tuning (1)'
x_label = 'Number of Place Fields'
elif metric == 'max_value_in_clusters':
title = 'Place Tuning (2)'
x_label = 'Max Activity in Place Fields'
elif metric == 'borderness':
title = 'Border Tuning'
x_label = 'Border Tuning Strength'
elif metric == 'mean_vector_length':
title = 'Direction Tuning'
x_label = 'Directional Tuning Strength'
axes[output_layer_i, unit_type_i].set_xlabel(x_label)
axes[output_layer_i, unit_type_i].set_title(f'{title} ({output_layer})')
axes[output_layer_i, unit_type_i].spines.right.set_visible(False)
axes[output_layer_i, unit_type_i].spines.top.set_visible(False)
axes[output_layer_i, 0].set_ylabel(f'Density')
axes[output_layer_i, -1].legend(loc='upper right')
plt.tight_layout()
plt.savefig(f'figs/paper/unit_chart_against_coef_{model_name}.png')
def lesion_by_coef_each_model_across_layers_and_lr():
envs = ['env28_r24']
env = envs[0]
movement_mode = '2d'
sampling_rate = 0.3
random_seeds = [42]
model_names = ['vgg16', 'resnet50', 'vit_b16']
moving_trajectory = 'uniform'
decoding_model_choice = {'name': 'ridge_regression', 'hparams': 1.0}
decoding_model_name = decoding_model_choice['name']
decoding_model_hparams = decoding_model_choice['hparams']
base_feature_selection = 'l2'
error_types = ['loc', 'rot', 'dist']
tracked_metrics = ['mse', 'ci', 'baseline_predict_mid_mse', 'baseline_predict_random_mse']
ranks = ['top', 'random']
thr = 'thr'
lesion_metric = 'coef'
lesion_ratios = [0, 0.1, 0.3, 0.5, 0.7]
results_collector = \
defaultdict( # key - model_name
lambda: defaultdict( # key - lesion rank
lambda: defaultdict( # key - error_type
lambda: defaultdict( # key - output_layer
lambda: defaultdict(list) # key - metric
)
)
)
)
for model_name in model_names:
output_layers = data.load_model_layers(model_name)
for rank in ranks:
for error_type in error_types:
if 'loc' in error_type:
experiment = 'loc_n_rot'