/
tst.py
1888 lines (1613 loc) · 70 KB
/
tst.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
"""Module containing many types of two sample test algorithms"""
from __future__ import print_function
from __future__ import division
from builtins import str
from builtins import range
from past.utils import old_div
from builtins import object
from future.utils import with_metaclass
__author__ = "wittawat"
from abc import ABCMeta, abstractmethod
import autograd
import autograd.numpy as np
#from numba import jit
import freqopttest.util as util
import freqopttest.kernel as kernel
import matplotlib.pyplot as plt
import scipy
import scipy.stats as stats
import theano
import theano.tensor as tensor
import theano.tensor.nlinalg as nlinalg
import theano.tensor.slinalg as slinalg
class TwoSampleTest(with_metaclass(ABCMeta, object)):
"""Abstract class for two sample tests."""
def __init__(self, alpha=0.01):
"""
alpha: significance level of the test
"""
self.alpha = alpha
@abstractmethod
def perform_test(self, tst_data):
"""perform the two-sample test and return values computed in a dictionary:
{alpha: 0.01, pvalue: 0.0002, test_stat: 2.3, h0_rejected: True, ...}
tst_data: an instance of TSTData
"""
raise NotImplementedError()
@abstractmethod
def compute_stat(self, tst_data):
"""Compute the test statistic"""
raise NotImplementedError()
#@abstractmethod
#def visual_test(self, tst_data):
# """Perform the test and plot the results. This is suitable for use
# with IPython."""
# raise NotImplementedError()
##@abstractmethod
#def pvalue(self):
# """Compute and return the p-value of the test"""
# raise NotImplementedError()
#def h0_rejected(self):
# """Return true if the null hypothesis is rejected"""
# return self.pvalue() < self.alpha
class HotellingT2Test(TwoSampleTest):
"""Two-sample test with Hotelling T-squared statistic.
Techinical details follow "Applied Multivariate Analysis" of Neil H. Timm.
See page 156.
"""
def __init__(self, alpha=0.01):
self.alpha = alpha
def perform_test(self, tst_data):
"""perform the two-sample test and return values computed in a dictionary:
{alpha: 0.01, pvalue: 0.0002, test_stat: 2.3, h0_rejected: True, ...}
tst_data: an instance of TSTData
"""
d = tst_data.dim()
chi2_stat = self.compute_stat(tst_data)
pvalue = stats.chi2.sf(chi2_stat, d)
alpha = self.alpha
results = {'alpha': self.alpha, 'pvalue': pvalue, 'test_stat': chi2_stat,
'h0_rejected': pvalue < alpha}
return results
def compute_stat(self, tst_data):
"""Compute the test statistic"""
X, Y = tst_data.xy()
#if X.shape[0] != Y.shape[0]:
# raise ValueError('Require nx = ny for now. Will improve if needed.')
nx = X.shape[0]
ny = Y.shape[0]
mx = np.mean(X, 0)
my = np.mean(Y, 0)
mdiff = mx-my
sx = np.cov(X.T)
sy = np.cov(Y.T)
s = old_div(sx,nx) + old_div(sy,ny)
chi2_stat = np.dot(np.linalg.solve(s, mdiff), mdiff)
return chi2_stat
class LinearMMDTest(TwoSampleTest):
"""Two-sample test with linear MMD^2 statistic.
"""
def __init__(self, kernel, alpha=0.01):
"""
kernel: an instance of Kernel
"""
self.kernel = kernel
self.alpha = alpha
def perform_test(self, tst_data):
"""perform the two-sample test and return values computed in a dictionary:
{alpha: 0.01, pvalue: 0.0002, test_stat: 2.3, h0_rejected: True, ...}
tst_data: an instance of TSTData
"""
X, Y = tst_data.xy()
n = X.shape[0]
stat, snd = LinearMMDTest.two_moments(X, Y, self.kernel)
#var = snd - stat**2
var = snd
pval = stats.norm.sf(stat, loc=0, scale=(2.0*var/n)**0.5)
results = {'alpha': self.alpha, 'pvalue': pval, 'test_stat': stat,
'h0_rejected': pval < self.alpha}
return results
def compute_stat(self, tst_data):
"""Compute unbiased linear mmd estimator."""
X, Y = tst_data.xy()
return LinearMMDTest.linear_mmd(X, Y, self.kernel)
@staticmethod
def linear_mmd(X, Y, kernel):
"""Compute linear mmd estimator. O(n)"""
lin_mmd, _ = LinearMMDTest.two_moments(X, Y, kernel)
return lin_mmd
@staticmethod
def two_moments(X, Y, kernel):
"""Compute linear mmd estimator and a linear estimate of
the uncentred 2nd moment of h(z, z'). Total cost: O(n).
return: (linear mmd, linear 2nd moment)
"""
if X.shape[0] != Y.shape[0]:
raise ValueError('Require sample size of X = size of Y')
n = X.shape[0]
if n%2 == 1:
# make it even by removing the last row
X = np.delete(X, -1, axis=0)
Y = np.delete(Y, -1, axis=0)
Xodd = X[::2, :]
Xeven = X[1::2, :]
assert Xodd.shape[0] == Xeven.shape[0]
Yodd = Y[::2, :]
Yeven = Y[1::2, :]
assert Yodd.shape[0] == Yeven.shape[0]
# linear mmd. O(n)
xx = kernel.pair_eval(Xodd, Xeven)
yy = kernel.pair_eval(Yodd, Yeven)
xo_ye = kernel.pair_eval(Xodd, Yeven)
xe_yo = kernel.pair_eval(Xeven, Yodd)
h = xx + yy - xo_ye - xe_yo
lin_mmd = np.mean(h)
"""
Compute a linear-time estimate of the 2nd moment of h = E_z,z' h(z, z')^2.
Note that MMD = E_z,z' h(z, z').
Require O(n). Same trick as used in linear MMD to get O(n).
"""
lin_2nd = np.mean(h**2)
return lin_mmd, lin_2nd
@staticmethod
def variance(X, Y, kernel, lin_mmd=None):
"""Compute an estimate of the variance of the linear MMD.
Require O(n^2). This is the variance under H1.
"""
if X.shape[0] != Y.shape[0]:
raise ValueError('Require sample size of X = size of Y')
n = X.shape[0]
if lin_mmd is None:
lin_mmd = LinearMMDTest.linear_mmd(X, Y, kernel)
# compute uncentred 2nd moment of h(z, z')
K = kernel.eval(X, X)
L = kernel.eval(Y, Y)
KL = kernel.eval(X, Y)
snd_moment = old_div(np.sum( (K+L-KL-KL.T)**2 ),(n*(n-1)))
var_mmd = 2.0*(snd_moment - lin_mmd**2)
return var_mmd
@staticmethod
def grid_search_kernel(tst_data, list_kernels, alpha):
"""
Return from the list the best kernel that maximizes the test power.
return: (best kernel index, list of test powers)
"""
X, Y = tst_data.xy()
n = X.shape[0]
powers = np.zeros(len(list_kernels))
for ki, kernel in enumerate(list_kernels):
lin_mmd, snd_moment = LinearMMDTest.two_moments(X, Y, kernel)
var_lin_mmd = (snd_moment - lin_mmd**2)
# test threshold from N(0, var)
thresh = stats.norm.isf(alpha, loc=0, scale=(2.0*var_lin_mmd/n)**0.5)
power = stats.norm.sf(thresh, loc=lin_mmd, scale=(2.0*var_lin_mmd/n)**0.5)
#power = lin_mmd/var_lin_mmd
powers[ki] = power
best_ind = np.argmax(powers)
return best_ind, powers
# end of LinearMMDTest
class QuadMMDTest(TwoSampleTest):
"""
Quadratic MMD test where the null distribution is computed by permutation.
- Use a single U-statistic i.e., remove diagonal from the Kxy matrix.
- The code is based on a Matlab code of Arthur Gretton from the paper
A TEST OF RELATIVE SIMILARITY FOR MODEL SELECTION IN GENERATIVE MODELS
ICLR 2016
"""
def __init__(self, kernel, n_permute=400, alpha=0.01, use_1sample_U=False):
"""
kernel: an instance of Kernel
n_permute: number of times to do permutation
"""
self.kernel = kernel
self.n_permute = n_permute
self.alpha = alpha
self.use_1sample_U = use_1sample_U
def perform_test(self, tst_data):
"""perform the two-sample test and return values computed in a dictionary:
{alpha: 0.01, pvalue: 0.0002, test_stat: 2.3, h0_rejected: True, ...}
tst_data: an instance of TSTData
"""
d = tst_data.dim()
alpha = self.alpha
mmd2_stat = self.compute_stat(tst_data, use_1sample_U=self.use_1sample_U)
X, Y = tst_data.xy()
k = self.kernel
repeats = self.n_permute
list_mmd2 = QuadMMDTest.permutation_list_mmd2(X, Y, k, repeats)
# approximate p-value with the permutations
pvalue = np.mean(list_mmd2 > mmd2_stat)
results = {'alpha': self.alpha, 'pvalue': pvalue, 'test_stat': mmd2_stat,
'h0_rejected': pvalue < alpha, 'list_permuted_mmd2': list_mmd2}
return results
def compute_stat(self, tst_data, use_1sample_U=True):
"""Compute the test statistic: empirical quadratic MMD^2"""
X, Y = tst_data.xy()
nx = X.shape[0]
ny = Y.shape[0]
if nx != ny:
raise ValueError('nx must be the same as ny')
k = self.kernel
mmd2, var = QuadMMDTest.h1_mean_var(X, Y, k, is_var_computed=False,
use_1sample_U=use_1sample_U)
return mmd2
@staticmethod
def permutation_list_mmd2(X, Y, k, n_permute=400, seed=8273):
"""
Repeatedly mix, permute X,Y and compute MMD^2. This is intended to be
used to approximate the null distritubion.
TODO: This is a naive implementation where the kernel matrix is recomputed
for each permutation. We might be able to improve this if needed.
"""
return QuadMMDTest.permutation_list_mmd2_gram(X, Y, k, n_permute, seed)
@staticmethod
def permutation_list_mmd2_gram(X, Y, k, n_permute=400, seed=8273):
"""
Repeatedly mix, permute X,Y and compute MMD^2. This is intended to be
used to approximate the null distritubion.
"""
XY = np.vstack((X, Y))
Kxyxy = k.eval(XY, XY)
rand_state = np.random.get_state()
np.random.seed(seed)
nxy = XY.shape[0]
nx = X.shape[0]
ny = Y.shape[0]
list_mmd2 = np.zeros(n_permute)
for r in range(n_permute):
#print r
ind = np.random.choice(nxy, nxy, replace=False)
# divide into new X, Y
indx = ind[:nx]
#print(indx)
indy = ind[nx:]
Kx = Kxyxy[np.ix_(indx, indx)]
#print(Kx)
Ky = Kxyxy[np.ix_(indy, indy)]
Kxy = Kxyxy[np.ix_(indx, indy)]
mmd2r, var = QuadMMDTest.h1_mean_var_gram(Kx, Ky, Kxy, is_var_computed=False)
list_mmd2[r] = mmd2r
np.random.set_state(rand_state)
return list_mmd2
@staticmethod
def h1_mean_var_gram(Kx, Ky, Kxy, is_var_computed, use_1sample_U=True):
"""
Same as h1_mean_var() but takes in Gram matrices directly.
"""
nx = Kx.shape[0]
ny = Ky.shape[0]
xx = old_div((np.sum(Kx) - np.sum(np.diag(Kx))),(nx*(nx-1)))
yy = old_div((np.sum(Ky) - np.sum(np.diag(Ky))),(ny*(ny-1)))
# one-sample U-statistic.
if use_1sample_U:
xy = old_div((np.sum(Kxy) - np.sum(np.diag(Kxy))),(nx*(ny-1)))
else:
xy = old_div(np.sum(Kxy),(nx*ny))
mmd2 = xx - 2*xy + yy
if not is_var_computed:
return mmd2, None
# compute the variance
Kxd = Kx - np.diag(np.diag(Kx))
Kyd = Ky - np.diag(np.diag(Ky))
m = nx
n = ny
v = np.zeros(11)
Kxd_sum = np.sum(Kxd)
Kyd_sum = np.sum(Kyd)
Kxy_sum = np.sum(Kxy)
Kxy2_sum = np.sum(Kxy**2)
Kxd0_red = np.sum(Kxd, 1)
Kyd0_red = np.sum(Kyd, 1)
Kxy1 = np.sum(Kxy, 1)
Kyx1 = np.sum(Kxy, 0)
# varEst = 1/m/(m-1)/(m-2) * ( sum(Kxd,1)*sum(Kxd,2) - sum(sum(Kxd.^2))) ...
v[0] = 1.0/m/(m-1)/(m-2)*( np.dot(Kxd0_red, Kxd0_red ) - np.sum(Kxd**2) )
# - ( 1/m/(m-1) * sum(sum(Kxd)) )^2 ...
v[1] = -( 1.0/m/(m-1) * Kxd_sum )**2
# - 2/m/(m-1)/n * sum(Kxd,1) * sum(Kxy,2) ...
v[2] = -2.0/m/(m-1)/n * np.dot(Kxd0_red, Kxy1)
# + 2/m^2/(m-1)/n * sum(sum(Kxd))*sum(sum(Kxy)) ...
v[3] = 2.0/(m**2)/(m-1)/n * Kxd_sum*Kxy_sum
# + 1/(n)/(n-1)/(n-2) * ( sum(Kyd,1)*sum(Kyd,2) - sum(sum(Kyd.^2))) ...
v[4] = 1.0/n/(n-1)/(n-2)*( np.dot(Kyd0_red, Kyd0_red) - np.sum(Kyd**2 ) )
# - ( 1/n/(n-1) * sum(sum(Kyd)) )^2 ...
v[5] = -( 1.0/n/(n-1) * Kyd_sum )**2
# - 2/n/(n-1)/m * sum(Kyd,1) * sum(Kxy',2) ...
v[6] = -2.0/n/(n-1)/m * np.dot(Kyd0_red, Kyx1)
# + 2/n^2/(n-1)/m * sum(sum(Kyd))*sum(sum(Kxy)) ...
v[7] = 2.0/(n**2)/(n-1)/m * Kyd_sum*Kxy_sum
# + 1/n/(n-1)/m * ( sum(Kxy',1)*sum(Kxy,2) -sum(sum(Kxy.^2)) ) ...
v[8] = 1.0/n/(n-1)/m * ( np.dot(Kxy1, Kxy1) - Kxy2_sum )
# - 2*(1/n/m * sum(sum(Kxy)) )^2 ...
v[9] = -2.0*( 1.0/n/m*Kxy_sum )**2
# + 1/m/(m-1)/n * ( sum(Kxy,1)*sum(Kxy',2) - sum(sum(Kxy.^2))) ;
v[10] = 1.0/m/(m-1)/n * ( np.dot(Kyx1, Kyx1) - Kxy2_sum )
#%additional low order correction made to some terms compared with ICLR submission
#%these corrections are of the same order as the 2nd order term and will
#%be unimportant far from the null.
# %Eq. 13 p. 11 ICLR 2016. This uses ONLY first order term
# varEst = 4*(m-2)/m/(m-1) * varEst ;
varEst1st = 4.0*(m-2)/m/(m-1) * np.sum(v)
Kxyd = Kxy - np.diag(np.diag(Kxy))
# %Eq. 13 p. 11 ICLR 2016: correction by adding 2nd order term
# varEst2nd = 2/m/(m-1) * 1/n/(n-1) * sum(sum( (Kxd + Kyd - Kxyd - Kxyd').^2 ));
varEst2nd = 2.0/m/(m-1) * 1/n/(n-1) * np.sum( (Kxd + Kyd - Kxyd - Kxyd.T)**2)
# varEst = varEst + varEst2nd;
varEst = varEst1st + varEst2nd
# %use only 2nd order term if variance estimate negative
if varEst<0:
varEst = varEst2nd
return mmd2, varEst
@staticmethod
def h1_mean_var(X, Y, k, is_var_computed, use_1sample_U=True):
"""
X: nxd numpy array
Y: nxd numpy array
k: a Kernel object
is_var_computed: if True, compute the variance. If False, return None.
use_1sample_U: if True, use one-sample U statistic for the cross term
i.e., k(X, Y).
Code based on Arthur Gretton's Matlab implementation for
Bounliphone et. al., 2016.
return (MMD^2, var[MMD^2]) under H1
"""
nx = X.shape[0]
ny = Y.shape[0]
Kx = k.eval(X, X)
Ky = k.eval(Y, Y)
Kxy = k.eval(X, Y)
return QuadMMDTest.h1_mean_var_gram(Kx, Ky, Kxy, is_var_computed, use_1sample_U)
@staticmethod
def grid_search_kernel(tst_data, list_kernels, alpha, reg=1e-3):
"""
Return from the list the best kernel that maximizes the test power criterion.
In principle, the test threshold depends on the null distribution, which
changes with kernel. Thus, we need to recompute the threshold for each kernel
(require permutations), which is expensive. However, asymptotically
the threshold goes to 0. So, for each kernel, the criterion needed is
the ratio mean/variance of the MMD^2. (Source: Arthur Gretton)
This is an approximate to avoid doing permutations for each kernel
candidate.
- reg: regularization parameter
return: (best kernel index, list of test power objective values)
"""
import time
X, Y = tst_data.xy()
n = X.shape[0]
obj_values = np.zeros(len(list_kernels))
for ki, k in enumerate(list_kernels):
start = time.time()
mmd2, mmd2_var = QuadMMDTest.h1_mean_var(X, Y, k, is_var_computed=True)
obj = float(mmd2)/((mmd2_var + reg)**0.5)
obj_values[ki] = obj
end = time.time()
print('(%d/%d) %s: mmd2: %.3g, var: %.3g, power obj: %g, took: %s'%(ki+1,
len(list_kernels), str(k), mmd2, mmd2_var, obj, end-start))
best_ind = np.argmax(obj_values)
return best_ind, obj_values
class GammaMMDKGaussTest(TwoSampleTest):
"""MMD test by fitting a Gamma distribution to the test statistic (MMD^2).
This class is specific to Gaussian kernel.
The implementation follows Arthur Gretton's Matlab code at
http://www.gatsby.ucl.ac.uk/~gretton/mmd/mmd.htm
- Has O(n^2) memory and runtime complexity
"""
def __init__(self, gwidth2, alpha=0.01):
"""
gwidth2: Gaussian width squared. Kernel is exp(|x-y|^2/(2*width^2))
"""
self.alpha = alpha
self.gwidth2 = gwidth2
raise NotImplementedError('GammaMMDKGaussTest is not implemented.')
def perform_test(self, tst_data):
"""perform the two-sample test and return values computed in a dictionary:
{alpha: 0.01, pvalue: 0.0002, test_stat: 2.3, h0_rejected: True, ...}
"""
meanMMD, varMMD, test_stat = \
GammaMMDKGaussTest.compute_mean_variance_stat(tst_data, self.gwidth2)
# parameters of the fitted Gamma distribution
X, _ = tst_data.xy()
n = X.shape[0]
al = old_div(meanMMD**2, varMMD)
bet = varMMD*n / meanMMD
pval = stats.gamma.sf(test_stat, al, scale=bet)
results = {'alpha': self.alpha, 'pvalue': pval, 'test_stat': test_stat,
'h0_rejected': pval < self.alpha}
return results
def compute_stat(self, tst_data):
"""Compute the test statistic"""
raise NotImplementedError()
@staticmethod
def compute_mean_variance_stat(tst_data, gwidth2):
"""Compute the mean and variance of the MMD^2, and the test statistic
:return: (mean, variance)
"""
X, Y = tst_data.xy()
if X.shape[0] != Y.shape[0]:
raise ValueError('Require sample size of X = size of Y')
ker = kernel.KGauss(gwidth2)
K = ker.eval(X, X)
L = ker.eval(Y, Y)
KL = ker.eval(X, Y)
n = X.shape[0]
# computing meanMMD is only correct for Gaussian kernels.
meanMMD = 2.0/n * (1.0 - 1.0/n*np.sum(np.diag(KL)))
np.fill_diagonal(K, 0.0)
np.fill_diagonal(L, 0.0)
np.fill_diagonal(KL, 0.0)
varMMD = 2.0/n/(n-1) * 1.0/n/(n-1) * np.sum((K + L - KL - KL.T)**2)
# test statistic
test_stat = 1.0/n * np.sum(K + L - KL - KL.T)
return meanMMD, varMMD, test_stat
@staticmethod
def grid_search_gwidth2(tst_data, list_gwidth2, alpha):
"""
Return the Gaussian width squared in the list that maximizes the test power.
The test power p(test_stat > alpha) is computed based on the distribution
of the MMD^2 under H_1, which is a Gaussian.
- list_gwidth2: a list of squared Gaussian width candidates
:return: best width^2, list of test powers
"""
raise NotImplementedError('Not implemented yet')
pass
#X, Y = tst_data.xy()
#gwidth2_powers = np.zeros(len(list_gwidth2))
#n = X.shape[0]
#for i, gwidth2_i in enumerate(list_gwidth2):
# meanMMD, varMMD, test_stat = \
# GammaMMDKGaussTest.compute_mean_variance_stat(tst_data, gwidth2_i)
# # x_alpha = location corresponding to alpha under H0
# al = meanMMD**2 / varMMD
# bet = varMMD*n / meanMMD
# x_alpha = stats.gamma.ppf(1.0-alpha, al, scale=bet)
# # Distribution of MMD under H1 is a Gaussian
# power = stats.norm.sf(x_alpha, loc=meanMMD, scale=(varMMD/n)**0.5)
# gwidth2_powers[i] = power
# print 'al: %.3g, bet: %.3g, gw2: %.2g, m_mmd: %.3g, v_mmd: %.3g'%(al, bet,
# gwidth2_i, meanMMD, varMMD)
# print 'x_alpha: %.3g'%x_alpha
# print ''
#best_i = np.argmax(gwidth2_powers)
#return list_gwidth2[best_i], gwidth2_powers
#-------------------------------------------------
class SmoothCFTest(TwoSampleTest):
"""Class for two-sample test using smooth characteristic functions.
Use Gaussian kernel."""
def __init__(self, test_freqs, gaussian_width, alpha=0.01):
"""
:param test_freqs: J x d numpy array of J frequencies to test the difference
gaussian_width: The width is used to divide the data. The test will be
equivalent if the data is divided beforehand and gaussian_width=1.
"""
super(SmoothCFTest, self).__init__(alpha)
self.test_freqs = test_freqs
self.gaussian_width = gaussian_width
@property
def gaussian_width(self):
# Gaussian width. Positive number.
return self._gaussian_width
@gaussian_width.setter
def gaussian_width(self, width):
if util.is_real_num(width) and float(width) > 0:
self._gaussian_width = float(width)
else:
raise ValueError('gaussian_width must be a float > 0. Was %s'%(str(width)))
def compute_stat(self, tst_data):
# test freqs or Gaussian width undefined
if self.test_freqs is None:
raise ValueError('test_freqs must be specified.')
X, Y = tst_data.xy()
test_freqs = self.test_freqs
gamma = self.gaussian_width
s = SmoothCFTest.compute_nc_parameter(X, Y, test_freqs, gamma)
return s
def perform_test(self, tst_data):
"""perform the two-sample test and return values computed in a dictionary:
{alpha: 0.01, pvalue: 0.0002, test_stat: 2.3, h0_rejected: True, ...}
tst_data: an instance of TSTData
"""
stat = self.compute_stat(tst_data)
J, d = self.test_freqs.shape
# 2J degrees of freedom because of sin and cos
pvalue = stats.chi2.sf(stat, 2*J)
alpha = self.alpha
results = {'alpha': self.alpha, 'pvalue': pvalue, 'test_stat': stat,
'h0_rejected': pvalue < alpha}
return results
#---------------------------------
@staticmethod
def compute_nc_parameter(X, Y, T, gwidth, reg='auto'):
"""
Compute the non-centrality parameter of the non-central Chi-squared
which is the distribution of the test statistic under the H_1 (and H_0).
The nc parameter is also the test statistic.
"""
if gwidth is None or gwidth <= 0:
raise ValueError('require gaussian_width > 0. Was %s'%(str(gwidth)))
Z = SmoothCFTest.construct_z(X, Y, T, gwidth)
s = generic_nc_parameter(Z, reg)
return s
@staticmethod
def grid_search_gwidth(tst_data, T, list_gwidth, alpha):
"""
Linear search for the best Gaussian width in the list that maximizes
the test power, fixing the test locations ot T.
The test power is given by the CDF of a non-central Chi-squared
distribution.
return: (best width index, list of test powers)
"""
func_nc_param = SmoothCFTest.compute_nc_parameter
J = T.shape[0]
return generic_grid_search_gwidth(tst_data, T, 2*J, list_gwidth, alpha,
func_nc_param)
@staticmethod
def create_randn(tst_data, J, alpha=0.01, seed=19):
"""Create a SmoothCFTest whose test frequencies are drawn from
the standard Gaussian """
rand_state = np.random.get_state()
np.random.seed(seed)
gamma = tst_data.mean_std()*tst_data.dim()**0.5
d = tst_data.dim()
T = np.random.randn(J, d)
np.random.set_state(rand_state)
scf_randn = SmoothCFTest(T, gamma, alpha=alpha)
return scf_randn
@staticmethod
def construct_z(X, Y, test_freqs, gaussian_width):
"""Construct the features Z to be used for testing with T^2 statistics.
Z is defined in Eq.14 of Chwialkovski et al., 2015 (NIPS).
test_freqs: J x d test frequencies
Return a n x 2J numpy array. 2J because of sin and cos for each frequency.
"""
if X.shape[0] != Y.shape[0]:
raise ValueError('Sample size n must be the same for X and Y.')
X = old_div(X,gaussian_width)
Y = old_div(Y,gaussian_width)
n, d = X.shape
J = test_freqs.shape[0]
# inverse Fourier transform (upto scaling) of the unit-width Gaussian kernel
fx = np.exp(old_div(-np.sum(X**2, 1),2))[:, np.newaxis]
fy = np.exp(old_div(-np.sum(Y**2, 1),2))[:, np.newaxis]
# n x J
x_freq = np.dot(X, test_freqs.T)
y_freq = np.dot(Y, test_freqs.T)
# zx: n x 2J
zx = np.hstack((np.sin(x_freq)*fx, np.cos(x_freq)*fx))
zy = np.hstack((np.sin(y_freq)*fy, np.cos(y_freq)*fy))
z = zx-zy
assert z.shape == (n, 2*J)
return z
@staticmethod
def construct_z_theano(Xth, Yth, Tth, gwidth_th):
"""Construct the features Z to be used for testing with T^2 statistics.
Z is defined in Eq.14 of Chwialkovski et al., 2015 (NIPS).
Theano version.
Return a n x 2J numpy array. 2J because of sin and cos for each frequency.
"""
Xth = old_div(Xth,gwidth_th)
Yth = old_div(Yth,gwidth_th)
# inverse Fourier transform (upto scaling) of the unit-width Gaussian kernel
fx = tensor.exp(old_div(-(Xth**2).sum(1),2)).reshape((-1, 1))
fy = tensor.exp(old_div(-(Yth**2).sum(1),2)).reshape((-1, 1))
# n x J
x_freq = Xth.dot(Tth.T)
y_freq = Yth.dot(Tth.T)
# zx: n x 2J
zx = tensor.concatenate([tensor.sin(x_freq)*fx, tensor.cos(x_freq)*fx], axis=1)
zy = tensor.concatenate([tensor.sin(y_freq)*fy, tensor.cos(y_freq)*fy], axis=1)
z = zx-zy
return z
@staticmethod
def optimize_freqs_width(tst_data, alpha, n_test_freqs=10, max_iter=400,
freqs_step_size=0.2, gwidth_step_size=0.01, batch_proportion=1.0,
tol_fun=1e-3, seed=1):
"""Optimize the test frequencies and the Gaussian kernel width by
maximizing the test power. X, Y should not be the same data as used
in the actual test (i.e., should be a held-out set).
- max_iter: #gradient descent iterations
- batch_proportion: (0,1] value to be multipled with nx giving the batch
size in stochastic gradient. 1 = full gradient ascent.
- tol_fun: termination tolerance of the objective value
Return (test_freqs, gaussian_width, info)
"""
J = n_test_freqs
"""
Optimize the empirical version of Lambda(T) i.e., the criterion used
to optimize the test locations, for the test based
on difference of mean embeddings with Gaussian kernel.
Also optimize the Gaussian width.
:return a theano function T |-> Lambda(T)
"""
d = tst_data.dim()
# set the seed
rand_state = np.random.get_state()
np.random.seed(seed)
# draw frequencies randomly from the standard Gaussian.
# TODO: Can we do better?
T0 = np.random.randn(J, d)
# reset the seed back to the original
np.random.set_state(rand_state)
# grid search to determine the initial gwidth
mean_sd = tst_data.mean_std()
scales = 2.0**np.linspace(-4, 3, 20)
list_gwidth = np.hstack( (mean_sd*scales*(d**0.5), 2**np.linspace(-4, 4, 20) ))
list_gwidth.sort()
besti, powers = SmoothCFTest.grid_search_gwidth(tst_data, T0,
list_gwidth, alpha)
# initialize with the best width from the grid search
gwidth0 = list_gwidth[besti]
assert util.is_real_num(gwidth0), 'gwidth0 not real. Was %s'%str(gwidth0)
assert gwidth0 > 0, 'gwidth0 not positive. Was %.3g'%gwidth0
func_z = SmoothCFTest.construct_z_theano
# info = optimization info
T, gamma, info = optimize_T_gaussian_width(tst_data, T0, gwidth0, func_z,
max_iter=max_iter, T_step_size=freqs_step_size,
gwidth_step_size=gwidth_step_size, batch_proportion=batch_proportion,
tol_fun=tol_fun)
assert util.is_real_num(gamma), 'gamma is not real. Was %s' % str(gamma)
ninfo = {'test_freqs': info['Ts'], 'test_freqs0': info['T0'],
'gwidths': info['gwidths'], 'obj_values': info['obj_values'],
'gwidth0': gwidth0, 'gwidth0_powers': powers}
return (T, gamma, ninfo )
@staticmethod
def optimize_gwidth(tst_data, T, gwidth0, max_iter=400,
gwidth_step_size=0.1, batch_proportion=1.0, tol_fun=1e-3):
"""Optimize the Gaussian kernel width by
maximizing the test power, fixing the test frequencies to T. X, Y should
not be the same data as used in the actual test (i.e., should be a
held-out set).
- max_iter: #gradient descent iterations
- batch_proportion: (0,1] value to be multipled with nx giving the batch
size in stochastic gradient. 1 = full gradient ascent.
- tol_fun: termination tolerance of the objective value
Return (gaussian_width, info)
"""
func_z = SmoothCFTest.construct_z_theano
# info = optimization info
gamma, info = optimize_gaussian_width(tst_data, T, gwidth0, func_z,
max_iter=max_iter, gwidth_step_size=gwidth_step_size,
batch_proportion=batch_proportion, tol_fun=tol_fun)
ninfo = {'test_freqs': T, 'gwidths': info['gwidths'], 'obj_values':
info['obj_values']}
return ( gamma, ninfo )
#-------------------------------------------------
class UMETest(TwoSampleTest):
"""
Unnormalized ME (UME) test. The test statistic is given by n (sample size)
times the unbiased version of the average of the evaluations of the squared
witness function. The squared witness is evaluated at J "test locations".
This is the test mentioned in Chwialkovski et al., 2015, but not studied.
The test statistic is a second-order U-statistic scaled up by n.
"""
def __init__(self, test_locs, k, n_simulate=2000, seed=87, alpha=0.01):
"""
test_locs: J x d numpy array of J test locations
k: a Kernel
n_simulate: number of draws from the null distribution
seed: random seed used when simulating the null distribution
alpha: significance level of the test.
"""
super(UMETest, self).__init__(alpha)
if test_locs is None or len(test_locs) == 0:
raise ValueError('test_locs cannot be empty. Was {}'.format(test_locs))
self.test_locs = test_locs
self.k = k
self.n_simulate = n_simulate
self.seed = seed
def perform_test(self, tst_data, return_simulated_stats=False):
with util.ContextTimer() as t:
alpha = self.alpha
X, Y = tst_data.xy()
n = X.shape[0]
V = self.test_locs
J = V.shape[0]
# stat = n*(UME stat)
# Z = n x J feature matrix
stat, Z = self.compute_stat(tst_data, return_feature_matrix=True)
# Simulate from the asymptotic null distribution
n_simulate = self.n_simulate
# Uncentred covariance matrix
cov = np.dot(Z.T, Z)/float(n)
arr_nume, eigs = UMETest.list_simulate_spectral(cov, J, n_simulate,
seed=self.seed)
# approximate p-value with the permutations
pvalue = np.mean(arr_nume > stat)
results = {'alpha': self.alpha, 'pvalue': pvalue, 'test_stat': stat,
'h0_rejected': pvalue < alpha, 'n_simulate': n_simulate,
'time_secs': t.secs,
}
if return_simulated_stats:
results['sim_stats'] = arr_nume
return results
def compute_stat(self, tst_data, return_feature_matrix=False):
"""
tst_data: TSTData object
Return the statistic. If return_feature_matrix is True, then return
(the statistic, feature tensor of size nxJ )
"""
X, Y = tst_data.xy()
# n = sample size
n = X.shape[0]
Z = self.feature_matrix(tst_data)
uhat = UMETest.ustat_h1_mean_variance(Z, return_variance=False,
use_unbiased=True)
stat = n*uhat
if return_feature_matrix:
return stat, Z
else:
return stat
def feature_matrix(self, tst_data):
"""
Compute the n x J feature matrix. The test statistic and other relevant
quantities can all be expressed as a function of this matrix. Here, n =
sample size, J = number of test locations.
"""
X, Y = tst_data.xy()
V = self.test_locs
# J = number of test locations
J = V.shape[0]
k = self.k
# n x J feature matrix
g = k.eval(X, V)/np.sqrt(J)
h = k.eval(Y, V)/np.sqrt(J)
Z = g-h
return Z
@staticmethod
def list_simulate_spectral(cov, J, n_simulate=2000, seed=82):
"""
Simulate the null distribution using the spectrum of the covariance
matrix. This is intended to be used to approximate the null
distribution.
Return (a numpy array of simulated n*FSSD values, eigenvalues of cov)
"""
# eigen decompose
eigs, _ = np.linalg.eig(cov)
eigs = np.real(eigs)
# sort in decreasing order
eigs = -np.sort(-eigs)
sim_umes = UMETest.simulate_null_dist(eigs, J, n_simulate=n_simulate,
seed=seed)
return sim_umes, eigs
@staticmethod
def simulate_null_dist(eigs, J, n_simulate=2000, seed=7):
"""
Simulate the null distribution using the spectrum of the covariance
matrix of the U-statistic. The simulated statistic is n*UME^2 where
UME is an unbiased estimator.
- eigs: a numpy array of estimated eigenvalues of the covariance
matrix. eigs is of length J
- J: the number of test locations.
Return a numpy array of simulated statistics.
"""
# draw at most J x block_size values at a time
block_size = max(20, int(old_div(1000.0,J)))
umes = np.zeros(n_simulate)
from_ind = 0
with util.NumpySeedContext(seed=seed):
while from_ind < n_simulate:
to_draw = min(block_size, n_simulate-from_ind)
# draw chi^2 random variables.
chi2 = np.random.randn(J, to_draw)**2
# an array of length to_draw
sim_umes = np.dot(eigs, chi2-1.0)
# store
end_ind = from_ind+to_draw
umes[from_ind:end_ind] = sim_umes
from_ind = end_ind
return umes
@staticmethod
def power_criterion(tst_data, test_locs, k, reg=1e-2, use_unbiased=True):
"""
Compute the mean and standard deviation of the statistic under H1.
Return power criterion = mean_under_H1/sqrt(var_under_H1 + reg) .
"""
ume = UMETest(test_locs, k)
Z = ume.feature_matrix(tst_data)
u_mean, u_variance = UMETest.ustat_h1_mean_variance(Z,
return_variance=True, use_unbiased=use_unbiased)
# mean/sd criterion
sigma_h1 = np.sqrt(u_variance + reg)
ratio = old_div(u_mean, sigma_h1)
return ratio
@staticmethod
def ustat_h1_mean_variance(feature_matrix, return_variance=True,
use_unbiased=True):
"""
Compute the mean and variance of the asymptotic normal distribution
under H1 of the test statistic. The mean converges to a constant as
n->\infty.
feature_matrix: n x J feature matrix
return_variance: If false, avoid computing and returning the variance.
use_unbiased: If True, use the unbiased version of the mean. Can be
negative.
Return the mean [and the variance]
"""
Z = feature_matrix
n, J = Z.shape
assert n > 1, 'Need n > 1 to compute the mean of the statistic.'
if use_unbiased:
t1 = np.sum(np.mean(Z, axis=0)**2)*(n/float(n-1))
t2 = np.mean(np.sum(Z**2, axis=1))/float(n-1)
mean_h1 = t1 - t2
else:
mean_h1 = np.sum(np.mean(Z, axis=0)**2)
if return_variance:
# compute the variance
mu = np.mean(Z, axis=0) # length-J vector
variance = 4.0*np.mean(np.dot(Z, mu)**2) - 4.0*np.sum(mu**2)**2
return mean_h1, variance
else:
return mean_h1
# end of class UMETest
class GaussUMETest(UMETest):
"""
UMETest using a Gaussian kernel. This class provides static methods for
optimizing the Gaussian kernel bandwidth, and test locations.
"""
def __init__(self, test_locs, sigma2, n_simulate=2000, seed=87, alpha=0.01):
"""
test_locs: J x d numpy array of J test locations
sigma2: Squared bandwidth in the Gaussian kernel.