forked from kennedyCzar/GCVAE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
executable file
·2489 lines (2182 loc) · 124 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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
seed = 124
import math
import os
from tqdm import tqdm
import tensorflow as tf
from tensorflow import keras
from sklearn.mixture import GaussianMixture
import torch; torch.manual_seed(seed)
import torch.utils
import torch.distributions
import numpy as np
import torch.nn.functional as F
import matplotlib.patheffects as pe
import matplotlib.pyplot as plt; plt.rcParams['figure.dpi'] = 100
device = 'cuda' if torch.cuda.is_available() else 'cpu'
#word embeddings use..
from gensim.corpora import Dictionary
from gensim.models import Word2Vec
from gensim.similarities import WordEmbeddingSimilarityIndex
from gensim.similarities import SoftCosineSimilarity, SparseTermSimilarityMatrix
#import dependencies for evaluation metric
from sklearn.preprocessing import minmax_scale
from sklearn.metrics import mean_squared_error
from pyitlib import discrete_random_variable as drv
#dependencies for validation Eastword disentaglement metric
from sklearn.linear_model import Lasso
from sklearn.ensemble.forest import RandomForestRegressor
# training utilities...
def MSE(x_original, x_predicted):
'''
Parameters
----------
x_original : np.array
original data.
x_predicted : np.array
reconstructed data or decoder output.
Returns
-------
int
Mean Square Error loss.
'''
return F.mse_loss(x_original, x_predicted)
def binary_cross_entropy_loss(x_original, x_predicted, withsigmoid = False):
'''
Parameters
----------
x_original : np.array
original data.
x_predicted : np.array
reconstructed data or decoder output.
Returns
-------
int
Binary CrossEntropy Loss.
'''
if not withsigmoid:
return F.binary_cross_entropy(x_predicted, x_original)
else:
return F.binary_cross_entropy_with_logits(x_predicted, x_original)
def plot_latent(model, test, input_dim, num_batches = 100, dt = 'MNIST_cnn'):
plt.figure(figsize=(12, 10))
for i, x in enumerate(test): #(x, y) if MNIST dataset
if dt == 'MNIST_ff':
x = x.view(-1, 1, input_dim).to(device)
z = model.encoder(x.to(device))
z = z.to(device).detach().numpy()
z = z.reshape(-1, z.shape[2])
elif dt == 'MNIST_cnn':
x = x.view(-1, 1, input_dim).to(device)
z, _, _ = model.encoder(x.to(device))
z = z.to(device).detach().numpy()
elif dt == 'normal':
x = x.view(-1, 1, input_dim).to(device)
z, _, _ = model.encoder(x.to(device))
z = z.to(device).detach().numpy()
plt.scatter(z[:, 0], z[:, 1], cmap='tab10', edgecolor="black", s = 20) #, c=y for MNISt datastet
plt.xlabel('z[0]-latent')
plt.ylabel('z[1]-latent')
def plot_losses(epochs, ELBO, RECON_LOSS, KL_DIV):
'''
Parameters
----------
epochs : int
Number of epochs to run training.
ELBO : int
Evidence Lower Bound or Variational Loss.
RECON_LOSS : int
Reconstruction loss.
KL_DIV : TYPE
KL divergence between two Gaussian distribution.
Returns
-------
matplotlib object.
'''
#vae mean and std
epochs = np.arange(1, epochs+1)
#check index of when ELBO is +ve and -ve
bc_pos = lambda x: [(i,j) for (i,j) in enumerate(x) if j>0]
#bc_neg = lambda x: [(i,j) for (i,j) in enumerate(x) if j<0]
ind_kl_elbo_pos = bc_pos(ELBO)[-1][0] +1 #index of last postive value. shift of 1 since epoch is shifted by +1
ind_kl_elbo_neg = ind_kl_elbo_pos + 1 #index of negative value
#---
try:
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.plot(epochs, ELBO, lw = 1.5, c = 'r', label = 'ELBO',
path_effects=[pe.SimpleLineShadow(), pe.Normal()])
ax1.plot(epochs, RECON_LOSS, path_effects=[pe.SimpleLineShadow(), pe.Normal()],
lw = 1.5, c = 'g', label = 'Reconstruction loss')
ax1.axhline(y = 0, color='r', ls = '--')
ax1.axvline(x = ind_kl_elbo_pos, ymin = 0.0, ymax = epochs[-1], color='b')
ax1.axvline(x = ind_kl_elbo_neg, ymin = 0.0, ymax = epochs[-1], color='r')
ax1.legend()
ax1.grid()
ax1.set_xlabel('Numbers of epochs')
ax1.set_ylabel('Loss')
ax2.plot(epochs, KL_DIV, path_effects=[pe.SimpleLineShadow(), pe.Normal()],
lw = 1.5, c = 'b', label = 'KL divergence')
ax2.axvline(x = ind_kl_elbo_pos, ymin = 0.0, ymax = epochs[-1], color='b')
ax2.axvline(x = ind_kl_elbo_neg, ymin = 0.0, ymax = epochs[-1], color='r')
ax2.legend()
ax2.grid()
ax2.set_xlabel('Numbers of epochs')
ax2.set_ylabel('KL divegrence')
plt.show()
except:
pass
def plot_losses_with_latent(epochs, ELBO, RECON_LOSS, KL_DIV, z_latent_pos, z_latent_neg):
'''
Parameters
----------
epochs : int
Number of epochs to run training.
ELBO : int
Evidence Lower Bound or Variational Loss.
RECON_LOSS : int
Reconstruction loss.
KL_DIV : TYPE
KL divergence between two Gaussian distribution.
Returns
-------
matplotlib object.
'''
#vae mean and std
epochs = np.arange(1, epochs+1)
#check index of when ELBO is +ve and -ve
bc_pos = lambda x: [(i,j) for (i,j) in enumerate(x) if j>0]
#bc_neg = lambda x: [(i,j) for (i,j) in enumerate(x) if j<0]
ind_kl_elbo_pos = bc_pos(ELBO)[-1][0] +1 #index of last postive value. shift of 1 since epoch is shifted by +1
ind_kl_elbo_neg = ind_kl_elbo_pos + 1 #index of negative value
#---
fig, ax = plt.subplots(2, 2)
if isinstance(z_latent_pos, np.ndarray):
ax[0, 0].scatter(z_latent_pos[:, 0], z_latent_pos[:, 1], cmap='tab10', edgecolor="blue", s = 20)
ax[0, 0].set_xlabel('z[0]-latent: Before')
ax[0, 0].set_ylabel('z[1]-latent')
else:
pass
ax[0, 1].plot(epochs, ELBO, lw = 1.5, c = 'r', label = 'ELBO',
path_effects=[pe.SimpleLineShadow(), pe.Normal()])
ax[0, 1].plot(epochs, RECON_LOSS, path_effects=[pe.SimpleLineShadow(), pe.Normal()],
lw = 1.5, c = 'g', label = 'Reconstruction loss')
ax[0, 1].axhline(y = 0, color='r', ls = '--')
ax[0, 1].axvline(x = ind_kl_elbo_pos, ymin = 0.0, ymax = epochs[-1], color='b')
ax[0, 1].axvline(x = ind_kl_elbo_neg, ymin = 0.0, ymax = epochs[-1], color='r')
ax[0, 1].legend()
ax[0, 1].grid()
ax[0, 1].set_xlabel('Numbers of epochs')
ax[0, 1].set_ylabel('Loss')
if isinstance(z_latent_neg, np.ndarray):
ax[1, 0].scatter(z_latent_neg[:, 0], z_latent_neg[:, 1], cmap='tab10', edgecolor="red", s = 20) #, c=y for MNISt datastet
ax[1, 0].set_xlabel('z[0]-latent: After')
ax[1, 0].set_ylabel('z[1]-latent')
else:
pass
ax[1, 1].plot(epochs, KL_DIV, path_effects=[pe.SimpleLineShadow(), pe.Normal()],
lw = 1.5, c = 'b', label = 'KL divergence')
ax[1, 1].axvline(x = ind_kl_elbo_pos, ymin = 0.0, ymax = epochs[-1], color='b')
ax[1, 1].axvline(x = ind_kl_elbo_neg, ymin = 0.0, ymax = epochs[-1], color='r')
ax[1, 1].legend()
ax[1, 1].grid()
ax[1, 1].set_xlabel('Numbers of epochs')
ax[1, 1].set_ylabel('KL divegrence')
plt.show()
def best_gmm_model(z, n_components = 50):
np.random.seed(50)
lowest_bic = np.infty
bic = []
n_components_range = range(1, n_components)
cv_types = ['spherical', 'tied', 'diag', 'full']
ls = z
for cv_type in cv_types:
for n_components in n_components_range:
# Fit a Gaussian mixture with EM
gmm = GaussianMixture(n_components=n_components, covariance_type=cv_type)
gmm.fit(ls)
bic.append(gmm.bic(ls))
if bic[-1] < lowest_bic:
lowest_bic = bic[-1]
best_gmm = gmm
return best_gmm
def compute_kernel(x, y):
x_size = tf.shape(x)[0]
y_size = tf.shape(y)[0]
dim = tf.shape(x)[1]
tiled_x = tf.tile(tf.reshape(x, tf.stack([x_size, 1, dim])), tf.stack([1, y_size, 1]))
tiled_y = tf.tile(tf.reshape(y, tf.stack([1, y_size, dim])), tf.stack([x_size, 1, 1]))
return tf.exp(-tf.reduce_mean(tf.square(tiled_x - tiled_y), axis=-1) / tf.cast(dim, tf.float32))
def z_mahalanobis(z, diag:bool = False, psd = False)->float:
'''
Parameters
----------
z : numpy array
latent array/code.
diag : bool, optional
Diagonal of the covariance matrix. The default is False.
Returns
-------
float
mahalanobis mean of the latent vector.
'''
z = z.numpy()
m = lambda z: z - z.mean(axis = 0) #mean of vectors
z_m = m(z) #mean centered data
cov = 1/(len(z)-1)*z_m.T.dot(z_m)
diag_cov = np.diag(np.diag(cov))
#check if matrix entries are
if not psd:
cov = 1/(len(z)-1)*z_m.T.dot(z_m)
diag_cov = np.diag(np.diag(cov))
else:
cov = 1/(len(z)-1)*z_m.T.dot(z_m)
cov = np.where(cov < 0, 0, cov)
diag_cov = np.diag(np.diag(cov))
diag_cov = np.where(diag_cov < 0, 0, diag_cov)
if not diag:
inv_cov = np.linalg.inv(cov) #inverse of a full covariance matrix
else:
inv_cov = np.linalg.inv(diag_cov) #inverse of diagonal covariance matrix
trans_x = z_m.dot(inv_cov).dot(z_m.T)
mah_mat_mean = np.mean(trans_x.diagonal())
return tf.Variable(mah_mat_mean, dtype=tf.float32)
def z_mahalanobis_v2(z_1, z_2, diag:bool = False, psd = False)->float:
'''
Parameters
----------
z : numpy array
latent array/code.
diag : bool, optional
Diagonal of the covariance matrix. The default is False.
Returns
-------
float
mahalanobis mean of the latent vector.
'''
z_1 = z_1.numpy()
z_2 = z_2.numpy()
m = lambda z: z - z.mean(axis = 0) #mean of vectors
z_m_1 = m(z_1) #mean centered data matrix 1
z_m_2 = m(z_2) #mean centered data matrix 2
#check if matrix entries are
if not psd:
cov = 1/(len(z_1)-1)*z_m_1.T.dot(z_m_2)
diag_cov = np.diag(np.diag(cov))
else:
cov = 1/(len(z_1)-1)*z_m_1.T.dot(z_m_2)
cov = np.where(cov < 0, 0, cov)
diag_cov = np.diag(np.diag(cov))
diag_cov = np.where(diag_cov < 0, 0, diag_cov)
if not diag:
inv_cov = np.linalg.inv(cov) #inverse of a full covariance matrix
else:
inv_cov = np.linalg.inv(diag_cov) #inverse of diagonal covariance matrix
trans_x = z_m_1.dot(inv_cov).dot(z_m_2.T)
mah_mat_mean = np.mean(trans_x.diagonal())
return tf.Variable(mah_mat_mean, dtype=tf.float32)
def z_mahalanobis_rkhs(z, diag:bool = False, psd = False)->float:
'''Reproducing Kernel Hilbert Space (RKHS)
Mahalanobis distance
Parameters
----------
z : numpy array
latent array/code.
diag : bool, optional
Diagonal of the covariance matrix. The default is False.
psd: bool, optional
is matrix is not positive semi definite
Returns
-------
float
mahalanobis mean of the latent vector.
'''
#z_sample = tf.keras.backend.random_normal(tf.shape(z), dtype = tf.float32, mean = 0., stddev = 1.0)
z = compute_kernel(z, z)
z = z.numpy()
m = lambda z: z - z.mean(axis = 0) #mean of vectors
z_m = m(z) #mean centered data
#check if matrix entries are
if not psd:
cov = 1/(len(z)-1)*z_m.T.dot(z_m)
diag_cov = np.diag(np.diag(cov))
else:
cov = 1/(len(z)-1)*z_m.T.dot(z_m)
cov = np.where(cov < 0, 0, cov)
diag_cov = np.diag(np.diag(cov))
diag_cov = np.where(diag_cov < 0, 0, diag_cov)
if not diag:
inv_cov = np.linalg.inv(cov) #inverse of a full covariance matrix
else:
inv_cov = np.linalg.inv(diag_cov) #inverse of diagonal covariance matrix
trans_x = z_m.dot(inv_cov).dot(z_m.T)
mah_mat_mean = np.mean(trans_x.diagonal())
return tf.Variable(mah_mat_mean, dtype=tf.float32)
#prepare FA data
def keywordReturn(text:list, keyword:str)->bool:
'''
Parameters
----------
text : list
list of the tokens to search.
keyword : str
keyword.
Returns
-------
bool
True or False.
'''
return True if keyword in text else False
class Mergefeatures():
def __init__(self, string):
super(Mergefeatures, self).__init__()
self.string = string
return
def concat(self):
'''Concatenate along the horizontal axis
'''
z = ','.join(y.strip('[]') for y in self.string)
z = [x.strip().strip("''") for x in z.split(',')]
z = ' '.join(x for x in z if not x == 'nan' if not x == ' ' if not x == '')
z = [x for x in z.split(' ')]
return z
class SimilarityMat():
def __init__(self, model, text):
'''Similarity Matrix
Parameters
----------
model:
text: textual document data set
Return
------
None
'''
self.model = model
self.text = text
#self.SimilarityMatrix()
return
def SimilarityMatrix(self):
'''
Return
-------
Returns Similarity matrix
'''
termsim_index = WordEmbeddingSimilarityIndex(self.model.wv)
self.dictionary = Dictionary(self.text)
bow_corpus = [self.dictionary.doc2bow(document) for document in self.text]
similarity_matrix = SparseTermSimilarityMatrix(termsim_index, self.dictionary)
self.docsim_index = SoftCosineSimilarity(bow_corpus, similarity_matrix)
return self
def QuerySim(self, query):
'''
Parameters
----------
query: Text to vectorize
Return
------
document similarity matrix
'''
return self.docsim_index[self.dictionary.doc2bow(query)]
def wordEmbed(self):
"""Word Embedding vector
Parameters
----------
None
Return
-------
word embedding vector
"""
self.features = []
for tokens in self.text:
self.zero_vector = np.zeros(self.model.vector_size)
self.vectors = []
for token in tokens:
if token in self.model.wv:
try:
self.vectors.append(self.model.wv[token])
except KeyError:
continue
if self.vectors:
self.vectors = np.asarray(self.vectors)
self.mean_vect = self.vectors.mean(axis = 0)
self.features.append(self.mean_vect)
else:
self.features.append(self.zero_vector)
self.feat_vect = np.array([x for x in self.features]) #reshape vectors
return self.feat_vect
#%% PID controllers
class PIDControl_v1(object):
def __init__(self):
self.I_k1 = 0.0
self.W_k1 = 1.0
self.e_k1 = 0.0
def _Kp_func(self, Err, scale=1):
return 1.0/(1.0 + float(scale)*np.exp(Err))
def pid(self, exp_KL, kl_divergence, Kp=0.1, Ki=-0.0001, Kd=0.01):
"""
position PID algorithm
Input: KL_loss
return: weight for KL loss, beta
"""
error_k = exp_KL - kl_divergence
## comput U as the control factor
Pk = Kp * self._Kp_func(error_k)+1
Ik = self.I_k1 + Ki * error_k
## window up for integrator
if self.W_k1 < 1:
Ik = self.I_k1
Wk = Pk + Ik
self.W_k1 = Wk
self.I_k1 = Ik
## min and max value
if Wk < 1:
Wk = 1
# return Wk, error_k
return Wk
class PIDControl_v2(object):
def __init__(self):
self.I_k1 = tf.Variable(0.0,trainable=False)
## W_k1 record the previous time weight W value
self.W_k1 = tf.Variable(0.0,trainable=False)
def _Kp_func(self, Err, scale=1.0):
return 1.0/(1.0+tf.exp(scale*Err))
def pid(self, exp_KL, KL_loss, Kp=0.1, Ki=-0.0001):
""" increment PID algorithm
Input: KL_loss
return: weight for KL loss, WL
$\beta$ only --> K_p = 0.1, K_i = -0.0001
$\beta$ only --> K_p = 0.1, K_i = -0.0001
"""
self.exp_KL = exp_KL
error_k = tf.stop_gradient(self.exp_KL - KL_loss)
## comput P control
Pk = Kp * self._Kp_func(error_k)
## I control accumulate error from time 0 to T
Ik = self.I_k1 + Ki * error_k
## when time = k-1
Ik = tf.cond(self.W_k1 < 0, lambda:self.I_k1, lambda:tf.cond(self.W_k1 > 1, lambda:self.I_k1, lambda:Ik))
# Ik = tf.cond(self.W_k1 > 1, lambda:self.I_k1, lambda:Ik)
## update k-1 accumulated error
op1 = tf.compat.v1.assign(self.I_k1,Ik) ## I_k1 = Ik
## update weight WL
Wk = Pk + Ik
op2 = tf.compat.v1.assign(self.W_k1,Wk) ## self.W_k1 = Wk
## min and max value --> 0 and 1
## if Wk > 1, Wk = 1; if Wk<0, Wk = 0
with tf.control_dependencies([op1,op2]):
Wk = tf.cond(Wk > 1, lambda: 1.0, lambda: tf.cond(Wk < 0, lambda: 0.0, lambda: Wk))
return Wk
#%% Plotting utils
def plot_latent_space(vae, n = 20, figsize = 15):
'''Source: https://keras.io/examples/generative/vae/
Parameters
----------
vae : tensorflow model
DESCRIPTION.
n : int, optional
DESCRIPTION. The default is 20.
figsize : matplotlib.pyplot object, optional
matplot graph. The default is 15.
Returns
-------
matplot object.
'''
# display a n*n 2D manifold of digits
digit_size = 28
scale = 1.0
figure = np.zeros((digit_size * n, digit_size * n))
# linearly spaced coordinates corresponding to the 2D plot
# of digit classes in the latent space
grid_x = np.linspace(-scale, scale, n)
grid_y = np.linspace(-scale, scale, n)[::-1]
for i, yi in enumerate(grid_y):
for j, xi in enumerate(grid_x):
z_sample = np.array([[xi, yi]])
x_decoded = vae.decoder.predict(z_sample)
digit = x_decoded[0].reshape(digit_size, digit_size)
figure[
i * digit_size : (i + 1) * digit_size,
j * digit_size : (j + 1) * digit_size,
] = digit
plt.figure(figsize=(figsize, figsize))
plt.axis('off')
#start_range = digit_size // 2
#end_range = n * digit_size + start_range
#pixel_range = np.arange(start_range, end_range, digit_size)
#sample_range_x = np.round(grid_x, 1)
#sample_range_y = np.round(grid_y, 1)
#plt.xticks(pixel_range, sample_range_x)
#plt.yticks(pixel_range, sample_range_y)
#plt.xlabel("z[0]")
#plt.ylabel("z[1]")
plt.imshow(figure, cmap="Greys_r")
plt.show()
#%% Evaluation metric
class Metric:
def __init__(self, x, y, nb_bins = 1000):
'''
Parameters
----------
x : R^{NxM} np.array (M: dimension of data)
True factors of the data.
y : R^{NxK} np.array (K: lower dimensional latent code)
Latent factor/code obtanined from Inference after N-epoch training.
nb_bins : int, optional
Number of bins to use for discretization.
The default is 1000.
Returns
-------
None.
'''
self.x = x
self.y = y
self.nb_bins = nb_bins
return
def get_mutual_information(self, x, y, normalize = True):
'''
Get mutual information
Parameters
----------
x : R^{NxM} np.array
True label.
y : R^{NxK} np.array
Predicted label. Note that N: number of observation; K: size of latent space
normalize : bool, optional
normalize mutual information score. The default is True.
Returns
-------
TYPE
DESCRIPTION.
'''
self.x, self.y = x, y
if normalize:
return drv.information_mutual_normalised(self.x, self.y, norm_factor='Y', cartesian_product = True)
else:
return drv.information_mutual(self.x, self.y, cartesian_product = True)
def get_bin_index(self, factor, nb_bins):
'''Get bin index
Parameters
----------
x : np.array
data.
nb_bins : int
number of bins to use for discretization.
Returns
-------
TYPE
DESCRIPTION.
'''
self.nb_bins = nb_bins
# get bins limits
bins = np.linspace(0, 1, self.nb_bins + 1)
# discretize input variable
return np.digitize(factor, bins[:-1], right = False).astype(int)
def compute_sparsity_(self, norm = True):
'''Compute sparsity score of the latent space obtained
from inference.
Parameters
----------
norm : bool, optional
normalize z latent by standard deviation. The default is True.
Returns
-------
float
Sparsity score.
'''
zs = self.y #latent
l_dim = zs.shape[-1]
if norm:
zs = zs / tf.math.reduce_std(zs)
numr_ = tf.math.reduce_sum(tf.math.abs(zs), axis = -1)
denm_ = tf.math.sqrt(tf.math.reduce_sum(tf.math.pow(zs, 2), -1))
l1_l2 = tf.reduce_mean(numr_/denm_)
return (math.sqrt(l_dim) - l1_l2) / (math.sqrt(l_dim) - 1)
@staticmethod
def mse(predicted, target):
'''Mean Squre Error
Parameters
----------
predicted : array
prediction or outcome.
target : array
expectated prediction outcome.
Returns
-------
float
Mean Square Error.
'''
# mean square error
predicted = predicted[:, None] if len(predicted.shape) == 1 else predicted # (n,)->(n,1)
target = target[:, None] if len(target.shape) == 1 else target # (n,)->(n,1)
err = predicted - target
err = err.T.dot(err) / len(err)
return err[0, 0]
@staticmethod
def rmse(predicted, target):
'''Root Mean Squre Error
Parameters
----------
predicted : array
prediction or outcome.
target : array
expectated prediction outcome.
Returns
-------
float
Root Mean Square Error.
'''
# root mean square error
return np.sqrt(Metric.mse(predicted, target))
@staticmethod
def nmse(predicted, target, eps = 1e-8):
'''Normalized Mean Squre Error
Parameters
----------
predicted : array
prediction or outcome.
target : array
expectated prediction outcome.
Returns
-------
float
Normalized Mean Squre Error.
'''
# normalized mean square error
return Metric.mse(predicted, target) / np.maximum(np.var(target), eps)
@staticmethod
def nrmse(predicted, target, eps = 1e-8):
'''Normalized Root Mean Squre Error
Parameters
----------
predicted : array
prediction or outcome.
target : array
expectated prediction outcome.
Returns
-------
float
Normalized Root Mean Squre Error.
'''
return Metric.rmse(predicted, target) / np.maximum(np.std(target), eps)
@staticmethod
def entropic_scores(R, eps = 1e-8):
''' Entropy scores
Parameters
----------
R : np.array
importance matrix: (num_latents, num_factors).
eps : np.float, optional
DESCRIPTION. The default is 1e-8.
Returns
-------
float
Entropy score.
'''
R = np.abs(R)
P = R / np.maximum(np.sum(R, axis=0), eps)
# H_norm: (num_factors,)
H_norm = -np.sum(P * np.log(np.maximum(P, eps)), axis=0)
if P.shape[0] > 1:
H_norm = H_norm / np.log(P.shape[0])
return 1 - H_norm
def kming(self, L = 1000, M = 10000):
'''Factor VAE disentanglement metric
@misc{modularity,
title={Disentangling by Factorising},
author={Hyunjik Kim, Andriy Mnih},
year={2019},
}
paper: https://arxiv.org/pdf/1802.05983.pdf
Parameters
----------
L : TYPE, optional
DESCRIPTION. The default is 25.
M : TYPE, optional
DESCRIPTION. The default is 1000.
Returns
-------
float
Z-min score proposed by Kim \& Minh.
'''
N, D = self.x.shape
_, K = self.y.shape #image data conats (NxLxM) dimension
zs_std = tf.math.reduce_std(self.x, axis = 0)
ys_uniq = [tf.unique(tf.reshape(c, [-1, ]))[0] for c in tf.split(self.y, K, 1)] #extract unique values from each y
V = tf.zeros([D, K], tf.float32).numpy()
ks = np.random.randint(0, K, M) #K: is the range of value; M: is the dimension # sample fixed-factor idxs ahead of time
for m in range(M):
k = ks[m]
fk_vals = ys_uniq[k]
# fix fk
fk = fk_vals[np.random.choice(len(fk_vals))]
# choose L random x that have this fk at factor k
zsh = self.x[self.y[:, k] == fk]
zsh = tf.random.shuffle(zsh)[:L]
d_star = tf.argmin(tf.math.reduce_variance(zsh/zs_std, axis=0)) #note that biased variance is computed in tensorflow
V[d_star, k] += 1
return tf.reduce_sum(tf.math.reduce_max(V, axis=1)) #/M
def mig(self, continuous_factors = True):
'''
MIG (Mutual Information Gap) metric from R. T. Q. Chen, X. Li, R. B. Grosse, and D. K. Duvenaud,
“Isolating sources of disentanglement in variationalautoencoders,”
in NeurIPS, 2018.
paper: https://arxiv.org/pdf/1802.04942.pdf
Parameters
----------
continuous_factors : bool, optional
True: factors are described as continuous variables
False: factors are described as discrete variables.
The default is True.
Returns
-------
mig_score : TYPE
DESCRIPTION.
'''
# count the number of factors and latent codes
nb_factors = self.x.shape[1] #original factors of data variable
nb_codes = self.y.shape[1] #latent variable
# quantize factors if they are continuous
if continuous_factors:
factors = minmax_scale(np.nan_to_num(self.x)) # normalize in [0, 1] all columns
factors = self.get_bin_index(self.x, self.nb_bins) # quantize values and get indexes
else:
factors = self.x
# quantize latent codes
if continuous_factors:
codes = minmax_scale(np.nan_to_num(self.y)) # normalize in [0, 1] all columns
codes = self.get_bin_index(self.y, self.nb_bins) # quantize values and get indexes
else:
codes = self.y
# compute mutual information matrix
mi_matrix = np.zeros((nb_factors, nb_codes))
for f in range(nb_factors):
for c in range(nb_codes):
mi_matrix[f, c] = self.get_mutual_information(factors[:, f], codes[:, c], normalize = False)
#compute discrete entropies
# num_factors = self.x.shape[0]
# h = np.zeros(num_factors)
# for e in range(num_factors):
# h[e] = self.get_mutual_information(factors[e, :], factors[e, :], normalize = False)
# compute the mean gap for all factors
sum_gap = 0
for f in range(nb_factors):
mi_f = np.sort(mi_matrix[f, :])
# get diff between highest and second highest term and add it to total gap
sum_gap += mi_f[-1] - mi_f[-2]
# compute the mean gap
mig_score = sum_gap / nb_factors
return mig_score
def modularity(self, continuous_factors=True):
'''
@misc{modularity,
title={Learning deep disentangled embeddings with the f-statistic loss},
author={K. Ridgeway and M. C. Mozer},
year={2018},
}
paper: https://arxiv.org/pdf/1802.05312.pdf
Parameters
----------
continuous_factors : bool, optional
True: factors are described as continuous variables
False: factors are described as discrete variables.
The default is True.
Returns
-------
mig_score : TYPE
DESCRIPTION.
'''
# count the number of factors and latent codes
nb_factors = self.x.shape[1]
nb_codes = self.y.shape[1]
# quantize factors if they are continuous
if continuous_factors:
factors = minmax_scale(np.nan_to_num(self.x)) # normalize in [0, 1] all columns
factors = self.get_bin_index(self.x, self.nb_bins) # quantize values and get indexes
else:
factors = self.x
# quantize latent codes
if continuous_factors:
codes = minmax_scale(np.nan_to_num(self.y)) # normalize in [0, 1] all columns
codes = self.get_bin_index(self.y, self.nb_bins) # quantize values and get indexes
else:
codes = self.y
# compute mutual information matrix
mi_matrix = np.zeros((nb_factors, nb_codes))
for f in range(nb_factors):
for c in range(nb_codes):
mi_matrix[f, c] = self.get_mutual_information(factors[:, f], codes[:, c], normalize = False)
# compute the score for all codes
sum_score = 0
for c in range(nb_codes):
# find the index of the factor with the maximum MI
max_mi_idx = np.argmax(mi_matrix[:, c])
# compute numerator
numerator = 0
for f, mi_f in enumerate(mi_matrix[:, c]):
if f != max_mi_idx:
numerator += mi_f ** 2
# get the score for this code
s = 1 - numerator / (mi_matrix[max_mi_idx, c] ** 2 * (nb_factors - 1))
sum_score += s
# compute the mean gap
modularity_score = sum_score / nb_codes
return modularity_score
def jemmig(self, continuous_factors = True):
'''
@misc{jemmig,
title={Theory and Evaluation Metrics for Learning Disentangled Representations},
author={Kien Do and Truyen Tran},
year={2021},
}
paper: https://arxiv.org/pdf/1908.09961.pdf
Parameters
----------
continuous_factors : bool, optional
True: factors are described as continuous variables