/
test_gee.py
1947 lines (1521 loc) · 68.3 KB
/
test_gee.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
"""
Test functions for GEE
External comparisons are to R and Stata. The statmodels GEE
implementation should generally agree with the R GEE implementation
for the independence and exchangeable correlation structures. For
other correlation structures, the details of the correlation
estimation differ among implementations and the results will not agree
exactly.
"""
from statsmodels.compat import lrange
import os
import numpy as np
import pytest
from numpy.testing import (assert_almost_equal, assert_equal, assert_allclose,
assert_array_less, assert_raises, assert_warns,
assert_)
import statsmodels.genmod.generalized_estimating_equations as gee
import statsmodels.tools as tools
import statsmodels.regression.linear_model as lm
from statsmodels.genmod import families
from statsmodels.genmod import cov_struct
import statsmodels.discrete.discrete_model as discrete
import pandas as pd
from scipy.stats.distributions import norm
import warnings
try:
import matplotlib.pyplot as plt
except ImportError:
pass
pdf_output = False
if pdf_output:
from matplotlib.backends.backend_pdf import PdfPages
pdf = PdfPages("test_glm.pdf")
else:
pdf = None
def close_or_save(pdf, fig):
if pdf_output:
pdf.savefig(fig)
def load_data(fname, icept=True):
"""
Load a data set from the results directory. The data set should
be a CSV file with the following format:
Column 0: Group indicator
Column 1: endog variable
Columns 2-end: exog variables
If `icept` is True, an intercept is prepended to the exog
variables.
"""
cur_dir = os.path.dirname(os.path.abspath(__file__))
Z = np.genfromtxt(os.path.join(cur_dir, 'results', fname),
delimiter=",")
group = Z[:, 0]
endog = Z[:, 1]
exog = Z[:, 2:]
if icept:
exog = np.concatenate((np.ones((exog.shape[0], 1)), exog),
axis=1)
return endog, exog, group
def check_wrapper(results):
# check wrapper
assert_(isinstance(results.params, pd.Series))
assert_(isinstance(results.fittedvalues, pd.Series))
assert_(isinstance(results.resid, pd.Series))
assert_(isinstance(results.centered_resid, pd.Series))
assert_(isinstance(results._results.params, np.ndarray))
assert_(isinstance(results._results.fittedvalues, np.ndarray))
assert_(isinstance(results._results.resid, np.ndarray))
assert_(isinstance(results._results.centered_resid, np.ndarray))
class TestGEE(object):
def test_margins_gaussian(self):
# Check marginal effects for a Gaussian GEE fit. Marginal
# effects and ordinary effects should be equal.
n = 40
np.random.seed(34234)
exog = np.random.normal(size=(n, 3))
exog[:, 0] = 1
groups = np.kron(np.arange(n / 4), np.r_[1, 1, 1, 1])
endog = exog[:, 1] + np.random.normal(size=n)
model = gee.GEE(endog, exog, groups)
result = model.fit(
start_params=[-4.88085602e-04, 1.18501903, 4.78820100e-02])
marg = result.get_margeff()
assert_allclose(marg.margeff, result.params[1:])
assert_allclose(marg.margeff_se, result.bse[1:])
# smoke test
marg.summary()
def test_margins_logistic(self):
# Check marginal effects for a binomial GEE fit. Comparison
# comes from Stata.
np.random.seed(34234)
endog = np.r_[0, 0, 0, 0, 1, 1, 1, 1]
exog = np.ones((8, 2))
exog[:, 1] = np.r_[1, 2, 1, 1, 2, 1, 2, 2]
groups = np.arange(8)
model = gee.GEE(endog, exog, groups, family=families.Binomial())
result = model.fit(
cov_type='naive', start_params=[-3.29583687, 2.19722458])
marg = result.get_margeff()
assert_allclose(marg.margeff, np.r_[0.4119796])
assert_allclose(marg.margeff_se, np.r_[0.1379962], rtol=1e-6)
def test_margins_multinomial(self):
# Check marginal effects for a 2-class multinomial GEE fit,
# which should be equivalent to logistic regression. Comparison
# comes from Stata.
np.random.seed(34234)
endog = np.r_[0, 0, 0, 0, 1, 1, 1, 1]
exog = np.ones((8, 2))
exog[:, 1] = np.r_[1, 2, 1, 1, 2, 1, 2, 2]
groups = np.arange(8)
model = gee.NominalGEE(endog, exog, groups)
result = model.fit(cov_type='naive', start_params=[
3.295837, -2.197225])
marg = result.get_margeff()
assert_allclose(marg.margeff, np.r_[-0.41197961], rtol=1e-5)
assert_allclose(marg.margeff_se, np.r_[0.1379962], rtol=1e-6)
@pytest.mark.smoke
@pytest.mark.matplotlib
def test_nominal_plot(self, close_figures):
np.random.seed(34234)
endog = np.r_[0, 0, 0, 0, 1, 1, 1, 1]
exog = np.ones((8, 2))
exog[:, 1] = np.r_[1, 2, 1, 1, 2, 1, 2, 2]
groups = np.arange(8)
model = gee.NominalGEE(endog, exog, groups)
result = model.fit(cov_type='naive',
start_params=[3.295837, -2.197225])
fig = result.plot_distribution()
assert_equal(isinstance(fig, plt.Figure), True)
def test_margins_poisson(self):
# Check marginal effects for a Poisson GEE fit.
np.random.seed(34234)
endog = np.r_[10, 15, 12, 13, 20, 18, 26, 29]
exog = np.ones((8, 2))
exog[:, 1] = np.r_[0, 0, 0, 0, 1, 1, 1, 1]
groups = np.arange(8)
model = gee.GEE(endog, exog, groups, family=families.Poisson())
result = model.fit(cov_type='naive', start_params=[
2.52572864, 0.62057649])
marg = result.get_margeff()
assert_allclose(marg.margeff, np.r_[11.0928], rtol=1e-6)
assert_allclose(marg.margeff_se, np.r_[3.269015], rtol=1e-6)
def test_multinomial(self):
"""
Check the 2-class multinomial (nominal) GEE fit against
logistic regression.
"""
np.random.seed(34234)
endog = np.r_[0, 0, 0, 0, 1, 1, 1, 1]
exog = np.ones((8, 2))
exog[:, 1] = np.r_[1, 2, 1, 1, 2, 1, 2, 2]
groups = np.arange(8)
model = gee.NominalGEE(endog, exog, groups)
results = model.fit(cov_type='naive', start_params=[
3.295837, -2.197225])
logit_model = gee.GEE(endog, exog, groups,
family=families.Binomial())
logit_results = logit_model.fit(cov_type='naive')
assert_allclose(results.params, -logit_results.params, rtol=1e-5)
assert_allclose(results.bse, logit_results.bse, rtol=1e-5)
def test_weighted(self):
# Simple check where the answer can be computed by hand.
exog = np.ones(20)
weights = np.ones(20)
weights[0:10] = 2
endog = np.zeros(20)
endog[0:10] += 1
groups = np.kron(np.arange(10), np.r_[1, 1])
model = gee.GEE(endog, exog, groups, weights=weights)
result = model.fit()
assert_allclose(result.params, np.r_[2 / 3.])
# Comparison against stata using groups with different sizes.
weights = np.ones(20)
weights[10:] = 2
endog = np.r_[1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7, 6,
7, 8, 7, 8]
exog1 = np.r_[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4,
3, 3, 3, 3]
groups = np.r_[1, 1, 2, 2, 2, 2, 4, 4, 5, 5, 6, 6, 6, 6,
8, 8, 9, 9, 10, 10]
exog = np.column_stack((np.ones(20), exog1))
# Comparison using independence model
model = gee.GEE(endog, exog, groups, weights=weights,
cov_struct=cov_struct.Independence())
g = np.mean([2, 4, 2, 2, 4, 2, 2, 2])
fac = 20 / float(20 - g)
result = model.fit(ddof_scale=0, scaling_factor=fac)
assert_allclose(result.params, np.r_[1.247573, 1.436893], atol=1e-6)
assert_allclose(result.scale, 1.808576)
# Stata multiples robust SE by sqrt(N / (N - g)), where N is
# the total sample size and g is the average group size.
assert_allclose(result.bse, np.r_[0.895366, 0.3425498], atol=1e-5)
# Comparison using exchangeable model
# Smoke test for now
model = gee.GEE(endog, exog, groups, weights=weights,
cov_struct=cov_struct.Exchangeable())
result = model.fit(ddof_scale=0)
# This is in the release announcement for version 0.6.
def test_poisson_epil(self):
cur_dir = os.path.dirname(os.path.abspath(__file__))
fname = os.path.join(cur_dir, "results", "epil.csv")
data = pd.read_csv(fname)
fam = families.Poisson()
ind = cov_struct.Independence()
mod1 = gee.GEE.from_formula("y ~ age + trt + base", data["subject"],
data, cov_struct=ind, family=fam)
rslt1 = mod1.fit(cov_type='naive')
# Coefficients should agree with GLM
from statsmodels.genmod.generalized_linear_model import GLM
mod2 = GLM.from_formula("y ~ age + trt + base", data,
family=families.Poisson())
rslt2 = mod2.fit()
# don't use wrapper, asserts_xxx don't work
rslt1 = rslt1._results
rslt2 = rslt2._results
assert_allclose(rslt1.params, rslt2.params, rtol=1e-6, atol=1e-6)
assert_allclose(rslt1.bse, rslt2.bse, rtol=1e-6, atol=1e-6)
def test_missing(self):
# Test missing data handling for calling from the api. Missing
# data handling does not currently work for formulas.
np.random.seed(34234)
endog = np.random.normal(size=100)
exog = np.random.normal(size=(100, 3))
exog[:, 0] = 1
groups = np.kron(lrange(20), np.ones(5))
endog[0] = np.nan
endog[5:7] = np.nan
exog[10:12, 1] = np.nan
mod1 = gee.GEE(endog, exog, groups, missing='drop')
rslt1 = mod1.fit()
assert_almost_equal(len(mod1.endog), 95)
assert_almost_equal(np.asarray(mod1.exog.shape), np.r_[95, 3])
ii = np.isfinite(endog) & np.isfinite(exog).all(1)
mod2 = gee.GEE(endog[ii], exog[ii, :], groups[ii], missing='none')
rslt2 = mod2.fit()
assert_almost_equal(rslt1.params, rslt2.params)
assert_almost_equal(rslt1.bse, rslt2.bse)
def test_missing_formula(self):
# Test missing data handling for formulas.
np.random.seed(34234)
endog = np.random.normal(size=100)
exog1 = np.random.normal(size=100)
exog2 = np.random.normal(size=100)
exog3 = np.random.normal(size=100)
groups = np.kron(lrange(20), np.ones(5))
endog[0] = np.nan
endog[5:7] = np.nan
exog2[10:12] = np.nan
data0 = pd.DataFrame({"endog": endog, "exog1": exog1, "exog2": exog2,
"exog3": exog3, "groups": groups})
for k in 0, 1:
data = data0.copy()
kwargs = {}
if k == 1:
data["offset"] = 0
data["time"] = 0
kwargs["offset"] = "offset"
kwargs["time"] = "time"
mod1 = gee.GEE.from_formula("endog ~ exog1 + exog2 + exog3",
groups="groups", data=data,
missing='drop', **kwargs)
rslt1 = mod1.fit()
assert_almost_equal(len(mod1.endog), 95)
assert_almost_equal(np.asarray(mod1.exog.shape), np.r_[95, 4])
data = data.dropna()
kwargs = {}
if k == 1:
kwargs["offset"] = data["offset"]
kwargs["time"] = data["time"]
mod2 = gee.GEE.from_formula("endog ~ exog1 + exog2 + exog3",
groups=data["groups"], data=data,
missing='none', **kwargs)
rslt2 = mod2.fit()
assert_almost_equal(rslt1.params.values, rslt2.params.values)
assert_almost_equal(rslt1.bse.values, rslt2.bse.values)
def test_invalid_args(self):
for j in range(3):
for k1 in False, True:
for k2 in False, True:
p = [20, 20, 20]
p[j] = 18
endog = np.zeros(p[0])
exog = np.zeros((p[1], 2))
kwargs = {}
kwargs["groups"] = np.zeros(p[2])
if k1:
kwargs["exposure"] = np.zeros(18)
if k2:
kwargs["time"] = np.zeros(18)
with assert_raises(ValueError):
gee.GEE(endog, exog, **kwargs)
def test_default_time(self):
# Check that the time defaults work correctly.
endog, exog, group = load_data("gee_logistic_1.csv")
# Time values for the autoregressive model
T = np.zeros(len(endog))
idx = set(group)
for ii in idx:
jj = np.flatnonzero(group == ii)
T[jj] = lrange(len(jj))
family = families.Binomial()
va = cov_struct.Autoregressive()
md1 = gee.GEE(endog, exog, group, family=family, cov_struct=va)
mdf1 = md1.fit()
md2 = gee.GEE(endog, exog, group, time=T, family=family,
cov_struct=va)
mdf2 = md2.fit()
assert_almost_equal(mdf1.params, mdf2.params, decimal=6)
assert_almost_equal(mdf1.standard_errors(),
mdf2.standard_errors(), decimal=6)
def test_logistic(self):
# R code for comparing results:
# library(gee)
# Z = read.csv("results/gee_logistic_1.csv", header=FALSE)
# Y = Z[,2]
# Id = Z[,1]
# X1 = Z[,3]
# X2 = Z[,4]
# X3 = Z[,5]
# mi = gee(Y ~ X1 + X2 + X3, id=Id, family=binomial,
# corstr="independence")
# smi = summary(mi)
# u = coefficients(smi)
# cfi = paste(u[,1], collapse=",")
# sei = paste(u[,4], collapse=",")
# me = gee(Y ~ X1 + X2 + X3, id=Id, family=binomial,
# corstr="exchangeable")
# sme = summary(me)
# u = coefficients(sme)
# cfe = paste(u[,1], collapse=",")
# see = paste(u[,4], collapse=",")
# ma = gee(Y ~ X1 + X2 + X3, id=Id, family=binomial,
# corstr="AR-M")
# sma = summary(ma)
# u = coefficients(sma)
# cfa = paste(u[,1], collapse=",")
# sea = paste(u[,4], collapse=",")
# sprintf("cf = [[%s],[%s],[%s]]", cfi, cfe, cfa)
# sprintf("se = [[%s],[%s],[%s]]", sei, see, sea)
endog, exog, group = load_data("gee_logistic_1.csv")
# Time values for the autoregressive model
T = np.zeros(len(endog))
idx = set(group)
for ii in idx:
jj = np.flatnonzero(group == ii)
T[jj] = lrange(len(jj))
family = families.Binomial()
ve = cov_struct.Exchangeable()
vi = cov_struct.Independence()
va = cov_struct.Autoregressive()
# From R gee
cf = [[0.0167272965285882, 1.13038654425893,
-1.86896345082962, 1.09397608331333],
[0.0178982283915449, 1.13118798191788,
-1.86133518416017, 1.08944256230299],
[0.0109621937947958, 1.13226505028438,
-1.88278757333046, 1.09954623769449]]
se = [[0.127291720283049, 0.166725808326067,
0.192430061340865, 0.173141068839597],
[0.127045031730155, 0.165470678232842,
0.192052750030501, 0.173174779369249],
[0.127240302296444, 0.170554083928117,
0.191045527104503, 0.169776150974586]]
for j, v in enumerate((vi, ve, va)):
md = gee.GEE(endog, exog, group, T, family, v)
mdf = md.fit()
if id(v) != id(va):
assert_almost_equal(mdf.params, cf[j], decimal=6)
assert_almost_equal(mdf.standard_errors(), se[j],
decimal=6)
# Test with formulas
D = np.concatenate((endog[:, None], group[:, None], exog[:, 1:]),
axis=1)
D = pd.DataFrame(D)
D.columns = ["Y", "Id", ] + ["X%d" % (k + 1)
for k in range(exog.shape[1] - 1)]
for j, v in enumerate((vi, ve)):
md = gee.GEE.from_formula("Y ~ X1 + X2 + X3", "Id", D,
family=family, cov_struct=v)
mdf = md.fit()
assert_almost_equal(mdf.params, cf[j], decimal=6)
assert_almost_equal(mdf.standard_errors(), se[j],
decimal=6)
# Check for run-time exceptions in summary
# print(mdf.summary())
def test_autoregressive(self):
dep_params_true = [0, 0.589208623896, 0.559823804948]
params_true = [[1.08043787, 1.12709319, 0.90133927],
[0.9613677, 1.05826987, 0.90832055],
[1.05370439, 0.96084864, 0.93923374]]
np.random.seed(342837482)
num_group = 100
ar_param = 0.5
k = 3
ga = families.Gaussian()
for gsize in 1, 2, 3:
ix = np.arange(gsize)[:, None] - np.arange(gsize)[None, :]
ix = np.abs(ix)
cmat = ar_param ** ix
cmat_r = np.linalg.cholesky(cmat)
endog = []
exog = []
groups = []
for i in range(num_group):
x = np.random.normal(size=(gsize, k))
exog.append(x)
expval = x.sum(1)
errors = np.dot(cmat_r, np.random.normal(size=gsize))
endog.append(expval + errors)
groups.append(i * np.ones(gsize))
endog = np.concatenate(endog)
groups = np.concatenate(groups)
exog = np.concatenate(exog, axis=0)
ar = cov_struct.Autoregressive()
md = gee.GEE(endog, exog, groups, family=ga, cov_struct=ar)
mdf = md.fit()
assert_almost_equal(ar.dep_params, dep_params_true[gsize - 1])
assert_almost_equal(mdf.params, params_true[gsize - 1])
def test_post_estimation(self):
family = families.Gaussian()
endog, exog, group = load_data("gee_linear_1.csv")
ve = cov_struct.Exchangeable()
md = gee.GEE(endog, exog, group, None, family, ve)
mdf = md.fit()
assert_almost_equal(np.dot(exog, mdf.params),
mdf.fittedvalues)
assert_almost_equal(endog - np.dot(exog, mdf.params),
mdf.resid)
def test_scoretest(self):
# Regression tests
np.random.seed(6432)
n = 200 # Must be divisible by 4
exog = np.random.normal(size=(n, 4))
endog = exog[:, 0] + exog[:, 1] + exog[:, 2]
endog += 3 * np.random.normal(size=n)
group = np.kron(np.arange(n / 4), np.ones(4))
# Test under the null.
L = np.array([[1., -1, 0, 0]])
R = np.array([0., ])
family = families.Gaussian()
va = cov_struct.Independence()
mod1 = gee.GEE(endog, exog, group, family=family,
cov_struct=va, constraint=(L, R))
res1 = mod1.fit()
assert_almost_equal(res1.score_test()["statistic"],
1.08126334)
assert_almost_equal(res1.score_test()["p-value"],
0.2984151086)
# Test under the alternative.
L = np.array([[1., -1, 0, 0]])
R = np.array([1.0, ])
family = families.Gaussian()
va = cov_struct.Independence()
mod2 = gee.GEE(endog, exog, group, family=family,
cov_struct=va, constraint=(L, R))
res2 = mod2.fit()
assert_almost_equal(res2.score_test()["statistic"],
3.491110965)
assert_almost_equal(res2.score_test()["p-value"],
0.0616991659)
# Compare to Wald tests
exog = np.random.normal(size=(n, 2))
L = np.array([[1, -1]])
R = np.array([0.])
f = np.r_[1, -1]
for i in range(10):
endog = exog[:, 0] + (0.5 + i / 10.) * exog[:, 1] +\
np.random.normal(size=n)
family = families.Gaussian()
va = cov_struct.Independence()
mod0 = gee.GEE(endog, exog, group, family=family,
cov_struct=va)
rslt0 = mod0.fit()
family = families.Gaussian()
va = cov_struct.Independence()
mod1 = gee.GEE(endog, exog, group, family=family,
cov_struct=va, constraint=(L, R))
res1 = mod1.fit()
se = np.sqrt(np.dot(f, np.dot(rslt0.cov_params(), f)))
wald_z = np.dot(f, rslt0.params) / se
wald_p = 2 * norm.cdf(-np.abs(wald_z))
score_p = res1.score_test()["p-value"]
assert_array_less(np.abs(wald_p - score_p), 0.02)
@pytest.mark.parametrize("cov_struct", [cov_struct.Independence, cov_struct.Exchangeable])
def test_compare_score_test(self, cov_struct):
np.random.seed(6432)
n = 200 # Must be divisible by 4
exog = np.random.normal(size=(n, 4))
group = np.kron(np.arange(n / 4), np.ones(4))
exog_sub = exog[:, [0, 3]]
endog = exog_sub.sum(1) + 3 * np.random.normal(size=n)
L = np.asarray([[0, 1, 0, 0], [0, 0, 1, 0]])
R = np.zeros(2)
mod_lr = gee.GEE(endog, exog, group, constraint=(L, R),
cov_struct=cov_struct())
_ = mod_lr.fit()
mod_sub = gee.GEE(endog, exog_sub, group, cov_struct=cov_struct())
res_sub = mod_sub.fit()
for call_fit in [False, True]:
mod = gee.GEE(endog, exog, group, cov_struct=cov_struct())
if call_fit:
# Should work with or without fitting the parent model
mod.fit()
score_results = mod.compare_score_test(res_sub)
assert_almost_equal(score_results["statistic"],
mod_lr.score_test_results["statistic"])
assert_almost_equal(score_results["p-value"],
mod_lr.score_test_results["p-value"])
assert_almost_equal(score_results["df"],
mod_lr.score_test_results["df"])
def test_compare_score_test_warnings(self):
np.random.seed(6432)
n = 200 # Must be divisible by 4
exog = np.random.normal(size=(n, 4))
group = np.kron(np.arange(n / 4), np.ones(4))
exog_sub = exog[:, [0, 3]]
endog = exog_sub.sum(1) + 3 * np.random.normal(size=n)
# Mismatched cov_struct
with assert_warns(UserWarning):
mod_sub = gee.GEE(endog, exog_sub, group, cov_struct=cov_struct.Exchangeable())
res_sub = mod_sub.fit()
mod = gee.GEE(endog, exog, group, cov_struct=cov_struct.Independence())
_ = mod.compare_score_test(res_sub)
# Mismatched family
with assert_warns(UserWarning):
mod_sub = gee.GEE(endog, exog_sub, group, family=families.Gaussian())
res_sub = mod_sub.fit()
mod = gee.GEE(endog, exog, group, family=families.Poisson())
_ = mod.compare_score_test(res_sub)
# Mismatched size
with assert_raises(Exception):
mod_sub = gee.GEE(endog, exog_sub, group)
res_sub = mod_sub.fit()
mod = gee.GEE(endog[0:100], exog[:100, :], group[0:100])
_ = mod.compare_score_test(res_sub)
# Mismatched weights
with assert_warns(UserWarning):
w = np.random.uniform(size=n)
mod_sub = gee.GEE(endog, exog_sub, group, weights=w)
res_sub = mod_sub.fit()
mod = gee.GEE(endog, exog, group)
_ = mod.compare_score_test(res_sub)
# Parent and submodel are the same dimension
with pytest.warns(UserWarning):
w = np.random.uniform(size=n)
mod_sub = gee.GEE(endog, exog, group)
res_sub = mod_sub.fit()
mod = gee.GEE(endog, exog, group)
_ = mod.compare_score_test(res_sub)
def test_constraint_covtype(self):
# Test constraints with different cov types
np.random.seed(6432)
n = 200
exog = np.random.normal(size=(n, 4))
endog = exog[:, 0] + exog[:, 1] + exog[:, 2]
endog += 3 * np.random.normal(size=n)
group = np.kron(np.arange(n / 4), np.ones(4))
L = np.array([[1., -1, 0, 0]])
R = np.array([0., ])
family = families.Gaussian()
va = cov_struct.Independence()
for cov_type in "robust", "naive", "bias_reduced":
model = gee.GEE(endog, exog, group, family=family,
cov_struct=va, constraint=(L, R))
result = model.fit(cov_type=cov_type)
result.standard_errors(cov_type=cov_type)
assert_allclose(result.cov_robust.shape, np.r_[4, 4])
assert_allclose(result.cov_naive.shape, np.r_[4, 4])
if cov_type == "bias_reduced":
assert_allclose(result.cov_robust_bc.shape, np.r_[4, 4])
def test_linear(self):
# library(gee)
# Z = read.csv("results/gee_linear_1.csv", header=FALSE)
# Y = Z[,2]
# Id = Z[,1]
# X1 = Z[,3]
# X2 = Z[,4]
# X3 = Z[,5]
# mi = gee(Y ~ X1 + X2 + X3, id=Id, family=gaussian,
# corstr="independence", tol=1e-8, maxit=100)
# smi = summary(mi)
# u = coefficients(smi)
# cfi = paste(u[,1], collapse=",")
# sei = paste(u[,4], collapse=",")
# me = gee(Y ~ X1 + X2 + X3, id=Id, family=gaussian,
# corstr="exchangeable", tol=1e-8, maxit=100)
# sme = summary(me)
# u = coefficients(sme)
# cfe = paste(u[,1], collapse=",")
# see = paste(u[,4], collapse=",")
# sprintf("cf = [[%s],[%s]]", cfi, cfe)
# sprintf("se = [[%s],[%s]]", sei, see)
family = families.Gaussian()
endog, exog, group = load_data("gee_linear_1.csv")
vi = cov_struct.Independence()
ve = cov_struct.Exchangeable()
# From R gee
cf = [[-0.01850226507491, 0.81436304278962,
-1.56167635393184, 0.794239361055003],
[-0.0182920577154767, 0.814898414022467,
-1.56194040106201, 0.793499517527478]]
se = [[0.0440733554189401, 0.0479993639119261,
0.0496045952071308, 0.0479467597161284],
[0.0440369906460754, 0.0480069787567662,
0.049519758758187, 0.0479760443027526]]
for j, v in enumerate((vi, ve)):
md = gee.GEE(endog, exog, group, None, family, v)
mdf = md.fit()
assert_almost_equal(mdf.params, cf[j], decimal=10)
assert_almost_equal(mdf.standard_errors(), se[j],
decimal=10)
# Test with formulas
D = np.concatenate((endog[:, None], group[:, None], exog[:, 1:]),
axis=1)
D = pd.DataFrame(D)
D.columns = ["Y", "Id", ] + ["X%d" % (k + 1)
for k in range(exog.shape[1] - 1)]
for j, v in enumerate((vi, ve)):
md = gee.GEE.from_formula("Y ~ X1 + X2 + X3", "Id", D,
family=family, cov_struct=v)
mdf = md.fit()
assert_almost_equal(mdf.params, cf[j], decimal=10)
assert_almost_equal(mdf.standard_errors(), se[j],
decimal=10)
def test_linear_constrained(self):
family = families.Gaussian()
np.random.seed(34234)
exog = np.random.normal(size=(300, 4))
exog[:, 0] = 1
endog = np.dot(exog, np.r_[1, 1, 0, 0.2]) +\
np.random.normal(size=300)
group = np.kron(np.arange(100), np.r_[1, 1, 1])
vi = cov_struct.Independence()
ve = cov_struct.Exchangeable()
L = np.r_[[[0, 0, 0, 1]]]
R = np.r_[0, ]
for j, v in enumerate((vi, ve)):
md = gee.GEE(endog, exog, group, None, family, v,
constraint=(L, R))
mdf = md.fit()
assert_almost_equal(mdf.params[3], 0, decimal=10)
def test_nested_linear(self):
family = families.Gaussian()
endog, exog, group = load_data("gee_nested_linear_1.csv")
group_n = []
for i in range(endog.shape[0] // 10):
group_n.extend([0, ] * 5)
group_n.extend([1, ] * 5)
group_n = np.array(group_n)[:, None]
dp = cov_struct.Independence()
md = gee.GEE(endog, exog, group, None, family, dp)
mdf1 = md.fit()
# From statsmodels.GEE (not an independent test)
cf = np.r_[-0.1671073, 1.00467426, -2.01723004, 0.97297106]
se = np.r_[0.08629606, 0.04058653, 0.04067038, 0.03777989]
assert_almost_equal(mdf1.params, cf, decimal=6)
assert_almost_equal(mdf1.standard_errors(), se,
decimal=6)
ne = cov_struct.Nested()
md = gee.GEE(endog, exog, group, None, family, ne,
dep_data=group_n)
mdf2 = md.fit(start_params=mdf1.params)
# From statsmodels.GEE (not an independent test)
cf = np.r_[-0.16655319, 1.02183688, -2.00858719, 1.00101969]
se = np.r_[0.08632616, 0.02913582, 0.03114428, 0.02893991]
assert_almost_equal(mdf2.params, cf, decimal=6)
assert_almost_equal(mdf2.standard_errors(), se,
decimal=6)
smry = mdf2.cov_struct.summary()
assert_allclose(smry.Variance, np.r_[1.043878, 0.611656, 1.421205], atol=1e-5, rtol=1e-5)
def test_nested_pandas(self):
np.random.seed(4234)
n = 10000
# Outer groups
groups = np.kron(np.arange(n // 100), np.ones(100)).astype(np.int)
# Inner groups
groups1 = np.kron(np.arange(n // 50), np.ones(50)).astype(np.int)
groups2 = np.kron(np.arange(n // 10), np.ones(10)).astype(np.int)
# Group effects
groups_e = np.random.normal(size=n // 100)
groups1_e = 2 * np.random.normal(size=n // 50)
groups2_e = 3 * np.random.normal(size=n // 10)
y = groups_e[groups] + groups1_e[groups1] + groups2_e[groups2]
y += 0.5 * np.random.normal(size=n)
df = pd.DataFrame({"y": y, "TheGroups": groups, "groups1": groups1, "groups2": groups2})
model = gee.GEE.from_formula("y ~ 1", groups="TheGroups",
dep_data="0 + groups1 + groups2",
cov_struct=cov_struct.Nested(),
data=df)
result = model.fit()
# The true variances are 1, 4, 9, 0.25
smry = result.cov_struct.summary()
assert_allclose(smry.Variance, np.r_[1.437299, 4.421543, 8.905295, 0.258480], atol=1e-5, rtol=1e-5)
def test_ordinal(self):
family = families.Binomial()
endog, exog, groups = load_data("gee_ordinal_1.csv",
icept=False)
va = cov_struct.GlobalOddsRatio("ordinal")
mod = gee.OrdinalGEE(endog, exog, groups, None, family, va)
rslt = mod.fit()
# Regression test
cf = np.r_[1.09250002, 0.0217443, -0.39851092, -0.01812116,
0.03023969, 1.18258516, 0.01803453, -1.10203381]
assert_almost_equal(rslt.params, cf, decimal=5)
# Regression test
se = np.r_[0.10883461, 0.10330197, 0.11177088, 0.05486569,
0.05997153, 0.09168148, 0.05953324, 0.0853862]
assert_almost_equal(rslt.bse, se, decimal=5)
# Check that we get the correct results type
assert_equal(type(rslt), gee.OrdinalGEEResultsWrapper)
assert_equal(type(rslt._results), gee.OrdinalGEEResults)
@pytest.mark.smoke
def test_ordinal_formula(self):
np.random.seed(434)
n = 40
y = np.random.randint(0, 3, n)
groups = np.arange(n)
x1 = np.random.normal(size=n)
x2 = np.random.normal(size=n)
df = pd.DataFrame({"y": y, "groups": groups, "x1": x1, "x2": x2})
model = gee.OrdinalGEE.from_formula("y ~ 0 + x1 + x2", groups, data=df)
model.fit()
with warnings.catch_warnings():
warnings.simplefilter("ignore")
model = gee.NominalGEE.from_formula("y ~ 0 + x1 + x2", groups, data=df)
model.fit()
@pytest.mark.smoke
def test_ordinal_independence(self):
np.random.seed(434)
n = 40
y = np.random.randint(0, 3, n)
groups = np.kron(np.arange(n / 2), np.r_[1, 1])
x = np.random.normal(size=(n, 1))
odi = cov_struct.OrdinalIndependence()
model1 = gee.OrdinalGEE(y, x, groups, cov_struct=odi)
model1.fit()
@pytest.mark.smoke
def test_nominal_independence(self):
np.random.seed(434)
n = 40
y = np.random.randint(0, 3, n)
groups = np.kron(np.arange(n / 2), np.r_[1, 1])
x = np.random.normal(size=(n, 1))
with warnings.catch_warnings():
warnings.simplefilter("ignore")
nmi = cov_struct.NominalIndependence()
model1 = gee.NominalGEE(y, x, groups, cov_struct=nmi)
model1.fit()
@pytest.mark.smoke
@pytest.mark.matplotlib
def test_ordinal_plot(self, close_figures):
family = families.Binomial()
endog, exog, groups = load_data("gee_ordinal_1.csv",
icept=False)
va = cov_struct.GlobalOddsRatio("ordinal")
mod = gee.OrdinalGEE(endog, exog, groups, None, family, va)
rslt = mod.fit()
fig = rslt.plot_distribution()
assert_equal(isinstance(fig, plt.Figure), True)
def test_nominal(self):
endog, exog, groups = load_data("gee_nominal_1.csv",
icept=False)
# Test with independence correlation
va = cov_struct.Independence()
mod1 = gee.NominalGEE(endog, exog, groups, cov_struct=va)
rslt1 = mod1.fit()
# Regression test
cf1 = np.r_[0.450009, 0.451959, -0.918825, -0.468266]
se1 = np.r_[0.08915936, 0.07005046, 0.12198139, 0.08281258]
assert_allclose(rslt1.params, cf1, rtol=1e-5, atol=1e-5)
assert_allclose(rslt1.standard_errors(), se1, rtol=1e-5, atol=1e-5)
# Test with global odds ratio dependence
va = cov_struct.GlobalOddsRatio("nominal")
mod2 = gee.NominalGEE(endog, exog, groups, cov_struct=va)
rslt2 = mod2.fit(start_params=rslt1.params)
# Regression test
cf2 = np.r_[0.455365, 0.415334, -0.916589, -0.502116]
se2 = np.r_[0.08803614, 0.06628179, 0.12259726, 0.08411064]
assert_allclose(rslt2.params, cf2, rtol=1e-5, atol=1e-5)
assert_allclose(rslt2.standard_errors(), se2, rtol=1e-5, atol=1e-5)
# Make sure we get the correct results type
assert_equal(type(rslt1), gee.NominalGEEResultsWrapper)
assert_equal(type(rslt1._results), gee.NominalGEEResults)