-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
1481 lines (1350 loc) · 78.1 KB
/
utils.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
#!/usr/bin/env python
import argparse
import os
import sys
import traceback
import time
import warnings
import pickle
from collections import OrderedDict
import yaml
import numpy as np
# torch
import torch
import cv2
import torch.nn as nn
import torch.optim as optim
#videovis:
#import matplotlib
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
#import matplotlib.image as mpimg
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
import array
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.decomposition import KernelPCA
from sklearn.manifold import TSNE
from sklearn.manifold import Isomap
import sklearn.cluster as cluster
from umap import UMAP
from PIL import Image
import scipy.stats as stats
import seaborn as sns
from data_processing import *
dp = data_processing()
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=FutureWarning)
import h5py
class IO():
def __init__(self, work_dir, save_log=True, print_log=True):
self.work_dir = work_dir
self.save_log = save_log
self.print_to_screen = print_log
self.cur_time = time.time()
self.split_timer = {}
self.pavi_logger = None
self.session_file = None
self.model_text = ''
# PaviLogger is removed in this version
def log(self, *args, **kwargs):
pass
# try:00
# if self.pavi_logger is None:
# from torchpack.runner.hooks import PaviLogger
# url = 'http://pavi.parrotsdnn.org/log'
# with open(self.session_file, 'r') as f:
# info = dict(
# session_file=self.session_file,
# session_text=f.read(),
# model_text=self.model_text)
# self.pavi_logger = PaviLogger(url)
# self.pavi_logger.connect(self.work_dir, info=info)
# self.pavi_logger.log(*args, **kwargs)
# except: #pylint: disable=W0702
# pass
def pca(self, nc):
pca = PCA(n_components=nc)
return pca
def kpca(self, nc, kernel='linear'):
kpca = KernelPCA(n_components=nc, kernel=kernel)
return kpca
def tsne(self, nc):
tsne_ = TSNE(n_components=nc, random_state=0)
return tsne_
def isomap(self, nc):
iso = Isomap(n_components=nc)
return iso
def umap(self, nc, n_neighbors=40, metric='cosine', min_dist=0.001, local_connectivity=0):
umap_ = UMAP(n_neighbors=n_neighbors , n_components=nc, metric=metric, min_dist=min_dist, local_connectivity=local_connectivity)
return umap_
def pca_states(self, states, nc=5):
"""
states of one layer of the neural network
timesteps, batchsize, layer, [h,c] (we want only h) , D (dim)
"""
len_ = len(states[0])
pca_ = self.pca(nc)
new_states = []
for l in range(len(states[0])):
for t in range(len(states)):
new_states.append(states[t][l][0].detach().cpu().numpy())
new_states = np.array(new_states)
states_pca = []
for l in range(len(new_states[0])):
pcas = pca_.fit_transform(new_states[:, l, :])
states_pca.append(pcas)
return new_states, states_pca
def cluster_latent(self, n):
return cluster.KMeans(n_clusters=n)
def correlation_matrix(self, data):
corr_matrix = np.corrcoef(data).round(decimals=2)
return corr_matrix
def dm_red(self,data, method='kpca', params={}):
"""
apply specified dimensionlity reduction to data
"""
reduced_data=[]
return reduced_data
def normalize(self, vec):
l = len(vec)
max = np.max(vec)
min = np.min(vec)
normalized_vec = [(vec[i]-min)/(max-min) for i in range(l)]
return normalized_vec
def sents(self):
nouns = ['red', 'green', 'blue', 'purple', 'yellow']
verbs = ['grasp . . .', 'move left . .', 'move right . .', 'move front . .', 'move back . .', 'put on green .',
'put on blue .', 'put on yellow .']
v_ = []
sentences = []
sentences_vecs = []
for v in range(len(verbs)):
v_.append(verbs[v].split(" "))
for n in range(len(nouns)):
for i in range(len(v_)):
s = [v_[i][0], nouns[n], v_[i][1], v_[i][2], v_[i][3]]
sent = " ".join(s)
sentences.append(sent)
sent_vec, _ = dp.lang_vec(sent, max_len=5)
sentences_vecs.append(np.array(sent_vec))
return sentences, sentences_vecs
def latent_state_plot(self, lang_latent_state, lang_labels, **params):
"""
langauge latent state and language labels should be an ordered pair
"""
#generate corpus
nouns = ['red', 'green', 'blue', 'purple', 'yellow']
verbs = ['grasp . . .', 'move left . .', 'move right . .', 'move front . .', 'move back . .', 'put on green .',
'put on blue .', 'put on yellow .']
sentences, sentences_vecs = self.sents()
#compute the kpca of latent states
kpca_2d = self.kpca(nc=2, kernel="linear")
lang_states = torch.from_numpy(lang_latent_state)
lkpca2d = kpca_2d.fit_transform(lang_latent_state) #
kpca2d_1 = [lkpca2d[i][0] for i in range(len(lkpca2d))]
kpca2d_2 = [lkpca2d[i][1] for i in range(len(lkpca2d))]
# put them in a list
lang_states_kpca2d = [[kpca2d_1[i], kpca2d_2[i]] for i in range(len(kpca2d_1))]
def get_mean_latent(self, latent_pca_1, latent_pca_2, latent_state_labels):
grasp_red, grasp_green, grasp_blue, grasp_purple, grasp_yellow = [], [], [], [], []
red_left, green_left, blue_left, purple_left, yellow_left = [], [], [], [], []
red_right, green_right, blue_right, purple_right, yellow_right = [], [], [], [], []
red_front, green_front, blue_front, purple_front, yellow_front = [], [], [], [], []
red_back, green_back, blue_back, purple_back, yellow_back = [], [], [], [], []
redongreen, greenongreen, blueongreen, purpleongreen, yellowongreen = [], [], [], [], []
redonblue, greenonblue, blueonblue, purpleonblue, yellowonblue = [], [], [], [], []
redonyellow, greenonyellow, blueonyellow, purpleonyellow, yellowonyellow = [], [], [], [], []
latent_state_labels = latent_state_labels.numpy()
red_v = dp.lang_vec("red", max_len=1)
green_v = dp.lang_vec("green", max_len=1)
blue_v = dp.lang_vec("blue", max_len=1)
purple_v = dp.lang_vec("purple", max_len=1)
yellow_v = dp.lang_vec("yellow", max_len=1)
left_v = dp.lang_vec("left", max_len=1)
right_v = dp.lang_vec("right", max_len=1)
front_v = dp.lang_vec("front", max_len=1)
back_v = dp.lang_vec("back", max_len=1)
grasp_v = dp.lang_vec("grasp", max_len=1)
put_v = dp.lang_vec("put", max_len=1)
for i in range(len(latent_state_labels)):
if np.argmax(latent_state_labels[i][0]) == np.argmax(grasp_v[0]):
if np.argmax(latent_state_labels[i][1]) == np.argmax(red_v[0]):
grasp_red.append([latent_pca_1[i], latent_pca_2[i]])
if np.argmax(latent_state_labels[i][1]) == np.argmax(green_v[0]):
grasp_green.append([latent_pca_1[i], latent_pca_2[i]])
if np.argmax(latent_state_labels[i][1]) == np.argmax(blue_v[0]):
grasp_blue.append([latent_pca_1[i], latent_pca_2[i]])
if np.argmax(latent_state_labels[i][1]) == np.argmax(purple_v[0]):
grasp_purple.append([latent_pca_1[i], latent_pca_2[i]])
if np.argmax(latent_state_labels[i][1]) == np.argmax(yellow_v[0]):
grasp_yellow.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][2]) == np.argmax(left_v[0]):
if np.argmax(latent_state_labels[i][1]) == np.argmax(red_v[0]):
red_left.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(green_v[0]):
green_left.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(blue_v[0]):
blue_left.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(purple_v[0]):
purple_left.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(yellow_v[0]):
yellow_left.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][2]) == np.argmax(right_v[0]):
if np.argmax(latent_state_labels[i][1]) == np.argmax(red_v[0]):
red_right.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(green_v[0]):
green_right.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(blue_v[0]):
blue_right.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(purple_v[0]):
purple_right.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(yellow_v[0]):
yellow_right.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][2]) == np.argmax(front_v[0]):
if np.argmax(latent_state_labels[i][1]) == np.argmax(red_v[0]):
red_front.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(green_v[0]):
green_front.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(blue_v[0]):
blue_front.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(purple_v[0]):
purple_front.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(yellow_v[0]):
yellow_front.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][2]) == np.argmax(back_v[0]):
if np.argmax(latent_state_labels[i][1]) == np.argmax(red_v[0]):
red_back.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(green_v[0]):
green_back.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(blue_v[0]):
blue_back.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(purple_v[0]):
purple_back.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(yellow_v[0]):
yellow_back.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][0]) == np.argmax(put_v[0]) and np.argmax(latent_state_labels[i][3]) == np.argmax(green_v[0]):
if np.argmax(latent_state_labels[i][1]) == np.argmax(red_v[0]):
redongreen.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(green_v[0]):
greenongreen.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(blue_v[0]):
blueongreen.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(purple_v[0]):
purpleongreen.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(yellow_v[0]):
yellowongreen.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][0]) == np.argmax(put_v[0]) and np.argmax(latent_state_labels[i][3]) == np.argmax(blue_v[0]):
if np.argmax(latent_state_labels[i][1]) == np.argmax(red_v[0]):
redonblue.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(green_v[0]):
greenonblue.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(blue_v[0]):
blueonblue.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(purple_v[0]):
purpleonblue.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(yellow_v[0]):
yellowonblue.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][0]) == np.argmax(put_v[0]) and np.argmax(latent_state_labels[i][3]) == np.argmax(yellow_v[0]):
if np.argmax(latent_state_labels[i][1]) == np.argmax(red_v[0]):
redonyellow.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(green_v[0]):
greenonyellow.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(blue_v[0]):
blueonyellow.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(purple_v[0]):
purpleonyellow.append([latent_pca_1[i], latent_pca_2[i]])
elif np.argmax(latent_state_labels[i][1]) == np.argmax(yellow_v[0]):
yellowonyellow.append([latent_pca_1[i], latent_pca_2[i]])
# print(np.mean(np.array(grasp_red)[:, 0]))
# print(np.array(grasp_red)[:, 1].shape)
# print(np.mean(np.array(grasp_blue)[:, 0]))
# exit()
labels_red, labeld_green, labels_blue, labels_purple, labels_yellow= [], [], [], [], []
grasp_red_mean, grasp_green_mean, grasp_blue_mean, grasp_purple_mean, grasp_yellow_mean = [0,0], [0,0], [0,0], [0,0], [0,0]
red_left_mean, green_left_mean, blue_left_mean, purple_left_mean, yellow_left_mean = [0,0], [0,0], [0,0], [0,0], [0,0]
red_right_mean, green_right_mean, blue_right_mean, purple_right_mean, yellow_right_mean = [0,0], [0,0], [0,0], [0,0], [0,0]
red_front_mean, green_front_mean, blue_front_mean, purple_front_mean, yellow_front_mean = [0,0], [0,0], [0,0], [0,0], [0,0]
red_back_mean, green_back_mean, blue_back_mean, purple_back_mean, yellow_back_mean = [0,0], [0,0], [0,0], [0,0], [0,0]
redongreen_mean, greenongreen_mean, blueongreen_mean, purpleongreen_mean, yellowongreen_mean = [0,0], [0,0], [0,0], [0,0], [0,0]
redonblue_mean, greenonblue_mean, blueonblue_mean, purpleonblue_mean, yellowonblue_mean = [0,0], [0,0], [0,0], [0,0], [0,0]
redonyellow_mean, greenonyellow_mean, blueonyellow_mean, purpleonyellow_mean, yellowonyellow_mean = [0,0], [0,0], [0,0], [0,0], [0,0]
if len(grasp_purple) != 0:
grasp_red_mean, grasp_green_mean, grasp_blue_mean, grasp_purple_mean, grasp_yellow_mean =\
[np.mean(np.array(grasp_red)[:, 0]), np.mean(np.array(grasp_red)[:, 1])], [np.mean(np.array(grasp_green)[:, 0]), np.mean(np.array(grasp_green)[:, 1])],\
[np.mean(np.array(grasp_blue)[:, 0]), np.mean(np.array(grasp_blue)[:, 1])], [np.mean(np.array(grasp_purple)[:, 0]), np.mean(np.array(grasp_purple)[:, 1])], \
[np.mean(np.array(grasp_yellow)[:, 0]), np.mean(np.array(grasp_yellow)[:, 1])]
else:
grasp_red_mean, grasp_green_mean, grasp_blue_mean, grasp_purple_mean, grasp_yellow_mean =\
[np.mean(np.array(grasp_red)[:, 0]), np.mean(np.array(grasp_red)[:, 1])], [np.mean(np.array(grasp_green)[:, 0]), np.mean(np.array(grasp_green)[:, 1])],\
[np.mean(np.array(grasp_blue)[:, 0]), np.mean(np.array(grasp_blue)[:, 1])], [0, 0], [0, 0]
if len(purple_left) != 0:
red_left_mean, green_left_mean, blue_left_mean, purple_left_mean, yellow_left_mean =\
[np.mean(np.array(red_left)[:, 0]), np.mean(np.array(red_left)[:, 1])], [
np.mean(np.array(green_left)[:, 0]), np.mean(np.array(green_left)[:, 1])], \
[np.mean(np.array(blue_left)[:, 0]), np.mean(np.array(blue_left)[:, 1])], [
np.mean(np.array(purple_left)[:, 0]), np.mean(np.array(purple_left)[:, 1])], \
[np.mean(np.array(yellow_left)[:, 0]), np.mean(np.array(yellow_left)[:, 1])]
elif len(red_left) !=0:
red_left_mean, green_left_mean, blue_left_mean, purple_left_mean, yellow_left_mean =\
[np.mean(np.array(red_left)[:, 0]), np.mean(np.array(red_left)[:, 1])], [
np.mean(np.array(green_left)[:, 0]), np.mean(np.array(green_left)[:, 1])], \
[np.mean(np.array(blue_left)[:, 0]), np.mean(np.array(blue_left)[:, 1])], [0,0], [0,0]
if len(purple_right) != 0:
red_right_mean, green_right_mean, blue_right_mean, purple_right_mean, yellow_right_mean = \
[np.mean(np.array(red_right)[:, 0]), np.mean(np.array(red_right)[:, 1])], [
np.mean(np.array(green_right)[:, 0]), np.mean(np.array(green_right)[:, 1])], \
[np.mean(np.array(blue_right)[:, 0]), np.mean(np.array(blue_right)[:, 1])], [
np.mean(np.array(purple_right)[:, 0]), np.mean(np.array(purple_right)[:, 1])], \
[np.mean(np.array(yellow_right)[:, 0]), np.mean(np.array(yellow_right)[:, 1])]
elif len(red_right) != 0:
red_right_mean, green_right_mean, blue_right_mean, purple_right_mean, yellow_right_mean = \
[np.mean(np.array(red_right)[:, 0]), np.mean(np.array(red_right)[:, 1])], [
np.mean(np.array(green_right)[:, 0]), np.mean(np.array(green_right)[:, 1])], \
[np.mean(np.array(blue_right)[:, 0]), np.mean(np.array(blue_right)[:, 1])], [0,0], [0,0]
if len(purple_front) != 0:
red_front_mean, green_front_mean, blue_front_mean, purple_front_mean, yellow_front_mean = \
[np.mean(np.array(red_front)[:, 0]), np.mean(np.array(red_front)[:, 1])], [
np.mean(np.array(green_front)[:, 0]), np.mean(np.array(green_front)[:, 1])], \
[np.mean(np.array(blue_front)[:, 0]), np.mean(np.array(blue_front)[:, 1])], [
np.mean(np.array(purple_front)[:, 0]), np.mean(np.array(purple_front)[:, 1])], \
[np.mean(np.array(yellow_front)[:, 0]), np.mean(np.array(yellow_front)[:, 1])]
elif len(red_front) !=0:
red_front_mean, green_front_mean, blue_front_mean, purple_front_mean, yellow_front_mean = \
[np.mean(np.array(red_front)[:, 0]), np.mean(np.array(red_front)[:, 1])], [
np.mean(np.array(green_front)[:, 0]), np.mean(np.array(green_front)[:, 1])], \
[np.mean(np.array(blue_front)[:, 0]), np.mean(np.array(blue_front)[:, 1])], [0,0], [0,0]
if len(purple_back) != 0:
red_back_mean, green_back_mean, blue_back_mean, purple_back_mean, yellow_back_mean = \
[np.mean(np.array(red_back)[:, 0]), np.mean(np.array(red_back)[:, 1])], [
np.mean(np.array(green_back)[:, 0]), np.mean(np.array(green_back)[:, 1])], \
[np.mean(np.array(blue_back)[:, 0]), np.mean(np.array(blue_back)[:, 1])], [
np.mean(np.array(purple_back)[:, 0]), np.mean(np.array(purple_back)[:, 1])], \
[np.mean(np.array(yellow_back)[:, 0]), np.mean(np.array(yellow_back)[:, 1])]
elif len(red_back) != 0:
red_back_mean, green_back_mean, blue_back_mean, purple_back_mean, yellow_back_mean = \
[np.mean(np.array(red_back)[:, 0]), np.mean(np.array(red_back)[:, 1])], [
np.mean(np.array(green_back)[:, 0]), np.mean(np.array(green_back)[:, 1])], \
[np.mean(np.array(blue_back)[:, 0]), np.mean(np.array(blue_back)[:, 1])], [0,0],[0,0]
if len(purpleongreen) != 0:
redongreen_mean, greenongreen_mean, blueongreen_mean, purpleongreen_mean, yellowongreen_mean = \
[np.mean(np.array(redongreen)[:, 0]), np.mean(np.array(redongreen)[:, 1])], [
np.mean(np.array(greenongreen)[:, 0]), np.mean(np.array(greenongreen)[:, 1])], \
[np.mean(np.array(blueongreen)[:, 0]), np.mean(np.array(blueongreen)[:, 1])], [
np.mean(np.array(purpleongreen)[:, 0]), np.mean(np.array(purpleongreen)[:, 1])], \
[np.mean(np.array(yellowongreen)[:, 0]), np.mean(np.array(yellowongreen)[:, 1])]
elif len(redongreen) != 0:
redongreen_mean, greenongreen_mean, blueongreen_mean, purpleongreen_mean, yellowongreen_mean = \
[np.mean(np.array(redongreen)[:, 0]), np.mean(np.array(redongreen)[:, 1])], [
np.mean(np.array(greenongreen)[:, 0]), np.mean(np.array(greenongreen)[:, 1])], \
[np.mean(np.array(blueongreen)[:, 0]), np.mean(np.array(blueongreen)[:, 1])], [0,0], [0,0]
if len(purpleonblue) != 0:
redonblue_mean, greenonblue_mean, blueonblue_mean, purpleonblue_mean, yellowonblue_mean = \
[np.mean(np.array(redonblue)[:, 0]), np.mean(np.array(redonblue)[:, 1])], [
np.mean(np.array(greenonblue)[:, 0]), np.mean(np.array(greenonblue)[:, 1])], \
[np.mean(np.array(blueonblue)[:, 0]), np.mean(np.array(blueonblue)[:, 1])], [
np.mean(np.array(purpleonblue)[:, 0]), np.mean(np.array(purpleonblue)[:, 1])], \
[np.mean(np.array(yellowonblue)[:, 0]), np.mean(np.array(yellowonblue)[:, 1])]
elif len(redonblue) != 0:
redonblue_mean, greenonblue_mean, blueonblue_mean, purpleonblue_mean, yellowonblue_mean = \
[np.mean(np.array(redonblue)[:, 0]), np.mean(np.array(redonblue)[:, 1])], [
np.mean(np.array(greenonblue)[:, 0]), np.mean(np.array(greenonblue)[:, 1])], \
[np.mean(np.array(blueonblue)[:, 0]), np.mean(np.array(blueonblue)[:, 1])], [0,0], [0,0]
if len(purpleonyellow) != 0:
redonyellow_mean, greenonyellow_mean, blueonyellow_mean, purpleonyellow_mean, yellowonyellow_mean = \
[np.mean(np.array(redonyellow)[:, 0]), np.mean(np.array(redonyellow)[:, 1])], [
np.mean(np.array(greenonyellow)[:, 0]), np.mean(np.array(greenonyellow)[:, 1])], \
[np.mean(np.array(blueonyellow)[:, 0]), np.mean(np.array(blueonyellow)[:, 1])], [
np.mean(np.array(purpleonyellow)[:, 0]), np.mean(np.array(purpleonyellow)[:, 1])], \
[np.mean(np.array(yellowonyellow)[:, 0]), np.mean(np.array(yellowonyellow)[:, 1])]
elif len(redonyellow) != 0:
redonyellow_mean, greenonyellow_mean, blueonyellow_mean, purpleonyellow_mean, yellowonyellow_mean = \
[np.mean(np.array(redonyellow)[:, 0]), np.mean(np.array(redonyellow)[:, 1])], [
np.mean(np.array(greenonyellow)[:, 0]), np.mean(np.array(greenonyellow)[:, 1])], \
[np.mean(np.array(blueonyellow)[:, 0]), np.mean(np.array(blueonyellow)[:, 1])], [0,0], [0,0]
red = [grasp_red_mean, red_left_mean, red_right_mean, red_front_mean, red_back_mean, redongreen_mean, redonblue_mean, redonyellow_mean]
green = [grasp_green_mean, green_left_mean, green_right_mean, green_front_mean, green_back_mean, greenongreen_mean,
greenonblue_mean, greenonyellow_mean]
blue = [grasp_blue_mean, blue_left_mean, blue_right_mean, blue_front_mean, blue_back_mean,
blueongreen_mean, blueonblue_mean, blueonyellow_mean]
purple = [grasp_purple_mean, purple_left_mean, purple_right_mean, purple_front_mean, purple_back_mean,
purpleongreen_mean, purpleonblue_mean, purpleonyellow_mean]
yellow = [grasp_yellow_mean, yellow_left_mean, yellow_right_mean, yellow_front_mean, yellow_back_mean,
yellowongreen_mean, yellowonblue_mean, yellowonyellow_mean]
return red, green, blue, purple, yellow
def plot_lang_latent(self, alph = 0.3, dir=None, lang_states=None, labels=None,pca_type="kpca", kernel='linear', colors=['red', 'green', 'blue', 'purple', 'yellow'], fn='lang_latent'):
"""
colors = red, green, blue, purple, yellow
labels and language states should be ordered appropriately
"""
s, s_vecs = self.sents()
labels_idx = []
for i in range(len(labels)):
for s in range(len(s_vecs)):
if np.array_equal(labels[i], s_vecs[s]): #.numpy()
labels_idx.append(s)
if pca_type == "kpca":
kpca_2d = self.kpca(nc=2, kernel=kernel)
elif pca_type == "pca":
kpca_2d = self.pca(nc=2)
lang_states = torch.from_numpy(lang_states)
labels = torch.from_numpy(labels)
lang_states_kpca2 = kpca_2d.fit_transform(lang_states[:].numpy())#
if pca_type == 'kpca':
var_values = kpca_2d.eigenvalues_ / sum(kpca_2d.eigenvalues_)
print("variance explained ={}".format(var_values))
kpca2d_1 = [lang_states_kpca2[i][0] for i in range(len(lang_states_kpca2))]
kpca2d_2 = [lang_states_kpca2[i][1] for i in range(len(lang_states_kpca2))]
normalized_kpca2d_1 = kpca2d_1 #self.normalize(pca2d_1)
normalized_kpca2d_2 = kpca2d_2 # self.normalize(pca2d_2)
lang_states_kpca2d = [[normalized_kpca2d_1[i], normalized_kpca2d_2[i]] for i in range(len(kpca2d_1))]
clus = self.cluster_latent(n=40)
# clustered_pca = clus.fit_transform(lang_states_pca2)
# lang_states_pca2d=clustered_pca
lang_states_red, lang_states_green, lang_states_blue, lang_states_yellow, lang_states_purple = [], [], [], [], []
lang_states_red2, lang_states_green2, lang_states_blue2, lang_states_yellow2, lang_states_purple2 = [], [], [], [], []
labels_red, labels_green, labels_blue, labels_purple, labels_yellow = [], [], [], [], []
(lang_states_moveleft, lang_states_moveright, lang_states_movefront, lang_states_moveback,
lang_states_grasp, lang_states_putongreen, lang_states_putonblue, lang_states_putonyellow) = [],[],[],[],[],[],[],[]
(lang_states_moveleft2, lang_states_moveright2, lang_states_movefront2, lang_states_moveback2,
lang_states_grasp2, lang_states_putongreen2, lang_states_putonblue2,
lang_states_putonyellow2) = [], [], [], [], [], [], [], []
(labels_left, labels_right, labels_front, labels_back,
labels_grasp, labels_putongreen, labels_putonblue, labels_putonyellow) = [], [], [], [], [], [], [], []
red_v = dp.lang_vec("red", max_len=1)
green_v = dp.lang_vec("green", max_len=1)
blue_v = dp.lang_vec("blue", max_len=1)
purple_v = dp.lang_vec("purple", max_len=1)
yellow_v = dp.lang_vec("yellow", max_len=1)
left_v = dp.lang_vec("left", max_len=1)
right_v = dp.lang_vec("right", max_len=1)
front_v = dp.lang_vec("front", max_len=1)
back_v = dp.lang_vec("back", max_len=1)
grasp_v = dp.lang_vec("grasp", max_len=1)
put_v = dp.lang_vec("put", max_len=1)
for i in range(len(lang_states)):
if np.argmax(labels[i][0]) == np.argmax(grasp_v[0]):
lang_states_grasp.append(lang_states_kpca2d[i][0])
lang_states_grasp2.append(lang_states_kpca2d[i][1])
labels_grasp.append(labels[i])
elif np.argmax(labels[i][2]) == np.argmax(left_v[0]):
lang_states_moveleft.append(lang_states_kpca2d[i][0])
lang_states_moveleft2.append(lang_states_kpca2d[i][1])
labels_left.append(labels[i])
elif np.argmax(labels[i][2]) == np.argmax(right_v[0]):
lang_states_moveright.append(lang_states_kpca2d[i][0])
lang_states_moveright2.append(lang_states_kpca2d[i][1])
labels_right.append(labels[i])
elif np.argmax(labels[i][2]) == np.argmax(front_v[0]):
lang_states_movefront.append(lang_states_kpca2d[i][0])
lang_states_movefront2.append(lang_states_kpca2d[i][1])
labels_front.append(labels[i])
elif np.argmax(labels[i][2]) == np.argmax(back_v[0]):
lang_states_moveback.append(lang_states_kpca2d[i][0])
lang_states_moveback2.append(lang_states_kpca2d[i][1])
labels_back.append(labels[i])
elif np.argmax(labels[i][0]) == np.argmax(put_v[0]) and np.argmax(labels[i][3]) == np.argmax(green_v[0]):
lang_states_putongreen.append(lang_states_kpca2d[i][0])
lang_states_putongreen2.append(lang_states_kpca2d[i][1])
labels_putongreen.append(labels[i])
elif np.argmax(labels[i][0]) == np.argmax(put_v[0]) and np.argmax(labels[i][3]) == np.argmax(blue_v[0]):
lang_states_putonblue.append(lang_states_kpca2d[i][0])
lang_states_putonblue2.append(lang_states_kpca2d[i][1])
labels_putonblue.append(labels[i])
elif np.argmax(labels[i][0]) == np.argmax(put_v[0]) and np.argmax(labels[i][3]) == np.argmax(yellow_v[0]):
lang_states_putonyellow.append(lang_states_kpca2d[i][0])
lang_states_putonyellow2.append(lang_states_kpca2d[i][1])
labels_putonyellow.append(labels[i])
if len(lang_states_putonyellow) != 0 and len(lang_states_putonblue) != 0: #5x8
figa2d = plt.figure(figsize=(9,9))
axgr = figa2d.add_subplot(331)
axle = figa2d.add_subplot(332)
axri = figa2d.add_subplot(333)
axfr = figa2d.add_subplot(334)
axba = figa2d.add_subplot(335)
axpg = figa2d.add_subplot(336)
axpb = figa2d.add_subplot(337)
axpy = figa2d.add_subplot(338)
elif len(lang_states_moveback) != 0 and len(lang_states_movefront) != 0:
figa2d = plt.figure(figsize=(9,6))
axgr = figa2d.add_subplot(231)
axle = figa2d.add_subplot(232)
axri = figa2d.add_subplot(233)
axfr = figa2d.add_subplot(234)
axba = figa2d.add_subplot(235)
axpg = figa2d.add_subplot(236)
else:
figa2d = plt.figure(figsize=(9, 3))
axgr = figa2d.add_subplot(131)
axle = figa2d.add_subplot(132)
axpg = figa2d.add_subplot(133)
# print("len pg = {}".format(len(lang_states_putongreen)))
col_gr, markers_gr = self.gen_markers(labels_grasp, colors)
col_le, markers_le = self.gen_markers(labels_left, colors)
col_pg, markers_pg = self.gen_markers(labels_putongreen, colors)
if len(lang_states_moveback) != 0 and len(lang_states_movefront) != 0:
col_ri, markers_ri = self.gen_markers(labels_right, colors)
col_fr, markers_fr = self.gen_markers(labels_front, colors)
col_ba, markers_ba = self.gen_markers(labels_back, colors)
if len(lang_states_putonyellow) != 0 and len(lang_states_putonblue) != 0:
col_pb, markers_pb = self.gen_markers(labels_putonblue,colors)
col_py, markers_py = self.gen_markers(labels_putonyellow, colors)
for i in range(len(lang_states_grasp)):
axgr.scatter(lang_states_grasp[i], lang_states_grasp2[i], c=col_gr[i],
label=self.gen_lang(labels_grasp[i]), marker=markers_gr[i], alpha=alph)
axgr.set_title('grasp')
# axgr.set_xlim(0, 1)
# axgr.set_ylim(0, 1)
axle.scatter(lang_states_moveleft[i], lang_states_moveleft2[i], c=col_le[i],
label=self.gen_lang(labels_left[i]), marker=markers_le[i], alpha=alph)
axle.set_title('move left')
# axle.set_xlim(0, 1)
# axle.set_ylim(0, 1)
axpg.scatter(lang_states_putongreen[i], lang_states_putongreen2[i], c=col_pg[i],
label=self.gen_lang(labels_putongreen[i]), marker=markers_pg[i], alpha=alph)
axpg.set_title('put on green')
# axpg.set_xlim(0, 1)
# axpg.set_ylim(0, 1)
if len(lang_states_moveback) != 0 and len(lang_states_movefront) != 0:
axri.scatter(lang_states_moveright[i], lang_states_moveright2[i], c=col_ri[i],
label=self.gen_lang(labels_right[i]), marker=markers_ri[i], alpha=alph)
axri.set_title('move right')
# axri.set_xlim(0, 1)
# axri.set_ylim(0, 1)
axfr.scatter(lang_states_movefront[i], lang_states_movefront2[i], c=col_fr[i],
label=self.gen_lang(labels_front[i]), marker=markers_fr[i], alpha=alph)
axfr.set_title('move front')
# axfr.set_xlim(0, 1)
# axfr.set_ylim(0, 1)
axba.scatter(lang_states_moveback[i], lang_states_moveback2[i], c=col_ba[i],
label=self.gen_lang(labels_back[i]), marker=markers_ba[i], alpha=alph)
axba.set_title('move back')
# axba.set_xlim(0, 1)
# axba.set_ylim(0, 1)
if len(lang_states_putonyellow) != 0 and len(lang_states_putonblue) != 0:
axpb.scatter(lang_states_putonblue[i], lang_states_putonblue2[i], c=col_pb[i],
label=self.gen_lang(labels_putonblue[i]), marker=markers_pb[i], alpha=alph)
axpb.set_title('put on blue')
# axpb.set_xlim(0, 1)
# axpb.set_ylim(0, 1)
axpy.scatter(lang_states_putonyellow[i], lang_states_putonyellow2[i], c=col_py[i],
label=self.gen_lang(labels_putonyellow[i]), marker=markers_py[i], alpha=alph)
axpy.set_title('put on yellow')
# axpy.set_xlim(0, 1)
# axpy.set_ylim(0, 1)
mean_pca = [np.mean(lang_states_grasp), np.mean(lang_states_moveleft),
np.mean(lang_states_moveright), np.mean(lang_states_movefront),
np.mean(lang_states_moveback), np.mean(lang_states_putongreen),
np.mean(lang_states_putonblue), np.mean(lang_states_putonyellow),]
std_pca = [np.std(lang_states_grasp), np.std(lang_states_moveleft),
np.std(lang_states_moveright), np.std(lang_states_movefront),
np.std(lang_states_moveback), np.std(lang_states_putongreen),
np.std(lang_states_putonblue),np.std(lang_states_putonyellow)]
mean_pca2 = [np.mean(lang_states_grasp2), np.mean(lang_states_moveleft2),
np.mean(lang_states_moveright2), np.mean(lang_states_movefront2),
np.mean(lang_states_moveback2), np.mean(lang_states_putongreen2),
np.mean(lang_states_putonblue2), np.mean(lang_states_putonyellow2),]
std_pca2 = [np.std(lang_states_grasp2), np.std(lang_states_moveleft2),
np.std(lang_states_moveright2), np.std(lang_states_movefront2),
np.std(lang_states_moveback2), np.std(lang_states_putongreen2),
np.std(lang_states_putonblue2),np.std(lang_states_putonyellow2)]
# print(len(lang_states_grasp), len(lang_states_grasp2))
print("mean={}, std={}".format(mean_pca, std_pca))
print("mean2={}, std2={}".format(mean_pca2, std_pca2))
figa2d.tight_layout()
# fig_l.subplots_adjust(right=0.05)
# self.legend_without_duplicate_labels(axy, loc='lower center', fontsize=5, n_col=2, bbox_to_anchor=(1.5, 0.5))
# plt.show()
plt.savefig("{}/{}.png".format(dir, fn+"pca2d_verbs_kclus"), bbox_inches='tight')
plt.close()
for i in range(len(lang_states)):
if np.argmax(labels[i][1]) == np.argmax(red_v[0]):
lang_states_red.append(lang_states_kpca2d[i][0])
lang_states_red2.append(lang_states_kpca2d[i][1])
labels_red.append(labels[i])
elif np.argmax(labels[i][1]) == np.argmax(green_v[0]):
lang_states_green.append(lang_states_kpca2d[i][0])
lang_states_green2.append(lang_states_kpca2d[i][1])
labels_green.append(labels[i])
elif np.argmax(labels[i][1]) == np.argmax(blue_v[0]):
lang_states_blue.append(lang_states_kpca2d[i][0])
lang_states_blue2.append(lang_states_kpca2d[i][1])
labels_blue.append(labels[i])
elif np.argmax(labels[i][1]) == np.argmax(purple_v[0]):
lang_states_purple.append(lang_states_kpca2d[i][0])
lang_states_purple2.append(lang_states_kpca2d[i][1])
labels_purple.append(labels[i])
elif np.argmax(labels[i][1]) == np.argmax(yellow_v[0]):
lang_states_yellow.append(lang_states_kpca2d[i][0])
lang_states_yellow2.append(lang_states_kpca2d[i][1])
labels_yellow.append(labels[i])
red_pca = lang_states_red
red_pca2 = lang_states_red2
green_pca = lang_states_green
green_pca2 = lang_states_green2
blue_pca = lang_states_blue
blue_pca2 = lang_states_blue2
purple_pca = lang_states_purple
purple_pca2 = lang_states_purple2
yellow_pca = lang_states_yellow
yellow_pca2 = lang_states_yellow2
# mean values of pca
red_mean, green_mean, blue_mean, purple_mean, yellow_mean = self.get_mean_latent(kpca2d_1, kpca2d_2, labels)
red_pca_m = np.array(red_mean)[:, 0]
red_pca2_m = np.array(red_mean)[:, 1]
green_pca_m = np.array(green_mean)[:, 0]
green_pca2_m = np.array(green_mean)[:, 1]
blue_pca_m = np.array(blue_mean)[:, 0]
blue_pca2_m = np.array(blue_mean)[:, 1]
purple_pca_m = np.array(purple_mean)[:, 0]
purple_pca2_m = np.array(purple_mean)[:, 1]
yellow_pca_m = np.array(yellow_mean)[:, 0]
yellow_pca2_m = np.array(yellow_mean)[:, 1]
labels_red_m = [dp.lang_vec("grasp red .", max_len=5)[0], dp.lang_vec("move red left .", max_len=5)[0],
dp.lang_vec("move red right .", max_len=5)[0], dp.lang_vec("move red front .", max_len=5)[0],
dp.lang_vec("move red back .", max_len=5)[0], dp.lang_vec("put red on green .", max_len=5)[0],
dp.lang_vec("put red on blue .", max_len=5)[0],
dp.lang_vec("put red on yellow .", max_len=5)[0]]
labels_green_m = [dp.lang_vec("grasp green .", max_len=5)[0], dp.lang_vec("move green left .", max_len=5)[0],
dp.lang_vec("move green right .", max_len=5)[0],
dp.lang_vec("move green front .", max_len=5)[0],
dp.lang_vec("move green back .", max_len=5)[0],
dp.lang_vec("put green on green .", max_len=5)[0],
dp.lang_vec("put green on blue .", max_len=5)[0],
dp.lang_vec("put green on yellow .", max_len=5)[0]]
labels_blue_m = [dp.lang_vec("grasp blue .", max_len=5)[0], dp.lang_vec("move blue left .", max_len=5)[0],
dp.lang_vec("move blue right .", max_len=5)[0], dp.lang_vec("move blue front .", max_len=5)[0],
dp.lang_vec("move blue back .", max_len=5)[0],
dp.lang_vec("put blue on green .", max_len=5)[0],
dp.lang_vec("put blue on blue .", max_len=5)[0],
dp.lang_vec("put blue on yellow .", max_len=5)[0]]
labels_purple_m = [dp.lang_vec("grasp purple .", max_len=5)[0], dp.lang_vec("move purple left .", max_len=5)[0],
dp.lang_vec("move purple right .", max_len=5)[0],
dp.lang_vec("move purple front .", max_len=5)[0],
dp.lang_vec("move purple back .", max_len=5)[0],
dp.lang_vec("put purple on green .", max_len=5)[0],
dp.lang_vec("put purple on blue .", max_len=5)[0],
dp.lang_vec("put purple on yellow .", max_len=5)[0]]
labels_yellow_m = [dp.lang_vec("grasp yellow .", max_len=5)[0], dp.lang_vec("move yellow left .", max_len=5)[0],
dp.lang_vec("move yellow right .", max_len=5)[0],
dp.lang_vec("move yellow front .", max_len=5)[0],
dp.lang_vec("move yellow back .", max_len=5)[0],
dp.lang_vec("put yellow on green .", max_len=5)[0],
dp.lang_vec("put yellow on blue .", max_len=5)[0],
dp.lang_vec("put yellow on yellow .", max_len=5)[0]]
#
# if len(lang_states_moveback) != 0 and len(lang_states_movefront) != 0:
# if len(lang_states_putonyellow) != 0 and len(lang_states_putonblue) != 0:
# labels_red_m = [dp.lang_vec("grasp red .", max_len=5)[0], dp.lang_vec("move red left .", max_len=5)[0],
# dp.lang_vec("move red right .", max_len=5)[0], dp.lang_vec("move red front .", max_len=5)[0],
# dp.lang_vec("move red back .", max_len=5)[0],dp.lang_vec("put red on green .", max_len=5)[0],
# dp.lang_vec("put red on blue .", max_len=5)[0], dp.lang_vec("put red on yellow .", max_len=5)[0]]
# labels_green_m = [dp.lang_vec("grasp green .", max_len=5)[0], dp.lang_vec("move green left .", max_len=5)[0],
# dp.lang_vec("move green right .", max_len=5)[0], dp.lang_vec("move green front .", max_len=5)[0],
# dp.lang_vec("move green back .", max_len=5)[0],dp.lang_vec("put green on green .", max_len=5)[0],
# dp.lang_vec("put green on blue .", max_len=5)[0], dp.lang_vec("put green on yellow .", max_len=5)[0]]
# labels_blue_m = [dp.lang_vec("grasp blue .", max_len=5)[0], dp.lang_vec("move blue left .", max_len=5)[0],
# dp.lang_vec("move blue right .", max_len=5)[0], dp.lang_vec("move blue front .", max_len=5)[0],
# dp.lang_vec("move blue back .", max_len=5)[0],dp.lang_vec("put blue on green .", max_len=5)[0],
# dp.lang_vec("put blue on blue .", max_len=5)[0], dp.lang_vec("put blue on yellow .", max_len=5)[0]]
# labels_purple_m = [dp.lang_vec("grasp purple .", max_len=5)[0], dp.lang_vec("move purple left .", max_len=5)[0],
# dp.lang_vec("move purple right .", max_len=5)[0], dp.lang_vec("move purple front .", max_len=5)[0],
# dp.lang_vec("move purple back .", max_len=5)[0],dp.lang_vec("put purple on green .", max_len=5)[0],
# dp.lang_vec("put purple on blue .", max_len=5)[0], dp.lang_vec("put purple on yellow .", max_len=5)[0]]
# labels_yellow_m = [dp.lang_vec("grasp yellow .", max_len=5)[0], dp.lang_vec("move yellow left .", max_len=5)[0],
# dp.lang_vec("move yellow right .", max_len=5)[0], dp.lang_vec("move yellow front .", max_len=5)[0],
# dp.lang_vec("move yellow back .", max_len=5)[0],dp.lang_vec("put yellow on green .", max_len=5)[0],
# dp.lang_vec("put yellow on blue .", max_len=5)[0], dp.lang_vec("put yellow on yellow .", max_len=5)[0]]
#
# else:
# labels_red_m = [dp.lang_vec("grasp red .", max_len=5)[0], dp.lang_vec("move red left .", max_len=5)[0],
# dp.lang_vec("move red right .", max_len=5)[0], dp.lang_vec("move red front .", max_len=5)[0],
# dp.lang_vec("move red back .", max_len=5)[0],dp.lang_vec("put red on green .", max_len=5)[0]]
# labels_green_m = [dp.lang_vec("grasp green .", max_len=5)[0], dp.lang_vec("move green left .", max_len=5)[0],
# dp.lang_vec("move green right .", max_len=5)[0], dp.lang_vec("move green front .", max_len=5)[0],
# dp.lang_vec("move green back .", max_len=5)[0],dp.lang_vec("put green on green .", max_len=5)[0]]
# labels_blue_m = [dp.lang_vec("grasp blue .", max_len=5)[0], dp.lang_vec("move blue left .", max_len=5)[0],
# dp.lang_vec("move blue right .", max_len=5)[0], dp.lang_vec("move blue front .", max_len=5)[0],
# dp.lang_vec("move blue back .", max_len=5)[0],dp.lang_vec("put blue on green .", max_len=5)[0]]
# labels_purple_m = [dp.lang_vec("grasp purple .", max_len=5)[0], dp.lang_vec("move purple left .", max_len=5)[0],
# dp.lang_vec("move purple right .", max_len=5)[0], dp.lang_vec("move purple front .", max_len=5)[0],
# dp.lang_vec("move purple back .", max_len=5)[0],dp.lang_vec("put purple on green .", max_len=5)[0]]
# labels_yellow_m = [dp.lang_vec("grasp yellow .", max_len=5)[0], dp.lang_vec("move yellow left .", max_len=5)[0],
# dp.lang_vec("move yellow right .", max_len=5)[0], dp.lang_vec("move yellow front .", max_len=5)[0],
# dp.lang_vec("move yellow back .", max_len=5)[0],dp.lang_vec("put yellow on green .", max_len=5)[0]]
# else:
# labels_red_m = [dp.lang_vec("grasp red .", max_len=5)[0], dp.lang_vec("move red left .", max_len=5)[0],
# dp.lang_vec("put red on green .", max_len=5)[0]]
# labels_green_m = [dp.lang_vec("grasp green .", max_len=5)[0],
# dp.lang_vec("move green left .", max_len=5)[0],
# dp.lang_vec("put green on green .", max_len=5)[0]]
# labels_blue_m = [dp.lang_vec("grasp blue .", max_len=5)[0], dp.lang_vec("move blue left .", max_len=5)[0],
# dp.lang_vec("put blue on green .", max_len=5)[0]]
# labels_purple_m = [dp.lang_vec("grasp purple .", max_len=5)[0],
# dp.lang_vec("move purple left .", max_len=5)[0],
# dp.lang_vec("put purple on green .", max_len=5)[0]]
# labels_yellow_m = [dp.lang_vec("grasp yellow .", max_len=5)[0],
# dp.lang_vec("move yellow left .", max_len=5)[0],
# dp.lang_vec("put yellow on green .", max_len=5)[0]]
col_rm, markers_rm = self.gen_markers(labels_red_m, ['red'])
col_gm, markers_gm = self.gen_markers(labels_green_m, ['green'])
col_bm, markers_bm = self.gen_markers(labels_blue_m, ['blue'])
if len(purple_pca_m) != 0 and len(yellow_pca_m) != 0:
col_pm, markers_pm = self.gen_markers(labels_purple_m, ['purple'])
col_ym, markers_ym = self.gen_markers(labels_yellow_m, ['yellow'])
print("no. of markers={}".format(len(markers_rm)))
if len(purple_pca) != 0 and len(yellow_pca) != 0:
fig2d = plt.figure(figsize=(15, 3))
axr = fig2d.add_subplot(151)
axg = fig2d.add_subplot(152)
axb = fig2d.add_subplot(153)
axp = fig2d.add_subplot(154)
axy = fig2d.add_subplot(155)
# to plot mean values
fig2dm = plt.figure(figsize=(15, 3))
axrm = fig2dm.add_subplot(151)
axgm = fig2dm.add_subplot(152)
axbm = fig2dm.add_subplot(153)
axpm = fig2dm.add_subplot(154)
axym = fig2dm.add_subplot(155)
else:
fig2d = plt.figure(figsize=(9, 3))
axr = fig2d.add_subplot(131)
axg = fig2d.add_subplot(132)
axb = fig2d.add_subplot(133)
fig2dm = plt.figure(figsize=(9, 3))
axrm = fig2dm.add_subplot(131)
axgm = fig2dm.add_subplot(132)
axbm = fig2dm.add_subplot(133)
# print(len(red_pca_m))
# exit()
mean_marker_size=80
for i in range(len(red_pca_m)):
if red_pca_m[i] == 0 and i != len(red_pca_m)-1:
red_pca_m[i] = red_pca_m[i+1]
red_pca2_m[i] = red_pca2_m[i+1]
if green_pca_m[i] == 0 and i != len(red_pca_m)-1:
green_pca_m[i] = green_pca_m[i+1]
green_pca2_m[i] = green_pca2_m[i+1]
if blue_pca_m[i] == 0 and i != len(red_pca_m)-1:
blue_pca_m[i] = blue_pca_m[i+1]
blue_pca2_m[i] = blue_pca2_m[i+1]
elif red_pca_m[i] !=0:
axrm.scatter(red_pca_m[i], red_pca2_m[i], c='r', marker=markers_rm[i], s=mean_marker_size, alpha=0.8)
axgm.scatter(green_pca_m[i], green_pca2_m[i], c='g', marker=markers_gm[i], s=mean_marker_size, alpha=0.8)
axbm.scatter(blue_pca_m[i], blue_pca2_m[i], c='b', marker=markers_bm[i], s=mean_marker_size, alpha=0.8)
if len(purple_pca) != 0 and len(yellow_pca) != 0:
if purple_pca_m[i] == 0 and i != len(red_pca_m)-1:
purple_pca_m[i] = purple_pca_m[i + 1]
purple_pca2_m[i] = purple_pca2_m[i + 1]
if yellow_pca_m[i] == 0 and i != len(red_pca_m)-1:
yellow_pca_m[i] = yellow_pca_m[i + 1]
yellow_pca2_m[i] = yellow_pca2_m[i + 1]
elif purple_pca_m[i] != 0:
axpm.scatter(purple_pca_m[i], purple_pca2_m[i], c='m', marker=markers_pm[i], s=mean_marker_size, alpha=0.8)
axym.scatter(yellow_pca_m[i], yellow_pca2_m[i], c='y', marker=markers_ym[i], s=mean_marker_size, alpha=0.8)
fig2dm.tight_layout()
fig2dm.savefig("{}/{}.png".format(dir, fn + "pca2d_nouns_mean"), bbox_inches='tight')
col_r, markers_r = self.gen_markers(labels_red, ['red'])
col_g, markers_g = self.gen_markers(labels_green, ['green'])
col_b, markers_b = self.gen_markers(labels_blue, ['blue'])
if len(purple_pca) != 0 and len(yellow_pca) != 0:
col_p, markers_p = self.gen_markers(labels_purple, ['purple'])
col_y, markers_y = self.gen_markers(labels_yellow, ['yellow'])
for i in range(len(red_pca)):
axr.scatter(red_pca[i], red_pca2[i], c='r', label=self.gen_lang(labels_red[i]), marker=markers_r[i], alpha=alph)
# axr.set_title('red')
# axr.set_xlim(0, 1)
# axr.set_ylim(0, 1)
axg.scatter(green_pca[i], green_pca2[i], c='g', label=self.gen_lang(labels_green[i]), marker=markers_g[i], alpha=alph)
# axg.set_title("green")
# axg.set_xlim(0, 1)
# axg.set_ylim(0, 1)
axb.scatter(blue_pca[i], blue_pca2[i], c='b', label=self.gen_lang(labels_blue[i]), marker=markers_b[i], alpha=alph)
# axb.set_title("blue")
# axb.set_xlim(0, 1)
# axb.set_ylim(0, 1)
if len(purple_pca) != 0 and len(yellow_pca) != 0:
axp.scatter(purple_pca[i], purple_pca2[i], c='m', label=self.gen_lang(labels_purple[i]), marker=markers_p[i], alpha=alph)
# axp.set_title("purple")
# axp.set_xlim(0, 1)
# axp.set_ylim(0, 1)
axy.scatter(yellow_pca[i], yellow_pca2[i], c='y', label=self.gen_lang(labels_yellow[i]), marker=markers_y[i], alpha=alph)
# axy.set_title("yellow")
# axy.set_xlim(0, 1)
# axy.set_ylim(0, 1)
fig2d.tight_layout()
fig2d.savefig("{}/{}.png".format(dir, fn+"pca2d_nouns"), bbox_inches='tight')
plt.close()
#
n = 3
if lang_states.shape[-1] < n:
nc = lang_states.shape[-1]
iso_l = self.isomap(nc=nc)
iso_lang = iso_l.fit_transform(lang_states[:].numpy())
kpca_l = self.kpca(nc=nc, kernel='linear')
kpca_lang = kpca_l.fit_transform(lang_states[:].numpy())
pca_l = self.pca(nc)
pca_lang = pca_l.fit_transform(lang_states[:].numpy())
umap_reducer = self.umap(nc=3, n_neighbors=80)
umap_lang = umap_reducer.fit_transform(lang_states[:].numpy())
tsne_l = self.tsne(nc=3)
tsne_lang = tsne_l.fit_transform(lang_states.numpy())
else:
nc = n
iso_l = self.isomap(nc=nc)
iso_lang = iso_l.fit_transform(lang_states[:].numpy())
kpca_l = self.kpca(nc=nc, kernel='cosine')
kpca_lang = kpca_l.fit_transform(lang_states[:].numpy())
pca_lang = lang_states.numpy()
umap_reducer = self.umap(nc=3)
umap_lang = umap_reducer.fit_transform(lang_states[:].numpy())
tsne_l = self.tsne(nc=3)
tsne_lang = tsne_l.fit_transform(lang_states.numpy())
# clustered_sne = clus.fit_transform(tsne_lang)
clustered_umap = clus.fit_transform(umap_lang)
#
# print("nc={}".format(nc))
# print("shape = {}".format(lang_states.numpy().shape))
# print("umapshape = {}".format(umap_lang.shape))
# print("labels shape = {}".format(labels.shape))
#
col, markers = self.gen_markers(labels, colors)
# fig_l = plt.figure()
# ax = fig_l.add_subplot(111, projection='3d')
# # ax_p1 = fig_l.add_subplot(211)
# # ax_p2 = fig_l.add_subplot(212)
#
label_str = []
for l in range(len(labels)):
label_str.append(self.gen_lang(labels[l]))
# for i in range(len(pca_lang)):
# # ax_p1.scatter(pca_lang[i][0], pca_lang[i][1], c=col[i], label=label_str[i], marker=markers[i])
# # ax_p2.scatter(pca_lang[i][2], pca_lang[i][3], c=col[i], label=label_str[i], marker=markers[i])
# #
# # box = ax_p2.get_position()
# # ax_p2.set_position([box.x0, box.y0, box.width * 0.8, box.height])
# ax.scatter(pca_lang[i][0], pca_lang[i][1], pca_lang[i][2], c=col[i], label=label_str[i], marker=markers[i])
# # ax.scatter(clustered_pca[i][0], clustered_pca[i][1], clustered_pca[i][2], c=col[i], label=label_str[i], marker=markers[i])
#
# # ax.plot(pca_lang[i][0], pca_lang[i][1], pca_lang[i][2], 'o', ms=20, mec='red', mfc='none', mew=2)
# # plt.tight_layout()
# fig_l.tight_layout()
# # fig_l.subplots_adjust(right=0.05)
# self.legend_without_duplicate_labels(ax, loc='upper center', fontsize=5, n_col=2, bbox_to_anchor=(1.5, 0.5))
# # plt.show()
# plt.savefig("{}/{}.png".format(dir, fn), bbox_inches='tight')
# plt.close()
#
# fig_k = plt.figure()
# axk = fig_k.add_subplot(111, projection='3d')
# for i in range(len(pca_lang)):
# axk.scatter(kpca_lang[i][0], kpca_lang[i][1], kpca_lang[i][2], c=col[i], label=label_str[i], marker=markers[i])
# fig_k.tight_layout()
# self.legend_without_duplicate_labels(axk, loc='upper center', fontsize=5, n_col=2, bbox_to_anchor=(1.3, 0.5))
# plt.savefig("{}/{}.png".format(dir, fn+"kpca"), bbox_inches='tight')
# plt.close()
#
# fig_i = plt.figure()
# axi = fig_i.add_subplot(111, projection='3d')
# for i in range(len(pca_lang)):
# axi.scatter(iso_lang[i][0], iso_lang[i][1], iso_lang[i][2], c=col[i], label=label_str[i], marker=markers[i])
# fig_i.tight_layout()
# self.legend_without_duplicate_labels(axi, loc='upper center', fontsize=5, n_col=2, bbox_to_anchor=(1.3, 0.5))
# plt.savefig("{}/{}.png".format(dir, fn+"iso"), bbox_inches='tight')
# plt.close()
#
fig2 = plt.figure()
ax1 = fig2.add_subplot(111, projection='3d')
for i in range(len(umap_lang)):
# ax1.scatter(umap_lang[i][0], umap_lang[i][1], umap_lang[i][2], c=col[i], label=label_str[i], marker=markers[i])
ax1.scatter(clustered_umap[i][0], clustered_umap[i][1], clustered_umap[i][2], c=col[i],
label=label_str[i], marker=markers[i])
fig2.tight_layout()
self.legend_without_duplicate_labels(ax1, loc='upper center', fontsize=5, n_col=2)
plt.savefig("{}/{}.png".format(dir, fn+"umap"), bbox_inches='tight')
plt.close()
#
# fig3 = plt.figure()
# ax2 = fig3.add_subplot(111, projection='3d')
# for i in range(len(tsne_lang)):
# # ax2.scatter(tsne_lang[i][0], tsne_lang[i][1], tsne_lang[i][2], c=col[i], label=label_str[i], marker=markers[i])
# ax2.scatter(clustered_sne[i][0], clustered_sne[i][1], clustered_sne[i][2], c=col[i], label=label_str[i], marker=markers[i])
# fig3.tight_layout()
# self.legend_without_duplicate_labels(ax2, loc='upper center', fontsize=5, n_col=2)
# plt.savefig("{}/{}.png".format(dir, fn+"tsne"), bbox_inches='tight')
# plt.close()
save_dict = {'pca_lang_latent_states': lang_states_kpca2d, 'lang_labels': labels,
"label_index_list": labels_idx, 'lang_latent_states': lang_states.numpy()}
np.savez(dir+"/latentplotdata", **save_dict)
########
def usefn(self):
dir = "exp_comp1_5x8_10_101/v-1/trainstate4500/rep0_aea5ec92-bb9d-41ef-9c9f-7d4c2b91aef5"
data = np.load(dir + "/latentplotdata.npz")
lang_states = data['lang_latent_states']
labels = data['lang_labels']
from utils import IO
io = IO(dir)
io.plot_lang_latent(dir=dir,
lang_states=lang_states, labels=labels, colors=['red', 'green', 'blue', 'purple', 'yellow'],
fn='/lang_latent2'
)
########
def plot_latentstates(self, states, nc=5, name='pvrnn_d.png'):
"""
return pca plot of latent state of activity of layers in the network
todo:it should be able to visualize prior and posterior activity of PVRNN as well
"""
# ToDo
fig = plt.figure(figsize=(10,5))
r, c = len(states[0]), 1
new_states, states_pca = self.pca_states(states, nc=nc)
print(states_pca[0].shape)
for l in range(len(states[0])):
ax = fig.add_subplot(r,c,l+1)
ax.plot(states_pca[l])
plt.tight_layout()
plt.savefig('{}/{}.png'.format(self.work_dir, name))
plt.close()
def pca_init(self, pca, train_lang, test_lang):
lang = torch.cat((train_lang, test_lang))
pca_lang = pca.fit_transform(lang.numpy().reshape(len(lang), -1))
train_lang_pca, test_lang_pca = pca_lang[:len(train_lang), :], pca_lang[len(train_lang):, :]
return torch.from_numpy(train_lang_pca), torch.from_numpy(test_lang_pca)
def load_model(self, model, **model_args):
Model = import_class(model)
model = Model(**model_args)
self.model_text += '\n\n' + str(model)
return model
def load_weights(self, model, weights_path, ignore_weights=None):
if ignore_weights is None:
ignore_weights = []
if isinstance(ignore_weights, str):
ignore_weights = [ignore_weights]
self.print_log('Load weights from {}.'.format(weights_path))
weights = torch.load(weights_path)
weights = OrderedDict([[k.split('module.')[-1],
v.cpu()] for k, v in weights.items()])
# filter weights
for i in ignore_weights:
ignore_name = list()
for w in weights:
if w.find(i) == 0:
ignore_name.append(w)