-
Notifications
You must be signed in to change notification settings - Fork 11
/
gmm_tmat.py
2092 lines (1983 loc) · 75.2 KB
/
gmm_tmat.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
# -*- coding: utf-8 -*-
""""
This module contains tools for Gaussian mixture modeling (GMM)
__author__ = 'Omid Sadjadi, Timothee Kheyrkhah'
__email__ = '[email protected]'
Modification and GPU-implementation by TrungNT
"""
import os
import pickle
import random
import threading
import time
from collections import Mapping, OrderedDict, defaultdict
import numpy as np
import tensorflow as tf
from scipy import linalg
from six import string_types
from odin import backend as K
from bigarray import MmapArray
from odin.ml.base import BaseEstimator, DensityMixin, TransformerMixin
from odin.utils import (MPI, Progbar, array_size, as_tuple, minibatch, cpu_count,
ctext, defaultdictkey, eprint, is_number, segment_list,
uuid, wprint)
EPS = 1e-6
# minimum batch size that will be optimal to transfer
# the data to GPU for calculation (tested on Titan X)
# NOTE: tensorflow has a lagging effect, it will be
# slower than numpy if you evaluate the
# expression for first time.
MINIMUM_GPU_BLOCK = 8000 * 120 * 4 # bytes
# ===========================================================================
# Helper
# ===========================================================================
def zeroStat(post):
""" Shape: (1, nmix)
# sum over all samples
# Zero-order statistics over all samples and dimension for
each components
"""
# ====== tensorflow tensor or variable ====== #
if K.is_tensor(post, inc_distribution=True, inc_variable=True):
y = tf.reduce_sum(post, axis=0, keepdims=True,
name="zero_stat")
# ====== numpy array ====== #
else:
y = np.sum(post, axis=0, keepdims=True) # (1, M)
return y
def firstStat(X, post):
""" Shape: (feat_dim, nmix)
First-order statistics over all samples for each components
"""
# ====== tensorflow tensor or variable ====== #
if K.is_tensor(X, inc_distribution=True, inc_variable=True):
y = tf.matmul(tf.transpose(X), post, name='first_stat')
# ====== numpy array ====== #
else:
y = np.dot(X.T, post)
return y
def secondStat(X, post):
""" Shape: (feat_dim, nmix)
Second-order statistics over all samples for each components
"""
# ====== tensorflow tensor or variable ====== #
if K.is_tensor(X, inc_distribution=True, inc_variable=True):
y = tf.matmul(tf.transpose(tf.pow(X, 2)), post, name="second_stat")
# ====== numpy array ====== #
else:
y = np.dot((X ** 2).T, post)
return y
def logsumexp(X, axis):
"""
Compute log(sum(exp(x),dim)) while avoiding numerical underflow
"""
# ====== tensorflow tensor or variable ====== #
if K.is_tensor(X, inc_distribution=True, inc_variable=True):
xmax = tf.reduce_max(X, axis=axis, keepdims=True)
y = tf.add_n(inputs=[
xmax,
tf.log(tf.reduce_sum(input_tensor=tf.exp(X - xmax),
axis=axis,
keepdims=True))],
name='llk')
# ====== numpy array ====== #
else:
xmax = np.max(X, axis=axis, keepdims=True)
y = xmax + np.log(np.sum(a=np.exp(X - xmax),
axis=axis,
keepdims=True))
return y
def _split_jobs(n_samples, ncpu, device, gpu_factor):
""" Return: jobs_cpu, jobs_gpu"""
# number of GPU
# TODO: fix `get_ngpu` here
ngpu = get_ngpu()
if ngpu == 0:
device = 'cpu'
# jobs split based on both number of CPU and GPU
if device == 'mix':
njob = ncpu + 1 + ngpu * gpu_factor
elif device == 'cpu':
njob = ncpu + 1
elif device == 'gpu':
njob = ngpu + 1
else:
raise ValueError("Unknown device: '%s'" % device)
jobs = np.linspace(start=0, stop=n_samples,
num=njob, dtype='int32')
jobs = list(zip(jobs, jobs[1:]))
# use both GPU and CPU
if device == 'mix':
jobs_gpu = [(jobs[i * gpu_factor][0],
jobs[i * gpu_factor + gpu_factor - 1][1])
for i in range(ngpu)]
jobs_cpu = [jobs[i] for i in range(ngpu * gpu_factor, len(jobs))]
elif device == 'gpu': # only GPU
jobs_gpu = jobs
jobs_cpu = []
elif device == 'cpu': # only CPU
jobs_gpu = []
jobs_cpu = jobs
return jobs_cpu, jobs_gpu
def _create_batch(X, sad, start, end, batch_size,
downsample, stochastic,
seed, curr_nmix, curr_niter):
"""
Return
------
(X, n_selected_frame, n_original_frame)
i.e. the number of select frames might be different from number
of original frames after applying SAD
"""
# stochastic downsample, seed change every iter and mixup
if stochastic:
random.seed(seed + curr_nmix + curr_niter)
else: # deterministic
random.seed(seed)
all_batches = list(minibatch(n=end - start, batch_size=batch_size))
random.shuffle(all_batches)
# iterate over batches
for batch_id, (batch_start, batch_end) in enumerate(all_batches):
batch_start += start
batch_end += start
n_original_sample = batch_end - batch_start
# first batch always selected,
# downsample by randomly ignore a batch
if batch_id == 0 or \
downsample == 1 or \
(downsample > 1 and random.random() <= 1. / downsample):
X_sad = (X[batch_start:batch_end]
if sad is None else
X[batch_start:batch_end][sad[batch_start:batch_end].astype('bool')])
yield X_sad, X_sad.shape[0], n_original_sample
# ====== batch ignored ====== #
else:
yield None, n_original_sample, n_original_sample
def _create_batch_indices(X, sad, indices, batch_size,
downsample, stochastic,
seed, curr_nmix, curr_niter):
"""
Return
------
(X, n_selected_frame, n_original_frame)
i.e. the number of select frames might be different from number
of original frames after applying SAD
"""
# stochastic downsample, seed change every iter and mixup
if stochastic:
random.seed(seed + curr_nmix + curr_niter)
else: # deterministic
random.seed(seed)
random.shuffle(indices)
# ====== prepare the buffer ====== #
X_buffer = []
n_original_buffer = 0
n_selected_buffer = 0
# ====== iterate over each file ====== #
for batch_id, (name, (file_start, file_end)) in enumerate(indices):
n_original_sample = file_end - file_start
# first batch always selected,
# downsample by randomly ignore a batch
if batch_id == 0 or \
downsample == 1 or \
(downsample > 1 and random.random() <= 1. / downsample):
# not enough sample for batching
if n_original_sample <= batch_size:
X_sad = (X[file_start:file_end]
if sad is None else
X[file_start:file_end][sad[file_start:file_end].astype('bool')])
# store in buffer
X_buffer.append(X_sad)
n_selected_buffer += X_sad.shape[0]
n_original_buffer += n_original_sample
# split into smaller mini-batch
else:
for batch_start, batch_end in minibatch(n=n_original_sample, batch_size=batch_size):
batch_start = batch_start + file_start
batch_end = batch_end + file_start
X_sad = (X[batch_start: batch_end]
if sad is None else
X[batch_start: batch_end][sad[batch_start: batch_end].astype('bool')])
if X_sad.shape[0] >= batch_size: # full batch
yield X_sad, X_sad.shape[0], n_original_sample
else: # store in buffer
X_buffer.append(X_sad)
n_selected_buffer += X_sad.shape[0]
n_original_buffer += n_original_sample
# ====== batch ignored ====== #
else:
yield None, n_original_sample, n_original_sample
# ====== check buffer to return ====== #
if n_selected_buffer >= batch_size:
yield np.concatenate(X_buffer, axis=0), n_selected_buffer, n_original_buffer
X_buffer = []
n_selected_buffer = 0
n_original_buffer = 0
# ====== check final buffer to return ====== #
if len(X_buffer) > 0:
yield np.concatenate(X_buffer, axis=0), n_selected_buffer, n_original_buffer
class _ExpectationResults(object):
""" ExpectationResult """
def __init__(self, n_samples, nb_results, name, print_progress):
super(_ExpectationResults, self).__init__()
# thread lock
self.lock = threading.Lock()
# progress bar
self.prog = Progbar(target=n_samples, print_report=True,
print_summary=False, name=name)
# GMM: Z, F, S, L, nframes
# I-vector: LU, RU, llk, nframes
self.stats = [0. for i in range(int(nb_results))]
self.print_progress = bool(print_progress)
def update(self, res):
"""
integer (or a number): number of processed samples (update the progress bar)
otherwise: list of results (update the statistics)
"""
# thread-safe udpate
self.lock.acquire()
try:
# returned number of processed samples
if is_number(res) and self.print_progress:
self.prog.add(res)
# return the statistics, end of process
else:
for i, r in enumerate(res):
self.stats[i] += r
finally:
self.lock.release()
# ===========================================================================
# Main GMM
# ===========================================================================
class GMM(DensityMixin, BaseEstimator, TransformerMixin):
r""" Gaussian Mixture Model with diagonal covariance.
Parameters
----------
nmix : int
number of mixtures
nmix_start : int
the algorithm start from given number of mixture, then perform
E-M and split to increase the mixtures to desire number
niter : int (default: 16)
number of iteration for E-M algorithm
dtype : {str, numpy.dtype} (default: float32)
desire dtype for mean, std, weights and input matrices
It is recommended to keep 'float32', since this speed up
a lot on GPU
allow_rollback : bool (default: True)
If True, reset the `mean`, `sigma` and `w` to the last
stable iteration, when `sigma` values smaller than 0
exit_on_error : bool (default: True)
Stop fitting when EM reach singular value and `sigma` become
numerical instabable (i.e. its values are smaller than 0)
batch_size : {int, 'auto'}
if 'auto', used `12 Megabytes` block for CPU batch and
`25 Megabytes` block for GPU batch
device : {'cpu', 'gpu', 'mix'}
'gpu' - run the computaiton on GPU
'cpu' - use multiprocessing for multiple cores
'mix' - use both GPU and multi-processing
* It is suggested to use mix of GPU and CPU if you have
more than 24 cores CPU, otherwise, 'gpu' gives the best
performance
ncpu : int
number of processes for parallel calculating Expectation
gpu_factor : int
how much jobs GPU will handle more than CPU
(i.e. `njob_gpu = gpu_factor * njob_cpu`)
stochastic_downsample : bool
if True, a subset of data is selected differently after
each iteration => the training is stochastic.
if False, a deterministic selection of data is performed
each iteration => the training is deterministic.
seed : int
random seed for reproducible
path : {str, None}
If given a path, save the model after everytime its
parameters changed (i.e. `maximization` or `gmm_mixup`
are called)
name : {str, None}
special name for this `Tmatrix` instance
Attributes
----------
mu : (feat_dim, nmix)
mean vector for each component
sigma : (feat_dim, nmix)
standard deviation for each component
w : (1, nmix)
weights of each component
Note
----
Memory throughput is the bottleneck in most of the case,
try to move the data to faster storage before fitting.
"""
STANDARD_CPU_BATCH_SIZE = 12 * 1024 * 1024 # 12 Megabytes
STANDARD_GPU_BATCH_SIZE = 25 * 1024 * 1024 # 25 Megabytes
def __init__(self, nmix, nmix_start=1, niter=16, dtype='float32',
allow_rollback=True, exit_on_error=False,
batch_size_cpu='auto', batch_size_gpu='auto',
downsample=1, stochastic_downsample=True,
device='cpu', ncpu=1, gpu_factor=80,
seed=1234, path=None, name=None):
super(GMM, self).__init__()
self._path = path if isinstance(path, string_types) else None
# ====== set number of mixtures ====== #
# start from 1 mixture, then split and up
nmix = int(nmix)
if nmix < 1:
raise ValueError("Number of Mixture must be greater than 1.")
self._nmix = nmix
self._curr_nmix = np.clip(int(nmix_start), 1, self._nmix)
# others dimension
self._feat_dim = None
self._niter = int(niter)
self.batch_size_cpu = batch_size_cpu
self.batch_size_gpu = batch_size_gpu
# ====== downsample ====== #
self.downsample = int(downsample)
self.stochastic_downsample = bool(stochastic_downsample)
self._seed = int(seed)
# ====== multi-processing ====== #
self.gpu_factor = int(gpu_factor)
# cpu
if ncpu is None:
ncpu = cpu_count() - 1
self.ncpu = int(ncpu)
# device
self.set_device(device)
# ====== state variable ====== #
# store history of {nmix -> [llk_1, llk_2] ...}
self._llk_hist = defaultdict(list)
# ====== error handling ====== #
self.allow_rollback = bool(allow_rollback)
self.exit_on_error = bool(exit_on_error)
self._stop_fitting = False
# ====== name ====== #
self._dtype = np.dtype(dtype)
if name is None:
name = uuid(length=8)
self._name = 'GMM_%s' % name
else:
self._name = str(name)
def __getstate__(self):
# 'means', 'variances', 'weights'
# self.mean, self.sigma, self.w
if not self.is_initialized:
raise RuntimeError("GMM hasn't been initialized, nothing to save")
return (self.mean, self.sigma, self.w,
self.allow_rollback, self.exit_on_error,
self._nmix, self._curr_nmix, self._feat_dim,
self._niter, self.batch_size_cpu, self.batch_size_gpu,
self.downsample, self.stochastic_downsample,
self._seed, self._llk_hist,
self.ncpu, self._device, self.gpu_factor,
self._dtype, self._path, self._name)
def __setstate__(self, states):
(self.mean, self.sigma, self.w,
self.allow_rollback, self.exit_on_error,
self._nmix, self._curr_nmix, self._feat_dim,
self._niter, self.batch_size_cpu, self.batch_size_gpu,
self.downsample, self.stochastic_downsample,
self._seed, self._llk_hist,
self.ncpu, self._device, self.gpu_factor,
self._dtype, self._path, self._name) = states
# basic constants
self._stop_fitting = False
self._feat_const = self.feat_dim * np.log(2 * np.pi)
self.X_ = tf.placeholder(shape=(None, self.feat_dim),
dtype=self.dtype,
name='GMM_input')
# init posterior
self._resfresh_cpu_posterior()
self._refresh_gpu_posterior()
# ====== warning no GPU ====== #
if self._device in ('gpu', 'mix') and get_ngpu() == 0:
wprint("Enabled GPU device, but no GPU found!")
def __str__(self):
if not self.is_initialized:
return '<"%s" nmix:%d initialized:False>' % (self.name, self._nmix)
s = '<"%s" nmix:%s ndim:%s mean:%s std:%s w:%s CPU:%s GPU:%s>' %\
(ctext(self.name, 'yellow'),
ctext(self._nmix, 'cyan'),
ctext(self._feat_dim, 'cyan'),
ctext(self.mean.shape, 'cyan'),
ctext(self.sigma.shape, 'cyan'),
ctext(self.w.shape, 'cyan'),
ctext(self.batch_size_cpu, 'cyan'),
ctext(self.batch_size_gpu, 'cyan'),
)
return s
# ==================== properties ==================== #
def set_device(self, device):
device = str(device).lower()
if device not in ('cpu', 'gpu', 'mix'):
raise ValueError("`device` must be one of the following: 'cpu', 'gpu', or 'mix'")
# ====== warning no GPU ====== #
if device in ('gpu', 'mix') and get_ngpu() == 0:
wprint("Using GPU device but NO GPU detected, "
"tensorflow will switch to slower CPU computation!")
self._device = device
return self
@property
def device(self):
return self._device
@property
def path(self):
return self._path
@property
def name(self):
return self._name
@property
def is_initialized(self):
return self._feat_dim is not None
@property
def is_fitted(self):
return self._curr_nmix == self._nmix
@property
def nmix(self):
return self._nmix
@property
def feat_dim(self):
if not self.is_initialized:
raise RuntimeError("GMM has not been initialized on data.")
return self._feat_dim
@property
def history(self):
""" Return the history of fitting this GMM in following format:
`[(current_nmix, current_niter, llk), ...]`
"""
return tuple(self._llk_hist)
@property
def dtype(self):
return self._dtype
# ==================== initialization ==================== #
def _resfresh_cpu_posterior(self):
""" Refresh cached value for CPu computations. """
expressions = {}
precision = 1 / (self.sigma + EPS)
C = np.sum((self.mean ** 2) * precision, axis=0, keepdims=True) + \
np.sum(np.log(self.sigma + EPS), axis=0, keepdims=True) - \
2 * np.log(self.w + EPS) # TODO: check here if add EPS to self.w
mu_precision = self.mean * precision
expressions['precision'] = precision
expressions['mu_precision'] = mu_precision
expressions['C'] = C
self.__expressions_cpu = expressions
def _refresh_gpu_posterior(self):
""" Call this function when you update the mixture
components.
Unlike CPU computation, tensorflow graph on need to
renew it placeholder which represent: mu, sigma, weight
when GMM mixup.
"""
expressions = {}
# ====== proper scope ====== #
if self._curr_nmix < self.nmix:
scope = self.name + str(self._curr_nmix)
else:
scope = self.name
# ====== build the graph ====== #
with tf.variable_scope(scope):
mu = tf.placeholder(shape=(self.feat_dim, self._curr_nmix),
dtype=self.dtype,
name='GMM_mu')
sigma = tf.placeholder(shape=(self.feat_dim, self._curr_nmix),
dtype=self.dtype,
name='GMM_sigma')
w = tf.placeholder(shape=(1, self._curr_nmix),
dtype=self.dtype,
name='GMM_weight')
expressions['mu'] = mu
expressions['sigma'] = sigma
expressions['w'] = w
# ====== log probability ====== #
# (feat_dim, nmix)
precision = 1 / (sigma + EPS)
C = tf.reduce_sum((mu ** 2) * precision,
axis=0, keepdims=True) + \
tf.reduce_sum(tf.log(sigma + EPS),
axis=0, keepdims=True) - \
2 * tf.log(w)
D = tf.matmul(self.X_ ** 2, precision) - \
2 * tf.matmul(self.X_, mu * precision) + \
self.feat_dim * np.log(2 * np.pi)
# (batch_size, nmix)
logprob = tf.multiply(x=tf.constant(-0.5, dtype=self.dtype),
y=C + D,
name='logprob')
expressions['logprob'] = logprob # (batch_size, nmix)
# ====== posterior and likelihood ====== #
llk = logsumexp(logprob, axis=1) # (batch_size, 1)
post = tf.exp(logprob - llk, name='postprob') # (batch_size, nmix)
expressions['llk'] = llk
expressions['post'] = post
# ====== expectation ====== #
expressions['zero'] = zeroStat(post)
expressions['first'] = firstStat(self.X_, post)
expressions['second'] = secondStat(self.X_, post)
expressions['L'] = tf.reduce_sum(llk, axis=None, name='sum_llk')
self.__expressions_gpu = expressions
def initialize(self, X):
indices = None
if isinstance(X, (tuple, list)):
tmp = [i for i in X if hasattr(i, 'shape')][0]
indices = [i for i in X if i != tmp][0]
X = tmp
# ====== check X ====== #
if not isinstance(X, np.ndarray):
raise ValueError("`X` must be numpy.ndarray")
# ====== check indices ====== #
if isinstance(indices, Mapping):
indices = list(indices.items())
elif not isinstance(indices, (tuple, list, np.ndarray, type(None))):
raise ValueError("`indices` must be None, Mapping, tuple, list or numpy.ndarray")
# ====== get input info ====== #
if hasattr(X, 'ndim'):
ndim = X.ndim
elif hasattr(X, 'get_shape'):
ndim = len(X.shape.as_list())
else:
raise ValueError("Cannot number of dimension from input.")
if hasattr(X, 'shape'):
feat_dim = X.shape[1]
elif hasattr(X, 'get_shape'):
feat_dim = X.shape.as_list()[1]
else:
raise ValueError("Cannot get feature dimension from input.")
# ====== already init ====== #
if self.is_initialized:
# validate the inputs
if ndim != 2 or feat_dim != self._feat_dim:
raise RuntimeError("Input must be 2-D matrix with the 1st "
"dimension equal to: %d" % feat_dim)
return X, indices
# ====== create input placeholder ====== #
self._feat_dim = int(feat_dim)
# const for specific dimension
self._feat_const = self.feat_dim * np.log(2 * np.pi)
# infer batch_size
if isinstance(self.batch_size_cpu, string_types):
self.batch_size_cpu = int(GMM.STANDARD_CPU_BATCH_SIZE /
(self.feat_dim * self.dtype.itemsize))
if isinstance(self.batch_size_gpu, string_types):
self.batch_size_gpu = int(GMM.STANDARD_GPU_BATCH_SIZE /
(self.feat_dim * self.dtype.itemsize))
# [batch_size, feat_dim]
self.X_ = tf.placeholder(shape=(None, self.feat_dim),
dtype=self.dtype,
name='GMM_input')
# ====== init ====== #
# (D, M)
self.mean = np.zeros((feat_dim, self._curr_nmix), dtype=self._dtype)
# (D, M)
self.sigma = np.ones((feat_dim, self._curr_nmix), dtype=self._dtype)
# (1, M)
self.w = np.ones((1, self._curr_nmix), dtype=self._dtype)
# init posterior
self._resfresh_cpu_posterior()
self._refresh_gpu_posterior()
return X, indices
# ==================== sklearn ==================== #
def fit(self, X, y=None):
"""
Parameters
----------
X : {numpy.ndarray, tuple, list}
in case a tuple is given, two options are considered:
- length of the list is 1: only training feature is given
- length of the list is 2: training data (numpy.ndarray),
indices or sad indices (numpy.ndarray)
- length of the list is 3: training data (numpy.ndarray),
sad indices (numpy.ndarray), indices
where the `indices` is a dictionary of the mapping
'file_name' -> (start_index, end_index) in the training
data array
NOTE
----
from 1, 2, 4 components, python multi-threading is fastest
from 8, 16 components, python multi-processing is fastest
from > 32 components, GPU scales much much better.
"""
# if indices is given it should be sorted for optimal
# memory access
if not isinstance(X, (tuple, list)):
X = (X,)
sad = None
indices = None
if len(X) == 1:
data = X[0]
elif len(X) == 2:
if hasattr(X[1], 'shape') and X[0].shape[0] == X[1].shape[0]:
data, sad = X
else:
data, indices = X
elif len(X) == 3:
data, sad, indices = X
else:
raise ValueError("No support for `X` in type of list with length: %d" % len(X))
# validate data
assert hasattr(data, 'shape') and data.ndim == 2, \
'Input data must be instance of 2-D ndarray but give: %s' % str(type(data))
# check if indices exist
if indices is not None:
if isinstance(indices, Mapping):
indices = list(indices.items())
indices = sorted(indices, key=lambda x: x[1][0])
X = (data, indices)
# otherwise, only data and sad are given
else:
X = data
# ====== start GMM ====== #
# supports 16384 components, modify for more components
niter = [1, 2, 4, 4, 4, 4, 6, 6, 10, 10, 10, 10, 10, 16, 16]
niter[int(np.log2(self._nmix))] = self._niter
self._stop_fitting = False
# run the algorithm
while True:
# fitting the mixtures
curr_nmix = self._curr_nmix
last_niter = len(self._llk_hist[curr_nmix])
idx = int(np.log2(curr_nmix))
curr_niter = niter[idx] - last_niter
if curr_niter > 0:
for i in range(curr_niter):
self.expectation_maximization(X, sad=sad, print_progress=True)
# check if stop now
if self._stop_fitting:
return self
print('---')
# update the mixtures
if curr_nmix < self._nmix:
self.gmm_mixup()
else:
break
return self
def score(self, X, y=None):
""" Compute the log-likelihood of each example to
the Mixture of Components.
"""
post = self.logprob(X) # (batch_size, nmix)
return logsumexp(post, axis=1) # (batch_size, 1)
def transform(self, X, zero=True, first=True, device=None):
""" Compute centered statistics given X and fitted mixtures
Parameters
----------
X : ndarray
input feature [n_samples, feat_dim] (e.g. all frames
of an utterance for audio data)
zero : bool (default: True)
if True, return the zero-th order statistics
first : bool (default: True)
if True, return the first order statistics
device : {None, 'cpu', 'gpu'}
select device for execute the expectation calculation
Return
------
zero-th statistics: [1, nmix]
e.g. the assignment score each samples to each components, hence,
`#frames = Z.sum()`
first statistics: [1, feat_dim * nmix]
dot-product of each sample and the posteriors.
NOTE
----
For more option check `GMM.expectation`
"""
if device is None:
device = self._device
zero = bool(zero)
first = bool(first)
if not zero and not first:
raise ValueError("One of `zero` or `first` must be True")
assert X.ndim == 2 and X.shape[1] == self.feat_dim, \
"`X` must be 2-D matrix, with `X.shape[1]=%d`; but given: %s" % \
(self.feat_dim, str(X.shape))
# ====== expectation ====== #
Z = None
F = None; F_hat = None
results = self._fast_expectation(X, zero=zero, first=first,
second=False, llk=False,
on_gpu=device != 'cpu')
# ====== return the results ====== #
if zero and first:
Z, F = results
# this equal to: .ravel()[np.newaxis, :]
F_hat = np.reshape(F - self.mean * Z,
newshape=(1, self.feat_dim * self._curr_nmix),
order='F')
return Z, F_hat
elif zero and not first:
Z = results
return Z
elif not zero and first:
F = results
# this equal to: .ravel()[np.newaxis, :]
F_hat = np.reshape(F - self.mean * Z,
newshape=(1, self.feat_dim * self._curr_nmix),
order='F')
return F_hat
def transform_to_disk(self, X, indices, sad=None,
pathZ=None, pathF=None, name_path=None,
dtype='float32', device='cpu', ncpu=None,
override=True):
""" Same as `transform`, however, save the transformed statistics
to file using `odin.fuel.MmapArray`
Return
------
zero-th statistics: [1, nmix]
e.g. the assignment score each samples to each components, hence,
`#frames = Z.sum()`
first statistics: [1, feat_dim * nmix]
dot-product of each sample and the posteriors.
Note
----
If your data contain many very long utterances, it is suggested to use
`device='gpu'`, otherwise, 'cpu' is mostly significant faster.
"""
# ====== prepare inputs ====== #
if isinstance(indices, Mapping):
indices = sorted(indices.items(), key=lambda x: x[1][0])
if sad is not None:
assert sad.shape[0] == X.shape[0], \
"Number of samples in `X` (%d) and `sad` (%d) are mismatched" % (len(X), len(sad))
assert sad.ndim == 1 or (sad.ndim == 2 and sad.shape[1] == 1), \
"Invalid shape for `sad.shape=%s`" % str(sad.shape)
# ====== check device ====== #
if device is None:
device = self._device
on_gpu = True if device != 'cpu' and get_ngpu() > 0 else False
name_list = []
prog = Progbar(target=len(indices),
print_report=True, print_summary=True,
name="Saving zero-th and first order statistics")
# ====== init data files ====== #
if pathZ is not None:
if os.path.exists(pathZ):
if override:
os.remove(pathZ)
z_dat = MmapArray(path=pathZ, dtype=dtype,
shape=(None, self.nmix))
else:
z_dat = None
if pathF is not None:
if os.path.exists(pathF):
if override:
os.remove(pathF)
f_dat = MmapArray(path=pathF, dtype=dtype,
shape=(None, self.nmix * self.feat_dim))
else:
f_dat = None
# ====== helper ====== #
def _update_zf(Z, F):
# save zero-th stats
if z_dat is not None:
z_dat.append(Z)
# save first stats
if f_dat is not None:
f_dat.append(F)
def _batched_transform(s, e, on_gpu):
reduction = np.floor(np.power(2, self._curr_nmix / 1024))
batch_size = self.batch_size_gpu if on_gpu else self.batch_size_cpu
batch_size = int(batch_size / reduction)
x = X[s:e]
if sad is not None:
x = x[sad[s:e].astype('bool')]
if x.shape[0] <= batch_size:
res = [self._fast_expectation(x,
zero=z_dat is not None or f_dat is not None,
first=f_dat is not None,
second=False, llk=False,
on_gpu=on_gpu)]
else:
res = [self._fast_expectation(x[start:end],
zero=z_dat is not None or f_dat is not None,
first=f_dat is not None,
second=False, llk=False,
on_gpu=on_gpu)
for start, end in minibatch(n=x.shape[0], batch_size=batch_size)]
Z = sum(r[0] for r in res)
if len(res[0]) == 2:
F = sum(r[1] for r in res)
F = np.reshape(a=F - self.mean * Z,
newshape=(Z.shape[0], self._feat_dim * self._curr_nmix),
order='F')
else:
F = None
return Z, F
# ====== running on GPU ====== #
if on_gpu:
for n, (start, end) in indices:
Z, F = _batched_transform(start, end, on_gpu=True)
_update_zf(Z, F)
name_list.append(n)
prog.add(1)
# ====== run on CPU ====== #
else:
def map_func(j):
Z_list, F_list = [], []
name = []
for n, (start, end) in j:
name.append(n)
Z, F = _batched_transform(start, end, on_gpu=False)
if z_dat is not None:
Z_list.append(Z)
if f_dat is not None:
F_list.append(F)
yield 1
# concatenate into single large matrix
if len(Z_list) > 0:
Z_list = np.concatenate(Z_list, axis=0)
if len(F_list) > 0:
F_list = np.concatenate(F_list, axis=0)
yield name, Z_list, F_list
# run the MPI task
mpi = MPI(jobs=list(indices.items()) if isinstance(indices, Mapping)
else indices,
func=map_func,
ncpu=self.ncpu if ncpu is None else int(ncpu),
batch=max(2, self.batch_size_cpu // (self.ncpu * 2)),
hwm=2**25)
for results in mpi:
if is_number(results):
prog['Z_path'] = str(pathZ)
prog['F_path'] = str(pathF)
prog.add(results)
else:
name, Z, F = results
_update_zf(Z, F)
name_list += name
# ====== flush and return ====== #
if z_dat is not None:
z_dat.flush()
z_dat.close()
if f_dat is not None:
f_dat.flush()
f_dat.close()
# ====== save name_list ====== #
if isinstance(name_path, string_types):
np.savetxt(fname=name_path, X=name_list, fmt='%s')
return name_list
# ==================== math helper ==================== #
def logprob(self, X):
""" Shape: [batch_size, nmix]
the log probability of each observations to each components
given the GMM.
"""
self.initialize(X)
if self._device != 'cpu':
feed_dict = {self.X_: X}
feed_dict[self.__expressions_gpu['mu']] = self.mean
feed_dict[self.__expressions_gpu['sigma']] = self.sigma
feed_dict[self.__expressions_gpu['w']] = self.w
return K.eval(x=self.__expressions_gpu['logprob'],
feed_dict=feed_dict)
# ====== run on numpy ====== #
# (feat_dim, nmix)
precision = self.__expressions_cpu['precision']
mu_precision = self.__expressions_cpu['mu_precision']
C = self.__expressions_cpu['C']
X_2 = X ** 2
D = np.dot(X_2, precision) - \
2 * np.dot(X, mu_precision) + \
self._feat_const
# (batch_size, nmix)
logprob = -0.5 * (C + D)
return logprob
def postprob(self, X, gpu='auto'):
""" Shape: (batch_size, nmix)
The posterior probability of mixtures for each frame
"""
self.initialize(X)
if self._device != 'cpu':
feed_dict = {self.X_: X}
feed_dict[self.__expressions_gpu['mu']] = self.mean
feed_dict[self.__expressions_gpu['sigma']] = self.sigma
feed_dict[self.__expressions_gpu['w']] = self.w
return K.eval(x=self.__expressions_gpu['post'],
feed_dict=feed_dict)
# ====== run on numpy ====== #
# (feat_dim, nmix)
precision = self.__expressions_cpu['precision']
mu_precision = self.__expressions_cpu['mu_precision']
C = self.__expressions_cpu['C']
X_2 = X ** 2
D = np.dot(X_2, precision) - \
2 * np.dot(X, mu_precision) + \
self._feat_const
# (batch_size, nmix)
logprob = -0.5 * (C + D)
# ====== posterior and likelihood ====== #
llk = logsumexp(logprob, axis=1) # (batch_size, 1)
post = np.exp(logprob - llk) # (batch_size, nmix)
return post
def llk(self, X, gpu='auto'):
""" Shape: (batch_size, 1)
The log-likelihood value of each frame to all components
"""
self.initialize(X)
if self._device != 'cpu':
feed_dict = {self.X_: X}
feed_dict[self.__expressions_gpu['mu']] = self.mean
feed_dict[self.__expressions_gpu['sigma']] = self.sigma
feed_dict[self.__expressions_gpu['w']] = self.w
return K.eval(x=self.__expressions_gpu['llk'],
feed_dict=feed_dict)
# ====== run on numpy ====== #
# (feat_dim, nmix)
precision = self.__expressions_cpu['precision']
mu_precision = self.__expressions_cpu['mu_precision']
C = self.__expressions_cpu['C']
X_2 = X ** 2
D = np.dot(X_2, precision) - \
2 * np.dot(X, mu_precision) + \
self._feat_const
# (batch_size, nmix)
logprob = -0.5 * (C + D)
# ====== posterior and likelihood ====== #
llk = logsumexp(logprob, axis=1) # (batch_size, 1)
return llk
def _fast_expectation(self, X, zero=True, first=True, second=True,
llk=True, on_gpu=False):
# ====== run on GPU ====== #
if on_gpu: