-
Notifications
You must be signed in to change notification settings - Fork 1
/
inspect_model_units_V1.py
1768 lines (1566 loc) · 71.8 KB
/
inspect_model_units_V1.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"
import time
import logging
import itertools
import multiprocessing
import cv2
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
import utils
import data
import models
import scores
"""
Visualize individual model units see
if there are any patterns (e.g., place cells.)
"""
def _is_dead_unit(heatmap):
"""
Given a unit's 2D heatmap, check if it is a dead unit.
"""
# return np.allclose(heatmap, 0)
# unit is dead if less than 1% of the heatmap is active
return np.sum(heatmap > 0) < 0.01 * heatmap.shape[0] * heatmap.shape[1]
def _single_model_reps(config):
"""
Produce model_reps either directly computing if the first time,
or load from disk if already computed.
return:
model_reps: \in (n_locations, n_rotations, n_features)
"""
os.environ["TF_NUM_INTRAOP_THREADS"] = f"{TF_NUM_INTRAOP_THREADS}"
os.environ["TF_NUM_INTEROP_THREADS"] = "1"
model_reps_fname = \
f'results/'\
f'{config["unity_env"]}/'\
f'{config["movement_mode"]}/'\
f'{config["model_name"]}/'\
f'model_reps_{config["output_layer"]}.npy'
if os.path.exists(model_reps_fname):
logging.info(f'Loading model_reps from {model_reps_fname}')
model_reps = np.load(model_reps_fname)
logging.info(f'model_reps.shape: {model_reps.shape}')
return model_reps
else:
# load model outputs
if config['model_name'] == 'none':
model = None
preprocess_func = None
else:
model, preprocess_func = models.load_model(
config['model_name'], config['output_layer'])
preprocessed_data = data.load_preprocessed_data(
config=config,
data_path=\
f"data/unity/"\
f"{config['unity_env']}/"\
f"{config['movement_mode']}",
movement_mode=config['movement_mode'],
env_x_min=config['env_x_min'],
env_x_max=config['env_x_max'],
env_y_min=config['env_y_min'],
env_y_max=config['env_y_max'],
multiplier=config['multiplier'],
n_rotations=config['n_rotations'],
preprocess_func=preprocess_func,
)
# (n_locations*n_rotations, n_features)
model_reps = data.load_full_dataset_model_reps(
config, model, preprocessed_data
)
# reshape to (n_locations, n_rotations, n_features)
model_reps = model_reps.reshape(
(model_reps.shape[0] // config['n_rotations'], # n_locations
config['n_rotations'], # n_rotations
model_reps.shape[1]) # all units
)
# save to disk
# # TODO: slow to save but is it benefitcial as we do it only once?
# logging.info(f'Saving model_reps to {model_reps_fname}...')
# np.save(model_reps_fname, model_reps)
# logging.info(f'[Saved] model_reps to {model_reps_fname}')
return model_reps
def _single_env_viz_units_ranked_by_coef(
config_version,
experiment,
reference_experiment,
feature_selection,
decoding_model_choice,
sampling_rate,
moving_trajectory,
random_seed,
filterings,
):
"""
Plot individual model units as heatmaps both
1. each rotation independently and
2. summed over rotations.
"""
os.environ["TF_NUM_INTRAOP_THREADS"] = f"{TF_NUM_INTRAOP_THREADS}"
os.environ["TF_NUM_INTEROP_THREADS"] = "1"
config = utils.load_config(config_version)
reference_experiment_results_path = \
utils.load_results_path(
config=config,
experiment=reference_experiment, # Dirty but coef is saved in loc_n_rot
feature_selection=feature_selection,
decoding_model_choice=decoding_model_choice,
sampling_rate=sampling_rate,
moving_trajectory=moving_trajectory,
random_seed=random_seed,
)
logging.info(
f'Loading results (for coef) from {reference_experiment_results_path}'
)
if reference_experiment_results_path is None:
logging.info(
f'Mismatch between feature '\
f'selection and decoding model, skip.'
)
return
movement_mode=config['movement_mode']
env_x_min=config['env_x_min']
env_x_max=config['env_x_max']
env_y_min=config['env_y_min']
env_y_max=config['env_y_max']
multiplier=config['multiplier']
# load model outputs
model_reps = _single_model_reps(config)
# TODO: feature selection based on rob metric or l1/l2
# notice, one complexity is coef is x, y, rot
# whereas rob metric may not be differentiating (x, y)
# one idea is to separately plot for x, y, rot
if feature_selection in ['l1', 'l2']:
# load regression coefs as selection criteria
# for model_reps (per unit)
targets = ['x', 'y', 'rot']
coef = \
np.load(
f'{reference_experiment_results_path}/res.npy',
allow_pickle=True).item()['coef'] # (n_targets, n_features)
logging.info(f'Loaded coef.shape: {coef.shape}')
# Due to meeting 24-May-2023, we use absolute
# values of coef for filtering.
coef = np.abs(coef)
for target_index in range(coef.shape[0]):
# filter columns of `model_reps`
# based on each coef of each target
# based on `n_units_filtering` and `filtering_order`
for filtering in filterings:
n_units_filtering = filtering['n_units_filtering']
filtering_order = filtering['filtering_order']
if filtering_order == 'top_n':
filtered_n_units_indices = np.argsort(
coef[target_index, :])[::-1][:n_units_filtering]
elif filtering_order == 'mid_n':
filtered_n_units_indices = np.argsort(
coef[target_index, :])[::-1][
int(coef.shape[1]/2)-int(n_units_filtering/2):
int(coef.shape[1]/2)+int(n_units_filtering/2)]
elif filtering_order == 'random_n':
# randomly sample n_units_filtering units
# but excluding the top_n (also n_units_filtering)
np.random.seed(random_seed)
filtered_n_units_indices = np.random.choice(
np.argsort(
coef[target_index, :])[::-1][n_units_filtering:],
n_units_filtering,
replace=False)
else:
raise NotImplementedError
# fig, axes = plt.subplots(
# nrows=n_units_filtering,
# ncols=model_reps.shape[1],
# figsize=(600, 600)
# )
# for unit_rank, unit_index in enumerate(filtered_n_units_indices):
# for rotation in range(model_reps.shape[1]):
# if movement_mode == '2d':
# # reshape to (n_locations, n_rotations, n_features)
# heatmap = model_reps[:, rotation, unit_index].reshape(
# (env_x_max*multiplier-env_x_min*multiplier+1,
# env_y_max*multiplier-env_y_min*multiplier+1)
# )
# # rotate heatmap to match Unity coordinate system
# # ref: tests/testReshape_forHeatMap.py
# heatmap = np.rot90(heatmap, k=1, axes=(0, 1))
# # plot heatmap
# axes[unit_rank, rotation].imshow(heatmap)
# axes[-1, rotation].set_xlabel('Unity x-axis')
# axes[unit_rank, 0].set_ylabel('Unity z-axis')
# axes[unit_rank, rotation].set_xticks([])
# axes[unit_rank, rotation].set_yticks([])
# sup_title = f"{filtering_order},{targets[target_index]}, "\
# f"{config['unity_env']},{movement_mode},"\
# f"{config['model_name']},{feature_selection}"\
# f"({decoding_model_choice['hparams']}),"\
# f"sr{sampling_rate},seed{random_seed}"
# figs_path = utils.load_figs_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,
# )
# # fix suptitle overlap.
# # fig.tight_layout(rect=[0, 0.03, 1, 0.98])
# plt.suptitle(sup_title)
# plt.savefig(
# f'{figs_path}/units_heatmaps_{targets[target_index]}'\
# f'_{filtering_order}.png'
# )
# plt.close()
# logging.info(
# f'[Saved] units heatmaps {targets[target_index]}'\
# f'{filtering_order} to {figs_path}'
# )
# plot summed over rotation heatmap and distribution of loc-wise
# activation intensities.
model_reps_summed = np.sum(
model_reps, axis=1, keepdims=True)
# 1 for heatmap, 1 for distribution
fig, axes = plt.subplots(
nrows=n_units_filtering,
ncols=2,
figsize=(5, 600)
)
for unit_rank, unit_index in enumerate(filtered_n_units_indices):
for rotation in range(model_reps_summed.shape[1]):
if movement_mode == '2d':
# reshape to (n_locations, n_rotations, n_features)
heatmap = model_reps_summed[:, rotation, unit_index].reshape(
(env_x_max*multiplier-env_x_min*multiplier+1,
env_y_max*multiplier-env_y_min*multiplier+1)
)
# rotate heatmap to match Unity coordinate system
# ref: tests/testReshape_forHeatMap.py
heatmap = np.rot90(heatmap, k=1, axes=(0, 1))
# # compute fields info and write them on the heatmap
# num_clusters, num_pixels_in_clusters, max_value_in_clusters, \
# mean_value_in_clusters, var_value_in_clusters, \
# bounds_heatmap = \
# _compute_single_heatmap_fields_info(
# heatmap=heatmap,
# pixel_min_threshold=10,
# pixel_max_threshold=int(heatmap.shape[0]*heatmap.shape[1]*0.5)
# )
# plot heatmap on the left column.
axes[unit_rank, 0].imshow(heatmap)
axes[-1, 0].set_xlabel('Unity x-axis')
axes[-1, 0].set_ylabel('Unity z-axis')
axes[unit_rank, 0].set_xticks([])
axes[unit_rank, 0].set_yticks([])
# axes[unit_rank, 0].set_title(
# f'rank{unit_rank},u{unit_index}\n'\
# f'coef{coef[target_index, unit_index]:.1f}'\
# f'{num_clusters},{num_pixels_in_clusters},{max_value_in_clusters} '\
# )
axes[unit_rank, 0].set_title(f'rank{unit_rank},u{unit_index}')
# # plot heatmap contour on the middle column.
# axes[unit_rank, 1].imshow(bounds_heatmap)
# plot distribution on the right column.
axes[unit_rank, 1].hist(
model_reps_summed[:, rotation, unit_index],
bins=10,
)
axes[-1, 1].set_xlabel('Activation intensity')
sup_title = f"{filtering_order},{targets[target_index]},"\
f"{config['unity_env']},{movement_mode},"\
f"{config['model_name']},{feature_selection}"\
f"({decoding_model_choice['hparams']}),"\
f"sr{sampling_rate},seed{random_seed}"
figs_path = utils.load_figs_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,
)
# fig.tight_layout(rect=[0, 0.03, 1, 0.95])
plt.tight_layout()
plt.suptitle(sup_title)
plt.savefig(
f'{figs_path}/units_heatmaps_{targets[target_index]}_'\
f'{filtering_order}_summed.png')
plt.close()
logging.info(
f'[Saved] units heatmaps {targets[target_index]} {filtering_order} '\
f'(summed) to {figs_path}')
else:
# TODO: metric-based feature selection.
raise NotImplementedError
def _compute_single_heatmap_fields_info(
heatmap,
pixel_min_threshold,
pixel_max_threshold
):
"""
Given a 2D heatmap of a unit, compute:
num_clusters, num_pixels_in_clusters, max_value_in_clusters, \
mean_value_in_clusters, var_value_in_clusters, heatmap_thresholded
"""
scaler = MinMaxScaler()
# normalize to [0, 1]
heatmap_normalized = scaler.fit_transform(heatmap)
# convert to [0, 255]
heatmap_gray = (heatmap_normalized * 255).astype(np.uint8)
# compute activity threshold as the mean of the heatmap
activity_threshold = np.mean(heatmap_gray)
_, heatmap_thresholded = cv2.threshold(
heatmap_gray, activity_threshold,
255, cv2.THRESH_BINARY
)
# num_labels=4,
# num_labels includes background
# labels \in (17, 17)
# stats \in (4, 5): [left, top, width, height, area] for each label
num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(heatmap_thresholded)
# Create a mask to filter clusters based on pixel thresholds
# e.g. mask=[False, True, False, True] for each label (i.e. a cluster)
mask = (stats[:, cv2.CC_STAT_AREA] >= pixel_min_threshold) & \
(stats[:, cv2.CC_STAT_AREA] <= pixel_max_threshold)
# set background to False regardless of pixel thresholds
mask[0] = False
# Filter the stats and labels based on the mask
# filtered_stats.shape (2, 5)
filtered_stats = stats[mask]
# For labels with mask=True, keep the label, otherwise set to 0
# this in fact will include 0, but we want 1, 3 only
# so when using `filtered_labels` to extract max value in each cluster
# we need to exclude 0
filtered_labels = np.where(np.isin(labels, np.nonzero(mask)[0]), labels, 0)
# Count the number of clusters that meet the criteria
num_clusters = np.array([filtered_stats.shape[0]])
# Get the number of pixels in each cluster
num_pixels_in_clusters = filtered_stats[:, cv2.CC_STAT_AREA]
# Get the max/mean/var value in heatmap based on each cluster
max_value_in_clusters = []
mean_value_in_clusters = []
var_value_in_clusters = []
for label in np.unique(filtered_labels):
if label != 0:
max_value_in_clusters.append(
np.around(
np.max(heatmap[filtered_labels == label]), 1
)
)
mean_value_in_clusters.append(
np.around(
np.mean(heatmap[filtered_labels == label]), 1
)
)
var_value_in_clusters.append(
np.around(
np.var(heatmap[filtered_labels == label]), 1
)
)
# Add 0 to `num_pixels_in_clusters` and `max_value_in_clusters`
# in case `num_clusters` is 0. This is helpful when we want to
# plot fields info against coef, as no matter if there is a cluster
# for a unit, there is always a coef for that unit.
if num_clusters[0] == 0:
num_pixels_in_clusters = np.array([0])
max_value_in_clusters = np.array([0])
mean_value_in_clusters = np.array([0])
var_value_in_clusters = np.array([0])
else:
max_value_in_clusters = np.array(max_value_in_clusters)
mean_value_in_clusters = np.array(mean_value_in_clusters)
var_value_in_clusters = np.array(var_value_in_clusters)
colors = np.arange(100, dtype=int).tolist()
for label in np.unique(filtered_labels):
if label != 0:
# create a mask for each label
mask = np.where(filtered_labels == label, 255, 0).astype(np.uint8)
# find contours
contours, _ = cv2.findContours(
mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
# draw contours
cv2.drawContours(heatmap_thresholded, contours, -1, colors[label-1], 1)
return num_clusters, num_pixels_in_clusters, max_value_in_clusters, \
mean_value_in_clusters, var_value_in_clusters, heatmap_thresholded
def _compute_single_heatmap_grid_scores(activation_map, smooth=False):
# mask parameters
starts = [0.2] * 10
ends = np.linspace(0.4, 1.0, num=10)
masks_parameters = zip(starts, ends.tolist())
scorer = scores.GridScorer(
len(activation_map), # nbins
[0, len(activation_map)-1], # coords_range
masks_parameters # parameters for the masks
)
score_60, score_90, max_60_mask, max_90_mask, sac = \
scorer.get_scores(activation_map)
return score_60, score_90, max_60_mask, max_90_mask, sac, scorer
def _compute_single_heatmap_border_scores(activation_map, db=3):
"""
Banino et al. 2018 uses db=3.
"""
num_bins = activation_map.shape[0]
# Compute c (average activity for bins further than db bins from any wall)
c = np.mean([
activation_map[i, j]
for i in range(db, num_bins - db)
for j in range(db, num_bins - db)
])
wall_scores = []
# Compute the average activation for each wall
for i in range(4):
if i == 0:
# Top wall
activations = activation_map[:db, :]
elif i == 1:
# Right wall
activations = activation_map[:, -db:]
elif i == 2:
# Bottom wall
activations = activation_map[-db:, :]
elif i == 3:
# Left wall
activations = activation_map[:, :db]
bi = np.mean(activations)
wall_scores.append((bi - c) / (bi + c))
return np.max(wall_scores)
def _compute_single_heatmap_directional_scores(activation_maps):
"""
Args:
`activation_maps` correspond to the un-summed activation maps
for a single unit across rotations \in (n_locations, n_rotations)
- num of angular bins in Banino here becomes `n_rotations`.
- based on Banino eq, we need to convert each n_rotations to
`alpha_i` which is angle.
- the intensity `beta_i` of an angle is the average activation
across all locations for that angle.
"""
# model_reps \in (n_locations, n_rotations, n_features)
# activation_maps \in (n_locations, n_rotations)
num_bins = activation_maps.shape[1]
alphas = np.linspace(0, 2*np.pi, num=num_bins, endpoint=False)
betas = np.mean(activation_maps, axis=0)
# given a rotation, we can compute alpha_i and beta_i
# which are used to compute r_i in the eq.
# we collect r_i for each rotation and compute the mean
# vector, whose length is used as the directional score.
polar_plot_coords = []
per_rotation_vector_length = []
for alpha_i, beta_i in zip(alphas, betas):
polar_plot_coords.append(
[beta_i*np.cos(alpha_i), beta_i*np.sin(alpha_i)]
)
per_rotation_vector_length.append(
np.linalg.norm([beta_i*np.cos(alpha_i), beta_i*np.sin(alpha_i)])
)
# to compute mean vector length,
# first we compute the sum of r_i normed by sum of beta_i
r_normed_by_beta = np.sum(
np.array(polar_plot_coords), axis=0) / np.sum(betas)
# then we compute the length of the mean vector
mean_vector_length = np.linalg.norm(r_normed_by_beta)
logging.info(f'[Check] mean_vector_length: {mean_vector_length}')
return mean_vector_length, per_rotation_vector_length
def _single_env_produce_fields_info_ranked_by_coef(
config_version,
experiment,
reference_experiment,
feature_selection,
decoding_model_choice,
sampling_rate,
moving_trajectory,
random_seed,
filterings,
):
"""
Produce fields info for each unit and save to disk, which
will be used for plotting by `_single_env_viz_fields_info`.
"""
os.environ["TF_NUM_INTRAOP_THREADS"] = f"{TF_NUM_INTRAOP_THREADS}"
os.environ["TF_NUM_INTEROP_THREADS"] = "1"
config = utils.load_config(config_version)
reference_experiment_results_path = \
utils.load_results_path(
config=config,
experiment=reference_experiment, # Dirty but coef is saved in loc_n_rot
feature_selection=feature_selection,
decoding_model_choice=decoding_model_choice,
sampling_rate=sampling_rate,
moving_trajectory=moving_trajectory,
random_seed=random_seed,
)
logging.info(
f'Loading results (for coef) from {reference_experiment_results_path}'
)
if reference_experiment_results_path is None:
logging.info(
f'Mismatch between feature '\
f'selection and decoding model, skip.'
)
return
movement_mode=config['movement_mode']
env_x_min=config['env_x_min']
env_x_max=config['env_x_max']
env_y_min=config['env_y_min']
env_y_max=config['env_y_max']
multiplier=config['multiplier']
# load model outputs
model_reps = _single_model_reps(config)
# TODO: feature selection based on rob metric or l1/l2
# notice, one complexity is coef is x, y, rot
# whereas rob metric may not be differentiating (x, y)
# one idea is to separately plot for x, y, rot
if feature_selection in ['l1', 'l2']:
# load regression coefs as selection criteria
# for model_reps (per unit)
targets = ['x', 'y', 'rot']
coef = \
np.load(
f'{reference_experiment_results_path}/res.npy',
allow_pickle=True).item()['coef'] # (n_targets, n_features)
logging.info(f'Loaded coef.shape: {coef.shape}')
# Due to meeting 24-May-2023, we use absolute
# values of coef for filtering.
coef = np.abs(coef)
for target_index in range(coef.shape[0]):
# filter columns of `model_reps`
# based on each coef of each target
# based on `n_units_filtering` and `filtering_order`
for filtering in filterings:
n_units_filtering = filtering['n_units_filtering']
filtering_order = filtering['filtering_order']
if filtering_order == 'top_n':
filtered_n_units_indices = np.argsort(
coef[target_index, :])[::-1][:n_units_filtering]
elif filtering_order == 'mid_n':
filtered_n_units_indices = np.argsort(
coef[target_index, :])[::-1][
int(coef.shape[1]/2)-int(n_units_filtering/2):
int(coef.shape[1]/2)+int(n_units_filtering/2)]
elif filtering_order == 'random_n':
# randomly sample n_units_filtering units
# but excluding the top_n (also n_units_filtering)
np.random.seed(random_seed)
filtered_n_units_indices = np.random.choice(
np.argsort(
coef[target_index, :])[::-1][n_units_filtering:],
n_units_filtering,
replace=False)
else:
raise NotImplementedError
# fields info for each unit is computed on the summed heatmap
# across rotations.
model_reps_summed = np.sum(model_reps, axis=1, keepdims=True)
for unit_rank, unit_index in enumerate(filtered_n_units_indices):
for rotation in range(model_reps_summed.shape[1]):
if movement_mode == '2d':
# reshape to (n_locations, n_rotations, n_features)
heatmap = model_reps_summed[:, rotation, unit_index].reshape(
(env_x_max*multiplier-env_x_min*multiplier+1,
env_y_max*multiplier-env_y_min*multiplier+1)
)
# rotate heatmap to match Unity coordinate system
# ref: tests/testReshape_forHeatMap.py
heatmap = np.rot90(heatmap, k=1, axes=(0, 1))
# compute, collect and save fields info
unit_fields_info = []
num_clusters, num_pixels_in_clusters, max_value_in_clusters, \
mean_value_in_clusters, var_value_in_clusters, \
bounds_heatmap = \
_compute_single_heatmap_fields_info(
heatmap=heatmap,
pixel_min_threshold=10,
pixel_max_threshold=int(heatmap.shape[0]*heatmap.shape[1]*0.5)
)
unit_fields_info.append(num_clusters)
unit_fields_info.append(num_pixels_in_clusters)
unit_fields_info.append(max_value_in_clusters)
unit_fields_info.append(mean_value_in_clusters)
unit_fields_info.append(var_value_in_clusters)
unit_fields_info.append(np.array([np.mean(heatmap)]))
unit_fields_info.append(np.array([np.var(heatmap)]))
# NOTE: we then save this unit's coef per target dimension
# as the last item in the list of fields info.
# by doing this, we can easily access the coef of this saved
# ranked unit without having to load `coef.npy` which is
# quite cumbersome.
# NOTE: in order to plot coef(x-axis) v fields info(y-axis), we need to
# make sure coef is repeated the same number of times as the number of
# clusters.
if num_clusters[0] > 1:
unit_fields_info.append(
np.array(
coef[target_index, unit_index].repeat(num_clusters[0])
)
)
else:
unit_fields_info.append(
np.array(
[coef[target_index, unit_index]])
)
unit_fields_info = np.array(
unit_fields_info, dtype=object
)
# save each unit fields info to disk
results_path = utils.load_results_path(
config=config,
experiment='fields_info',
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,
)
fpath = f'{results_path}/'\
f'{filtering_order}'\
f'_rank{unit_rank}'\
f'_{targets[target_index]}.npy'
logging.info(f'Saving unit fields info to {fpath}')
np.save(fpath, unit_fields_info)
def _single_env_viz_fields_info_ranked_by_coef(
config_version,
experiment,
reference_experiment,
feature_selection,
decoding_model_choice,
sampling_rate,
moving_trajectory,
random_seed,
filterings,
):
"""
Visualize fields info across units using fields info of units
produced by `_single_env_produce_fields_info`.
1. So far we are tracking the following info related to each unit:
tracked_fields_info = [
'num_clusters', 'num_pixels_in_clusters',
'max_value_in_clusters', 'mean_value_in_clusters', 'var_value_in_clusters',
'entire_map_mean', 'entire_map_var'
]
2. The fields info for each unit is stored in a list of lists:
fields_info = [[num_clusters], [num_pixels_in_clusters], [max_value_in_clusters], ...]
3. As we created separate groups of units based on top_n based
on units' corresponding coef (abs due to Meeting 25-May-2023).
We can plot these units using their fields info as representations,
and see if there are patterns associated with
whether these units are from the top_n or other groups (random_n, mid_n, etc.)
We can look at a few things:
1. num_clusters across top_n vs bottom_n
2. num_pixels_in_clusters across top_n vs bottom_n
3. max_value_in_clusters across top_n vs bottom_n
4. ...
4. Also perhaps across layers these fields info differ and can help
us understand the difference in decoding performance.
"""
targets = ['x', 'y', 'rot']
tracked_fields_info = [
'num_clusters', 'num_pixels_in_clusters',
'max_value_in_clusters', 'mean_value_in_clusters', 'var_value_in_clusters',
'entire_map_mean', 'entire_map_var']
n_units_filtering = filterings[0]['n_units_filtering']
filtering_types = [f['filtering_order'] for f in filterings]
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,
)
if results_path is None:
logging.info(
f'Mismatch between feature '\
f'selection and decoding model, skip.'
)
return
for target in targets:
fig, axes = plt.subplots(
nrows=len(tracked_fields_info),
ncols=3,
figsize=(14, 14)
)
for info_index, info in enumerate(tracked_fields_info):
top_n_stats = []
top_n_coef = []
random_n_stats = []
random_n_coef = []
mid_n_stats = []
mid_n_coef = []
for filtering in filtering_types:
for unit_rank in range(n_units_filtering):
fname = f'{results_path}/{filtering}_rank{unit_rank}_{target}.npy'
try:
fields_info = np.load(fname, allow_pickle=True)
except FileNotFoundError:
logging.info(
f'File {fname} not found, must `_single_env_viz_units`'\
f'to save the units fields info first.'
)
exit
if info == 'num_clusters':
stats = fields_info[0]
elif info == 'num_pixels_in_clusters':
stats = fields_info[1]
elif info == 'max_value_in_clusters':
stats = fields_info[2]
elif info == 'mean_value_in_clusters':
stats = fields_info[3]
elif info == 'var_value_in_clusters':
stats = fields_info[4]
elif info == 'entire_map_mean':
stats = fields_info[5]
elif info == 'entire_map_var':
stats = fields_info[6]
if filtering == 'top_n':
top_n_stats.extend(stats)
if info in ['num_clusters',
'entire_map_mean',
'entire_map_var']:
# HACK: due to coef is repeated the same number of times
# as the number of clusters during saving, but when
# info == 'num_clusters', there is only one value for
# one coef, we need to extract the first coef from the list
# of coef (first coef is the same as the rest though)
top_n_coef.append(fields_info[-1][0])
else:
top_n_coef.extend(fields_info[-1])
elif filtering == 'mid_n':
mid_n_stats.extend(stats)
if info in ['num_clusters',
'entire_map_mean',
'entire_map_var']:
mid_n_coef.append(fields_info[-1][0])
else:
mid_n_coef.extend(fields_info[-1])
elif filtering == 'random_n':
random_n_stats.extend(stats)
if info in ['num_clusters',
'entire_map_mean',
'entire_map_var']:
random_n_coef.append(fields_info[-1][0])
else:
random_n_coef.extend(fields_info[-1])
# plot for each info, how units/fields differ
# set x-axis correctly as they differ for different info
# e.g. num_clusters are wrt units, whereas max_value_in_clusters
# are wrt clusters (longer axis due to each unit may have multiple clusters)
if info in ['num_clusters', 'entire_map_mean', 'entire_map_var']:
axes[info_index, 0].set_xlabel('units')
elif info in ['num_pixels_in_clusters', 'max_value_in_clusters',
'mean_value_in_clusters', 'var_value_in_clusters']:
axes[info_index, 0].set_xlabel('fields')
axes[info_index, 0].set_title(info)
axes[info_index, 0].plot(
np.arange(len(top_n_stats)), top_n_stats, label='top_n', alpha=0.5
)
axes[info_index, 0].plot(
np.arange(len(mid_n_stats)), mid_n_stats, label='mid_n', alpha=0.5,
)
axes[info_index, 0].plot(
np.arange(len(random_n_stats)), random_n_stats, label='random_n', alpha=0.5,
c='gray'
)
# kdeplot for each info, how units (distribution) differ
axes[info_index, 1].set_title(info)
sns.kdeplot(
top_n_stats, label='top_n', ax=axes[info_index, 1], alpha=0.5
)
sns.kdeplot(
mid_n_stats, label='mid_n', ax=axes[info_index, 1], alpha=0.5,
)
sns.kdeplot(
random_n_stats, label='random_n', ax=axes[info_index, 1], alpha=0.5,
color='gray'
)
# scatterplot for each info, how unit coef and info correlate
axes[info_index, 2].set_title(info)
axes[info_index, 2].scatter(
top_n_coef, top_n_stats, label='top_n', alpha=0.1
)
axes[info_index, 2].scatter(
mid_n_coef, mid_n_stats, label='mid_n', alpha=0.1,
)
axes[info_index, 2].scatter(
random_n_coef, random_n_stats, label='random_n', alpha=0.3,
c='gray', marker='x'
)
axes[info_index, 2].set_xlabel('coef')
sup_title = f"{target},"\
f"{config['unity_env']},"\
f"{config['model_name']},{feature_selection}"\
f"({decoding_model_choice['hparams']}),"\
f"sr{sampling_rate},seed{random_seed}"
figs_path = utils.load_figs_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,
)
plt.legend()
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
plt.suptitle(sup_title)
plt.savefig(
f'{figs_path}/units_fields_info'\
f'_{target}_groupedByFilteringN.png')
plt.close()
logging.info(
f'[Saved] {figs_path}/units_fields_info'\
f'_{target}_groupedByFilteringN.png')
def _single_env_produce_unit_chart(
config_version,
experiment,
moving_trajectory,
reference_experiment=None,
feature_selection=None,
decoding_model_choice=None,
sampling_rate=None,
random_seed=None,
filterings=None,
# charting all units, use Nones to maintain API consistency
):
"""
Produce unit chart for each unit and save to disk, which
will be used for plotting by `_single_env_viz_unit_chart`.
Unit chart is intended to capture characteristics of each
unit (no filtering; ALL units). Currently, the chart includes:
0. if dead (if true, continue to next unit)
. fields info - [
1. num_clusters,
2. num_pixels_in_clusters,
3. max_value_in_clusters,
4. mean_value_in_clusters,
5. var_value_in_clusters,
6. entire_map_mean,
7. entire_map_var,
]
8. gridness - gridness score
9. borderness - border score
. directioness - [
10. mean_vector_length,
11. per_rotation_vector_length,
]
"""
os.environ["TF_NUM_INTRAOP_THREADS"] = f"{TF_NUM_INTRAOP_THREADS}"
os.environ["TF_NUM_INTEROP_THREADS"] = "1"
config = utils.load_config(config_version)
movement_mode=config['movement_mode']
env_x_min=config['env_x_min']
env_x_max=config['env_x_max']
env_y_min=config['env_y_min']
env_y_max=config['env_y_max']
multiplier=config['multiplier']
# load model outputs
model_reps = _single_model_reps(config)
# charted info:
charted_info = [
'dead',
# --- fields info
'num_clusters',
'num_pixels_in_clusters',
'max_value_in_clusters',
'mean_value_in_clusters',
'var_value_in_clusters',
'entire_map_mean',
'entire_map_var',
# ---
'gridness',
# ---
'borderness',