/
disentanglement_gym.py
1803 lines (1686 loc) · 62.7 KB
/
disentanglement_gym.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 contextlib
import random
import warnings
from collections import OrderedDict, defaultdict
from inspect import ismethod
from typing import Dict, List, Optional, Tuple, Union, Sequence, Callable, Any, \
Iterator, Text
import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt
from six import string_types
from sklearn import metrics
from sklearn.mixture import GaussianMixture
from tensorflow_probability.python.distributions import Distribution, Normal, \
Bernoulli
from tqdm import tqdm
from typeguard import typechecked
from typing_extensions import Literal
from odin import visual as vs
from odin.backend import TensorType
from odin.bay.distributions import Batchwise, QuantizedLogistic, \
MixtureQuantizedLogistic
from odin.bay.vi._base import VariationalModel
from odin.bay.vi.autoencoder import VariationalAutoencoder
from odin.bay.vi.losses import total_correlation
from odin.bay.vi.metrics import (Correlation, beta_vae_score, dci_scores,
factor_vae_score, mutual_info_gap,
separated_attr_predictability,
correlation_matrix, mutual_info_estimate,
importance_matrix, relative_strength)
from odin.bay.vi.utils import discretizing
from odin.fuel import get_dataset, ImageDataset
from odin.ml import DimReduce, fast_kmeans
from odin.search import diagonal_linear_assignment
from odin.utils import as_tuple, uuid
__all__ = [
'GroundTruth',
'DisentanglementGym',
'Correlation',
'DimReduce',
'plot_latent_stats'
]
DataPartition = Literal['train', 'valid', 'test']
CorrelationMethod = Literal['spearman', 'pearson', 'lasso', 'mi', 'importance']
ConvertFunction = Callable[[List[Distribution]], tf.Tensor]
Axes = Union[None, plt.Axes, Sequence[int], int]
FactorFilter = Union[Callable[[Any], bool],
Dict[Union[str, int], int],
float, int, str,
None]
DatasetNames = Literal['shapes3d', 'shapes3dsmall', 'shapes3d0',
'dsprites', 'dspritessmall', 'dsprites0',
'celeba', 'celebasmall',
'fashionmnist', 'mnist',
'cifar10', 'cifar100', 'svhn',
'cortex', 'pbmc',
'halfmoons']
def _reshape2D(x: tf.Tensor) -> tf.Tensor:
if x.shape.rank == 1:
return x
return tf.reshape(x, (x.shape[0], -1))
def concat_mean(dists: List[Distribution]) -> tf.Tensor:
return tf.concat([_reshape2D(d.mean()) for d in dists], -1)
def first_mean(dists: List[Distribution]) -> tf.Tensor:
return _reshape2D(dists[0].mean())
# ===========================================================================
# Helpers
# ===========================================================================
_CACHE = defaultdict(dict)
def _dist(p: Union[Distribution, Sequence[Distribution]]
) -> Union[Sequence[Distribution], Distribution]:
"""Convert DeferredTensor back to original Distribution"""
if isinstance(p, (tuple, list)):
return [_dist(i) for i in p]
p: Distribution
return (p.parameters['distribution']
if 'deferred_tensor' in str(type(p)) else p)
def _save_image(arr, path):
from PIL import Image
if hasattr(arr, 'numpy'):
arr = arr.numpy()
im = Image.fromarray(arr)
im.save(path)
def _prepare_categorical(y: np.ndarray, ds: ImageDataset,
return_index: bool = False) -> np.ndarray:
"""Return categorical labels and factors-based label"""
if ds is None:
dsname = None
labels = None
else:
dsname = ds.name
labels = ds.labels
if hasattr(y, 'numpy'):
y = y.numpy()
if dsname is None: # unknown
y_categorical = tf.argmax(y, axis=-1)
names = np.array([f'#{i}' for i in range(y.shape[1])])
elif dsname in ('mnist', 'fashionmnist', 'cifar10', 'cifar100', 'cortex'):
y_categorical = tf.argmax(y, axis=-1)
names = labels
elif 'celeba' in dsname:
y_categorical = tf.argmax(y, axis=-1)
raise NotImplementedError
elif 'shapes3d' in dsname:
y_categorical = y[:, 2]
names = ['cube', 'cylinder', 'sphere', 'round']
elif 'shapes3d0' in dsname:
y_categorical = tf.argmax(y, -1)
names = ['cube', 'cylinder', 'sphere', 'round']
elif 'dsprites' in dsname:
y_categorical = y[:, 2]
names = ['square', 'ellipse', 'heart']
elif 'dsprites0' in dsname:
y_categorical = tf.argmax(y, -1)
names = ['square', 'ellipse', 'heart']
elif 'halfmoons' in dsname:
y_categorical = y[:, -1]
names = ['circle', 'square', 'triangle', 'pentagon']
elif 'pbmc' == dsname:
names = ['CD4', 'CD8', 'CD45RA', 'CD45RO']
y_probs = []
for x in [i for n in names for i, l in zip(y.T, labels) if n == l]:
x = x[:, np.newaxis]
gmm = GaussianMixture(n_components=2,
covariance_type='full',
n_init=2,
random_state=1)
gmm.fit(x)
y_probs.append(gmm.predict_proba(x)[:, np.argmax(gmm.means_.ravel())])
y_categorical = np.argmax(np.vstack(y_probs).T, axis=1)
else:
raise RuntimeError(f'No support for dataset: {dsname}')
if return_index:
return y_categorical
return np.asarray([names[int(i)] for i in y_categorical])
def _prepare_images(x, normalize=False):
"""if normalize=True, normalize the image to [0, 1], used for the
reconstructed or generated image, not the original one.
"""
x = np.asarray(x)
n_images = x.shape[0]
if normalize:
vmin = x.reshape((n_images, -1)).min(axis=1).reshape((n_images, 1, 1, 1))
vmax = x.reshape((n_images, -1)).max(axis=1).reshape((n_images, 1, 1, 1))
x = (x - vmin) / (vmax - vmin)
if x.shape[-1] == 1: # grayscale image
x = np.squeeze(x, -1)
else: # color image
x = np.transpose(x, (0, 3, 1, 2))
return x
def plot_latent_stats(mean,
stddev,
kld=None,
weights=None,
ax=None,
name='q(z|x)'):
# === 2. plotting
ax = vs.to_axis(ax)
l1 = ax.plot(mean,
label='mean',
linewidth=0.5,
marker='o',
markersize=3,
color='r',
alpha=0.5)
l2 = ax.plot(stddev,
label='stddev',
linewidth=0.5,
marker='^',
markersize=3,
color='g',
alpha=0.5)
# ax.set_ylim(-1.5, 1.5)
ax.tick_params(axis='y', colors='r')
ax.set_ylabel(f'{name} Mean', color='r')
ax.grid(True)
lines = l1 + l2
## plotting the weights
if kld is not None or weights is not None:
ax = ax.twinx()
if kld is not None:
lines += plt.plot(kld,
label='KL(q|p)',
linestyle='--',
color='y',
marker='s',
markersize=2.5,
linewidth=1.0,
alpha=0.5)
if weights is not None:
l3 = ax.plot(weights,
label='weights',
linewidth=1.0,
linestyle='--',
marker='s',
markersize=2.5,
color='b',
alpha=0.5)
ax.tick_params(axis='y', colors='b')
ax.grid(False)
ax.set_ylabel('L2-norm weights', color='b')
lines += l3
ax.legend(lines, [l.get_label() for l in lines], fontsize=8)
ax.grid(alpha=0.5)
return ax
def _boostrap_sampling(
model: VariationalModel,
inputs: List[np.ndarray],
groundtruth: 'GroundTruth',
n_samples: int,
batch_size: int,
verbose: bool,
seed: int,
):
assert inputs.shape[0] == groundtruth.shape[0], \
('Number of samples mismatch between inputs and ground-truth, '
f'{inputs.shape[0]} != {groundtruth.shape[0]}')
inputs = as_tuple(inputs)
Xs = [list() for _ in range(len(inputs))] # inputs
Zs = [] # latents
Os = [] # outputs
indices = []
n = 0
random_state = np.random.RandomState(seed=seed)
prog = tqdm(desc=f'Sampling', total=n_samples, disable=not verbose)
while n < n_samples:
batch = min(batch_size, n_samples - n, groundtruth.shape[0])
if verbose:
prog.update(batch)
# factors
_, ids = groundtruth.sample_factors(n_per_factor=batch,
return_indices=True,
seed=random_state.randint(0, 1e8))
indices.append(ids)
# inputs
inps = []
for xi, inp in zip(Xs, inputs):
if tf.is_tensor(inp):
inp = tf.gather(inp, indices=ids, axis=0)
else:
inp = inp[ids]
xi.append(inp)
inps.append(inp)
# latents representation
z = model.encode(inps[0] if len(inps) == 1 else inps, training=False)
o = tf.nest.flatten(as_tuple(model.decode(z, training=False)))
# post-process latents
z = as_tuple(z)
if len(z) == 1:
z = z[0]
Os.append(o)
Zs.append(z)
# update the counter
n += len(ids)
# end progress
prog.clear()
prog.close()
# aggregate all data
Xs = [np.concatenate(x, axis=0) for x in Xs]
if isinstance(Zs[0], Distribution):
Zs = Batchwise(Zs, name="Latents")
else:
Zs = Blockwise(
[
Batchwise(
[z[zi] for z in Zs],
name=f"Latents{zi}",
) for zi in range(len(Zs[0]))
],
name="Latents",
)
Os = [
Batchwise(
[j[i] for j in Os],
name=f"Output{i}",
) for i in range(len(Os[0]))
]
indices = np.concatenate(indices, axis=0)
groundtruth = groundtruth[indices]
return Xs, groundtruth, Zs, Os, indices
# ===========================================================================
# GroundTruth
# ===========================================================================
def _fast_samples_indices(known: np.ndarray, factors: np.ndarray):
outputs = [-1] * len(known)
for k_idx in range(len(known)):
for f_idx in range(len(factors)):
if np.array_equal(known[k_idx], factors[f_idx]):
if outputs[k_idx] < 0:
outputs[k_idx] = f_idx
elif bool(random.getrandbits(1)):
outputs[k_idx] = f_idx
return outputs
try:
# with numba: ~1.3 sec
# without numba: ~19.3 sec
# ~15 times faster
from numba import jit
_fast_samples_indices = jit(
_fast_samples_indices,
# target='cpu',
cache=False,
parallel=False,
nopython=True)
except ImportError:
pass
def _create_factor_filter(known: FactorFilter,
factor_names: List[str]
) -> Callable[[Any], bool]:
if callable(known):
return known
if known is None:
known = {}
if isinstance(known, dict):
known = {
factor_names.index(k) if isinstance(k, string_types) else int(k): v
for k, v in known.items()
}
return lambda x: all(x[k] == v for k, v in known.items())
else:
return lambda x: x == known
class GroundTruth:
"""Discrete factor for disentanglement analysis. If the factors is continuous,
the values are casted to `int64` For discretizing continuous factor
`odin.bay.vi.discretizing`
Parameters
----------
factors : [type]
`[num_samples, n_factors]`, an Integer array
factor_names : [type], optional
None or `[n_factors]`, list of name for each factor, by default None
categorical : Union[bool, List[bool]], optional
list of boolean indicate if the given factor is categorical values or
continuous values.
This gives significant meaning when trying to visualize
the factors, by default False.
Attributes
---------
factor_labels : list of array,
unique labels for each factor
factor_sizes : list of Integer,
number of factor for each factor
Reference
---------
Google research: https://github.com/google-research/disentanglement_lib
Raises
------
ValueError
factors must be a matrix
"""
def __init__(
self,
factors: Union[tf.Tensor, np.ndarray, tf.data.Dataset],
factor_names: Optional[Sequence[str]] = None,
categorical: Union[bool, List[bool]] = False,
n_bins: Optional[Union[int, List[int]]] = None,
strategy: Literal['uniform', 'quantile', 'kmeans', 'gmm'] = 'uniform',
):
if isinstance(factors, tf.data.Dataset):
factors = tf.stack([x for x in factors])
if tf.is_tensor(factors):
factors = factors.numpy()
factors = np.atleast_2d(factors)
if factors.ndim != 2:
raise ValueError("factors must be a matrix [n_observations, n_factor], "
f"but given shape:{factors.shape}")
# check factors is one-hot encoded
if np.all(np.sum(factors, axis=-1) == 1):
factors = np.argmax(factors, axis=1)[:, np.newaxis]
categorical = True
n_factors = factors.shape[1]
# discretizing
factors_original = np.array(factors)
n_bins = as_tuple(n_bins, N=n_factors)
strategy = as_tuple(strategy, N=n_factors, t=str)
for i, (b, s) in enumerate(zip(n_bins, strategy)):
if b is not None:
factors[:, i] = discretizing(factors[:, i][:, np.newaxis],
n_bins=b,
strategy=s).ravel()
factors = factors.astype(np.int64)
# factor_names
if factor_names is None:
factor_names = [f'F{i}' for i in range(n_factors)]
else:
factor_names = [str(i) for i in ([factor_names]
if not isinstance(factor_names,
(tuple, list,
np.ndarray))
else factor_names)]
assert len(factor_names) == n_factors, \
f'Given {n_factors} but only {len(factor_names)} names'
# store the attributes
self._discrete_factors = factors
self._original_factors = factors_original
self.discretizer = list(zip(n_bins, strategy))
self.categorical = as_tuple(categorical, N=n_factors, t=bool)
self.factor_names = factor_names
self.unique_values = [np.unique(x) for x in factors.T]
self.sizes = [len(lab) for lab in self.unique_values]
def is_categorical(self, factor_index: Union[int, str]) -> bool:
if isinstance(factor_index, string_types):
factor_index = self.factor_names.index(factor_index)
return self.categorical[factor_index]
def copy(self) -> 'GroundTruth':
obj = GroundTruth.__new__(GroundTruth)
obj._discrete_factors = self._discrete_factors
obj._original_factors = self._original_factors
obj.discretizer = self.discretizer
obj.categorical = self.categorical
obj.factor_names = self.factor_names
obj.unique_values = self.unique_values
obj.sizes = self.sizes
return obj
def __getitem__(self, key):
obj = self.copy()
obj._discrete_factors = obj._discrete_factors[key]
obj._original_factors = obj._original_factors[key]
return obj
@property
def original_factors(self) -> np.ndarray:
return self._original_factors
@property
def discretized_factors(self) -> np.ndarray:
return self._discrete_factors
@property
def shape(self) -> List[int]:
return self._discrete_factors.shape
@property
def dtype(self) -> np.dtype:
return self._discrete_factors.dtype
@property
def n_factors(self) -> int:
return self._discrete_factors.shape[1]
def sample_factors(
self,
factor_filter: FactorFilter = None,
n_per_factor: int = 16,
replace: bool = False,
seed: int = 1) -> Tuple[np.ndarray, np.ndarray]:
"""Sample a batch of factors with output shape `[num, num_factor]`.
Parameters
----------
factor_filter : A Dictionary, mapping from factor_names or factor_index to
factor_value, this establishes a list of known
factors to sample from the unknown factors.
n_per_factor : An Integer
number of samples per factor
replace : A Boolean
replacement sample
seed: int
random seed
Return
------
factors : `[num, n_factors]`
the samples
indices : list of Integer
the indices if sampled factors
"""
factor_filter = _create_factor_filter(factor_filter, self.factor_names)
# all samples with similar known factors
samples = [(idx, x[None, :])
for idx, x in enumerate(self._discrete_factors)
if factor_filter(x)]
rand = np.random.RandomState(seed)
indices = rand.choice(len(samples), size=int(n_per_factor),
replace=replace)
factors = np.vstack([samples[i][1] for i in indices])
return factors, np.array([samples[i][0] for i in indices])
def sample_indices_from_factors(self,
factors: np.ndarray,
seed: int = 1) -> np.ndarray:
"""Sample a batch of observations indices given a batch of factors.
In other words, the algorithm find all the samples with matching factor
in given batch, then return the indices of those samples.
Parameters
----------
factors : `[n_samples, n_factors]`
the factors
seed : None or `np.random.RandomState`
the random seed
Return
------
indices : list of Integer
indices
"""
random_state = np.random.RandomState(seed=seed)
random.seed(random_state.randint(1e8))
if factors.ndim == 1:
factors = np.expand_dims(factors, axis=0)
assert factors.ndim == 2, "Only support matrix as factors."
return np.array(_fast_samples_indices(factors, self._discrete_factors))
def __str__(self):
text = f'GroundTruth: {self._discrete_factors.shape}\n'
for i, (discretizer, name, labels) in enumerate(
zip(self.discretizer, self.factor_names, self.unique_values)):
ftype = 'categorical' if self.categorical[i] else 'continuous'
text += (f" Factor#{i} type:{ftype} n={len(labels)} "
f"name:'{name}' discretizer:{discretizer} "
f"values:[{','.join([str(i) for i in labels])}]\n")
return text[:-1]
# ===========================================================================
# Disentanglement Gym
# ===========================================================================
class DisentanglementGym(vs.Visualizer):
"""Disentanglement Gym
Parameters
----------
dataset : str
name of the dataset
model : VariationalAutoencoder
instance of `VariationalAutoencoder`
batch_size : int, optional
batch size, by default 64
seed : int, optional
seed for random state and reproducibility, by default 1
"""
@typechecked
def __init__(
self,
model: VariationalModel,
dataset: Union[None, ImageDataset, DatasetNames, Text] = None,
train: Optional[Any] = None,
valid: Optional[Any] = None,
test: Optional[Any] = None,
labels_name: Optional[Sequence[str]] = None,
batch_size: int = 32,
dpi: int = 200,
seed: int = 1):
self.seed = int(seed)
self.dpi = int(dpi)
self._batch_size = int(batch_size)
self.model = model
# === 1. prepare dataset
if isinstance(dataset, string_types):
self.ds = get_dataset(dataset)
self.dsname = str(dataset).lower().strip()
elif isinstance(dataset, ImageDataset):
self.ds = dataset
self.dsname = dataset.name
else:
self.ds = None
self.dsname = 'unknown'
if dataset is None:
self._labels_name = labels_name
self._data = dict(train=train, valid=valid, test=test)
else:
self._labels_name = self.ds.labels
kw = dict(batch_size=batch_size,
label_percent=True,
shuffle=1000,
seed=seed)
self._data = dict(
train=self.ds.create_dataset(partition='train', **kw),
valid=self.ds.create_dataset(partition='valid', **kw),
test=self.ds.create_dataset(partition='test', **kw),
)
# === 3. attributes
self._context_setup = False
self._x_true = None
self._y_true = None
self._groundtruth = None
self._px = None
self._qz = None
self._pz = None
self._cache_key = None
def _assert_sampled(self):
assert self._context_setup, 'Call method run_model to produce the samples'
@property
def is_semi_supervised(self) -> bool:
return self.model.is_semi_supervised()
@property
def is_hierarchical(self) -> bool:
return self.model.is_hierarchical()
@property
def labels_name(self) -> Sequence[str]:
return np.array([f'#{i} ' for i in range(self.y_true.shape[1])]) \
if self._labels_name is None else self._labels_name
@property
def x_true(self) -> np.ndarray:
self._assert_sampled()
return self._x_true
@property
def y_true(self) -> np.ndarray:
self._assert_sampled()
y = self._y_true
if self.dsname in ['shapes3d', 'shapes3dsmall']:
y = np.concatenate([
np.expand_dims(np.argmax(y[:, 0:15], -1), -1),
np.expand_dims(np.argmax(y[:, 15:23], -1), -1),
np.expand_dims(np.argmax(y[:, 23:27], -1), -1),
np.expand_dims(np.argmax(y[:, 27:37], -1), -1),
np.expand_dims(np.argmax(y[:, 37:47], -1), -1),
np.expand_dims(np.argmax(y[:, 47:57], -1), -1),
], -1)
elif self.dsname in ['dsprites', 'dspritessmall']:
y = np.concatenate([
np.expand_dims(np.argmax(y[:, 0:40], -1), -1),
np.expand_dims(np.argmax(y[:, 40:46], -1), -1),
np.expand_dims(np.argmax(y[:, 46:49], -1), -1),
np.expand_dims(np.argmax(y[:, 49:(49 + 32)], -1), -1),
np.expand_dims(np.argmax(y[:, (49 + 32):(49 + 64)], -1), -1),
], -1)
return y
@property
def y_true_original(self) -> np.ndarray:
return self._y_true
@property
def groundtruth(self) -> GroundTruth:
self._assert_sampled()
y_true = self.y_true
if self._groundtruth is None:
n_bins = None
factor_names = self.labels_name
if self.dsname in ['fashionmnist', 'mnist',
'cifar10', 'cifar100', 'svhn',
'cortex', 'pbmc',
'dsprites0', 'shapes3d0']:
categorical = True
factor_names = 'classes'
elif self.dsname in ['shapes3d', 'shapes3dsmall']:
categorical = [True, True, True, True, True, True]
n_bins = [15, 8, 4, 10, 10, 10]
elif self.dsname in ['dsprites', 'dspritessmall']:
categorical = [True, True, True, True, True]
n_bins = [40, 6, 3, 32, 32]
elif self.dsname == 'halfmoons':
categorical = [False, False, False, True]
n_bins = [10, 10, 10, 4]
else:
raise NotImplementedError
self._groundtruth = GroundTruth(y_true,
factor_names=factor_names,
categorical=categorical,
n_bins=n_bins,
strategy='uniform')
return self._groundtruth
@property
def px_z(self) -> List[Batchwise]:
"""reconstruction: p(x|z)"""
self._assert_sampled()
return list(self._px)
@property
def qz_x(self) -> List[Batchwise]:
"""latents posterior: q(z|x)"""
self._assert_sampled()
return list(self._qz)
@property
def pz(self) -> List[Batchwise]:
"""latents prior: p(z) or p(z_i|z_j)"""
self._assert_sampled()
return list(self._pz)
@property
def n_samples(self) -> int:
self._assert_sampled()
return self.x_true.shape[0]
@property
def latents_dim(self) -> int:
self._assert_sampled()
return int(sum(
np.prod((q.batch_shape + q.event_shape)[1:])
for q in self.qz_x))
@property
def factors_dim(self) -> int:
self._assert_sampled()
return self.y_true.shape[1]
@property
def n_latent_vars(self) -> int:
"""Number of latents variables (useful when having hierarchical latent
variables)"""
return len(self.qz_x)
def get_correlation_matrix(
self,
convert_fn: ConvertFunction = first_mean,
method: CorrelationMethod = 'spearman',
n_neighbors: int = 3,
n_cpu: int = 1,
sort_pairs: bool = False,
) -> np.ndarray:
"""Correlation matrix of `latent codes` (row) and `groundtruth factors`
(column).
Parameters
----------
convert_fn : Callable
convert list of Distribution to a Tensor
method : {'spearman', 'pearson', 'lasso', 'mi', 'importance'}
method for calculating the correlation,
'spearman': rank or monotonic correlation
'pearson': linear correlation
'lasso': lasso regression
'mi': mutual information
'importance': importance matrix estimated by GBTree
by default 'spearman'
n_neighbors : int
number of neighbors for estimating mutual information (only used for
method = 'mi')
n_cpu : int
number of cpu for calculation of mutual information or importance
matrix
sort_pairs : bool, optional
If True, reorganize the row of correlation matrix
for the best match between code-factor (i.e. the largest diagonal sum).
Note: the decoding is performed on train matrix, then applied to test
matrix, by default False
Returns
-------
ndarray
correlation matrices `[n_latents, n_factors]`, all entries are in `[0, 1]`.
OrderedDict (optional)
mapping from best matched: factor index to latent code index.
"""
z = convert_fn(self.qz_x).numpy()
f = self.y_true
cache_key = f'{self._cache_key}_{id(convert_fn)}'
if method in ('spearman', 'pearson', 'lasso'):
mat = correlation_matrix(x1=z,
x2=f,
method=method,
cache_key=cache_key,
seed=self.seed)
elif method == 'mi':
mat = mutual_info_estimate(representations=z,
factors=f,
continuous_latents=True,
continuous_factors=False,
n_neighbors=n_neighbors,
n_cpu=n_cpu,
cache_key=cache_key,
seed=self.seed)
elif method == 'importance':
mat = importance_matrix(repr_train=z,
factor_train=f,
test_size=0.4,
seed=self.seed,
cache_key=cache_key,
n_jobs=1)[0]
else:
raise ValueError(f'No support for correlation method: {method}')
## decoding and return
if sort_pairs:
ids = diagonal_linear_assignment(mat)
mat = mat[ids, :]
return mat, OrderedDict(zip(range(self.factors_dim), ids))
return mat
@contextlib.contextmanager
def run_model(self,
*,
n_samples: int = -1,
partition: DataPartition = 'test',
device: Literal['gpu', 'cpu'] = 'cpu',
gpu_id: int = 0,
verbose: bool = True) -> 'DisentanglementGym':
# === 0. setup
tf.random.set_seed(self.seed)
self._context_setup = True
self._cache_key = uuid(12)
# === 1. prepare data
ds = self._data[partition]
if ds is None:
raise ValueError(f'No dataset for partition {partition}')
if not isinstance(ds, tf.data.Dataset):
if isinstance(ds, TensorType):
ds = tf.data.Dataset.from_tensor_slices(ds)
elif isinstance(ds, (tuple, list)):
ds = tf.data.Dataset.zip(tuple([tf.data.Dataset.from_tensor_slices(i)
for i in ds]))
else:
raise ValueError(f'No support for dataset type: {type(ds)}')
if n_samples > 0:
ds = ds.take(int(np.ceil(n_samples / self._batch_size)))
structure = tf.data.experimental.get_structure(ds)
assert len(structure) == 2, \
f'Dataset must return inputs and target, but given: {structure}'
progress = tqdm(ds,
desc=f"{self.model.name}-{self.dsname}",
disable=not verbose)
# === 2. running
x_true = []
y_true = []
P_xs = []
Q_zs = []
P_zs = []
with tf.device("/CPU:0" if device == 'cpu' else f"/GPU:{gpu_id}"):
for x, y in progress:
P, Q = self.model(x, training=False)
Q, Q_prior = self.model.get_latents(return_prior=True)
P = as_tuple(P)
Q = as_tuple(Q)
Q_prior = as_tuple(Q_prior)
x_true.append(x)
y_true.append(y)
P_xs.append(_dist(P))
Q_zs.append(_dist(Q))
P_zs.append(_dist(Q_prior))
# for the reconstruction
n_reconstruction = len(P_xs[0])
all_px = [Batchwise([x[i] for x in P_xs]) for i in range(n_reconstruction)]
# latents
n_latents = len(Q_zs[0])
all_qz = [Batchwise([z[i] for z in Q_zs]) for i in range(n_latents)]
all_pz = []
for i in range(n_latents):
p = [z[i] for z in P_zs]
if all(qz.batch_shape == pz.batch_shape
for qz, pz in zip(all_qz[i].distributions, p)):
p = Batchwise(p)
else:
p = p[0]
all_pz.append(p)
# assign prior attribute to qz
for q, p in zip(all_qz, all_qz):
q.prior = p
# labels
x_true = tf.concat(x_true, axis=0).numpy()
y_true = tf.concat(y_true, axis=0).numpy()
# === 3. save attributes
self._px = all_px
self._qz = all_qz
self._pz = all_pz
self._x_true = x_true
self._y_true = y_true
try:
import seaborn
seaborn.set()
except ImportError:
plt.rc('axes', axisbelow=True)
yield self
self._context_setup = False
def plot_reconstruction(self,
n_images: int = 36,
title: str = '') -> plt.Figure:
self._assert_sampled()
rand = np.random.RandomState(self.seed)
n_rows = int(np.sqrt(n_images))
ids = rand.permutation(self.n_samples)[:n_images]
org = _prepare_images(self.x_true[ids])
rec = _prepare_images(self.px_z[0].mean().numpy()[ids], normalize=True)
fig = plt.figure(figsize=(12, 7), dpi=self.dpi)
vs.plot_images(org, images_per_row=n_rows, ax=(1, 2, 1),
title=f'{title} Original')
vs.plot_images(rec, images_per_row=n_rows, ax=(1, 2, 2),
title=f'{title} Reconstructed '
f'(llk:{self.log_likelihood()[0]:.2f})')
plt.tight_layout()
self.add_figure(f'reconstruction{title}', fig)
return fig
def plot_distortion(self, title: str = '') -> plt.Figure:
with tf.device('/CPU:0'):
start = 0
llk = []
for px in self.px_z[0].distributions:
x = self.x_true[start: start + px.batch_shape[0]]
start += px.batch_shape[0]
if hasattr(px, 'distribution'):
px = px.distribution
if isinstance(px, Bernoulli):
px = Bernoulli(logits=px.logits)
elif isinstance(px, Normal):
px = Normal(loc=px.loc, scale=px.scale)
elif isinstance(px, QuantizedLogistic):
px = QuantizedLogistic(loc=px.loc, scale=px.scale,
low=px.low, high=px.high,
inputs_domain=px.inputs_domain,
reinterpreted_batch_ndims=None)
elif isinstance(px, MixtureQuantizedLogistic):
raise NotImplementedError
else:
raise NotImplementedError
llk.append(px.log_prob(x))
# aggregate and statistics
llk = -np.concatenate(llk, 0)
mean = np.mean(llk, 0)
mean_lims = (np.min(mean), np.max(mean))
std = np.std(llk, 0)
std_lims = (np.min(std), np.max(std))
n_channels = llk.shape[-1]
# helper
def ax_config(im, ax, lims):
ax.axis('off')
ax.margins(0)
ax.grid(False)
ticks = np.linspace(lims[0], lims[1], num=5)
cbar = plt.colorbar(im, ax=ax, fraction=0.04, pad=0.02, ticks=ticks)
cbar.ax.set_yticklabels([f'{i:.2f}' for i in ticks])
cbar.ax.tick_params(labelsize=6, length=2, width=0.5)
# plotting
fig = plt.figure(figsize=(2 * 2, n_channels * 2), dpi=self.dpi)
idx = 1
for i in range(n_channels):
# mean
ax = plt.subplot(n_channels, 2, idx)
im = ax.pcolormesh(mean[:, :, i], cmap='Spectral',
vmin=mean_lims[0], vmax=mean_lims[1],
linewidth=0, rasterized=True)
ax.set_title(rf'$\mu$', fontsize=6)
ax_config(im, ax, mean_lims)
ax.set_ylabel(f'Channel{i}')
idx += 1
# std
ax = plt.subplot(n_channels, 2, idx)
im = ax.pcolormesh(std[:, :, i], cmap='Spectral',
vmin=std_lims[0], vmax=std_lims[1],
linewidth=0, rasterized=True)
ax.set_title(rf'$\sigma$', fontsize=6)
ax_config(im, ax, std_lims)
idx += 1
plt.tight_layout()
self.add_figure(f'distortion{title}', fig)
return fig
def plot_latents_stats(self,
latent_idx: int = 0,
title: str = '') -> plt.Figure:
from odin.bay import Vamprior
self._assert_sampled()
rand = np.random.RandomState(seed=self.seed)
# === 0. prepare the latents
qz = self.qz_x[latent_idx]
pz = self.pz[latent_idx]
mean = np.mean(_reshape2D(qz.mean()), 0)