-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path03-inf.Rmd
More file actions
2077 lines (1582 loc) · 77.1 KB
/
03-inf.Rmd
File metadata and controls
2077 lines (1582 loc) · 77.1 KB
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
# Monte Carlo Methods in Inference
## Parametric Bootstrap
In this setting, we know distribution of $X$. We can freely generate from this distribution.
```{r paramboot, echo=FALSE, fig.cap="Parametric bootstrap"}
knitr::include_graphics("images/mcboot.png")
```
See Figure \@ref(fig:paramboot). From the "true" distribution, we can generate multiple samples. From each sample estimator can be computed. Then we can check these multiple estimates. Multiple estimates are close to motivation of estimator, so it helps exploring statistical inference with simple steps.
```{r}
mc_data <- function(rand, N = 10000, M = 1000, char = "s", ...) {
data.table(
x = rand(n = N * M, ...),
sam = gl(M, N, labels = paste0("s", 1:M))
)
}
```
## Monte Carlo Methods for Estimation
```{example, quanint, name = "Any quantity of interest"}
Suppose that $X_1, X_2 \iid N(0, 1)$. We want to estimate
$$\theta = E\lvert X_1 - X_2 \rvert$$
```
### Empirical distribution
\begin{algorithm}[H] \label{alg:algx1x2}
\SetAlgoLined
\SetKwInOut{Input}{input}
\SetKwInOut{Output}{output}
\Input{distribution $f$}
\For{$m \leftarrow 1$ \KwTo $M$}{
Generate $(X_1^{(m)}, X_2^{(m)}) \iid N(0, 1)$\;
Compute $\hat\theta^{(m)} = \lvert X_1^{(m)} - X_2^{(m)} \rvert$\;
}
Draw a histogram\;
\Output{$\bar{\hat\theta} = \frac{1}{M} \sum\limits_{m = 1}^M\hat\theta_m^{(m)}, \{ \hat\theta^{(1)}, \ldots, \hat\theta^{(M)} \}$}
\caption{Empirical distribution of $\hat\theta$}
\end{algorithm}
```{r}
basicmc <-
mc_data(rnorm, N = 2)[,
xname := gl(2, 1, length = 2000, labels = c("x1", "x2"))] %>%
dcast(sam ~ xname, value.var = "x") %>%
.[,
.(that = mean(abs(x1 - x2))),
by = sam]
```
```{r}
basicmc[,
.(est = mean(that))]
```
```{r absx12, fig.cap="Empirical distribution of $\\hat\\theta$ for $\\lvert X_1 - X_2 \\rvert$"}
basicmc %>%
ggplot(aes(x = that)) +
geom_histogram(bins = 30, col = gg_hcl(1), alpha = .7) +
xlab(expression(theta))
```
### Standard error
In Algorithm $\ref{alg:algx1x2}$, we can get standard error by just calculating standard deviation of
$$\{ \hat\theta^{(1)}, \ldots, \hat\theta^{(M)} \}$$
\begin{algorithm}[H] \label{alg:algmcse}
\SetAlgoLined
\SetKwInOut{Input}{input}
\SetKwInOut{Output}{output}
\Input{distribution $f$}
\For{$m \leftarrow 1$ \KwTo $M$}{
Generate $(X_1^{(m)}, X_2^{(m)}) \iid N(0, 1)$\;
Compute $\hat\theta^{(m)} = \lvert X_1^{(m)} - X_2^{(m)} \rvert$\;
}
$\bar{\hat\theta} = \frac{1}{M} \sum\limits_{m = 1}^M\hat\theta_m^{(m)}$\;
$\widehat{SE}(\hat\theta) = \sqrt{\frac{1}{M - 1}\sum\limits_{m = 1}^M(\hat\theta^{(m)} - \bar{\hat\theta})}$\;
\Output{$\widehat{SE}(\hat\theta)$}
\caption{Standard error of $\hat\theta$}
\end{algorithm}
```{r}
basicmc[,
.(se = sd(that))]
```
### Mean squared error
$MSE$ is used when comparing several estimators.
```{definition, mse, name = "Mean squared error"}
$$MSE(\hat\theta) := E(\hat\theta - \theta)^2$$
```
To know $MSE$, however, we should compute expectation. Some of them might be complicated even though we know true distribution. As the last chapter, we can apply Monte carlo method.
```{example, trim, name = "MSE of a trimmed mean"}
Suppose that $X_1, \ldots, X_n \iid N(2, 1)$. Consider three estimators for $\mu = 2$.
\begin{enumerate}
\item mean $\overline{X}$
\item median $\tilde{X}$
\item $k$th trimmed mean $\overline{X}_{[-k]}$
\end{enumerate}
```
\begin{algorithm}[H] \label{alg:algmse}
\SetAlgoLined
\SetKwInOut{Input}{input}
\SetKwInOut{Output}{output}
\Input{distribution $f$}
\For{$m \leftarrow 1$ \KwTo $M$}{
Generate $(X_1^{(m)}, \ldots, X_N^{(m)}) \iid N(2, 1)$\;
Sort $(X_1^{(m)}, \ldots, X_N^{(m)})$ in increasing order, i.e. $(X_{(1)}^{(m)}, \ldots, X_{(N)}^{(m)})$\;
Mean $\overline{X}^{(m)} = \frac{1}{N}\sum\limits_{i = 1}^N X_i^{(m)}$\;
Median $\tilde{X}^{(m)} = \begin{cases} X_{\frac{N}{2} + 1}^{(m)} & N \:\text{odd} \\ \frac{X_{\frac{N}{2}}^{(m)} + X_{\frac{N}{2} + 1}^{(m)}}{2} & N \:\text{even} \end{cases}$\;
$k$th trimmed mean $\overline{X}_{[-k]}^{(m)} = \frac{1}{N - 2k}\sum\limits_{i = k + 1}^{n - k}X_{(i)}^{(m)}$
}
$\widehat{MSE}(\overline{X}) = \frac{1}{M} \sum\limits_{m = 1}^M (\overline{X}^{(m)} - 2)^2$\;
$\widehat{MSE}(\tilde{X}) = \frac{1}{M} \sum\limits_{m = 1}^M (\tilde{X}^{(m)} - 2)^2$\;
$\widehat{MSE}(\overline{X}_{[-k]}) = \frac{1}{M} \sum\limits_{m = 1}^M (\overline{X}_{[-k]}^{(m)} - 2)^2$\;
\Output{$\widehat{MSE}(\overline{X}), \widehat{MSE}(\tilde{X}), \:\text{and}\: \widehat{MSE}(\overline{X}_{[-k]})$}
\caption{MSE of mean, median, and $k$th trimmed mean}
\end{algorithm}
```{r}
trim <- function(x, k = 1) {
n <- length(x)
x <- sort(x)
sum(x[(k + 1):(n - k)]) / (n - 2 * k)
}
#--------------------------------------
mu_list <- function(x, k) {
list(mean = mean(x), median = median(x), trim = trim(x, k))
}
```
Try $k = 1$.
```{r}
(trim_mc <-
mc_data(rnorm, mean = 2, sd = 1)[,
unlist(lapply(.SD, mu_list, k = 1)) %>% as.list,
by = sam])
```
```{r meanemp, fig.cap="Empirical distribution of each estimator for $\\mu = 2$"}
trim_mc %>%
melt(id.vars = "sam", variable.name = "hat") %>%
ggplot(aes(x = value, fill = hat)) +
geom_histogram(bins = 30, alpha = .3, position = "identity") +
xlab(expression(mu)) +
geom_vline(xintercept = 2, col = I("red")) +
scale_fill_discrete(
name = "Estimates",
labels = c("Mean", "Median", "Trimmed")
)
```
Here, median shows the largest standard error.
```{r}
trim_mc[,
lapply(.SD, sd),
.SDcols = -"sam"]
```
Now try various $k$ for trimmed mean.
```{r}
mse_list <- function(x, k) {
list(mse = mean((x - 2)^2), se = sd(x))
}
#-----------------------------------------
trim_mse <-
mc_data(rnorm, mean = 2, sd = 1)[,
lapply(.SD, function(x) {
sapply(0:9, function(k) {
trim(x = x, k = k)
})
}) %>%
unlist() %>%
as.list(),
by = sam][,
lapply(.SD, mse_list) %>%
unlist() %>%
as.list(),
.SDcols = -"sam"]
```
```{r}
trim_mse %>%
transpose() %>%
.[,
`:=`(
k = rep(0:9, each = 2),
hat = gl(2, k = 1, length = 2 * 10, labels = c("mse", "se"))
)] %>%
dcast(k ~ hat, value.var = "V1")
```
## Confidence interval
Remember the meaning of 95% confidence interval. *If we have 100 samples and construct confidence interval in each sample, 95 intervals would include true parameter*. In this Monte Carlo setting, we know true population distribution, so we can generate multiple samples. Thus, we can reproduce this confidence interval situation.
### Empirical confidence interval
See one of histograms of Figure \@ref(fig:meanemp). Estimates are sorted. Calculating the upper and lower quantiles would give values close to confidence interval. See Figure \@ref(fig:absx12). While the former show symmetric distribution, this is not. 0.25 and 0.975 quantile might be inappropriate. In this case, we should pick the *shortest interval with 95%*. Best critical region leads to the shortest length of CI given $\alpha$, so we are finding this one.
\begin{algorithm}[H] \label{alg:algempci}
\SetAlgoLined
\SetKwInOut{Input}{input}
\SetKwInOut{Output}{output}
\Input{distribution $f$}
\For{$m \leftarrow 1$ \KwTo $M$}{
Generate $X_1^{(m)}, \ldots, X_n^{(m)} \iid f$\;
Compute $\hat\theta^{(m)} = \hat\theta(\mathbf{\mathbf{X}^{(m)}})$\;
}
\eIf{Distribution of $\{ \hat\theta^{(m)} \}_1^M$ symmetric}{
Sort $\{ \hat\theta^{(1)}, \ldots, \hat\theta^{(M)} \}$ in decreasing order, i.e. $\{ \hat\theta_{(1)}^{(1)}, \ldots, \hat\theta_{(M)}^{(M)} \}$\;
Compute $LB= \frac{\alpha}{2} \:\text{sample quantile}$ and $UB= 1 - \frac{\alpha}{2} \:\text{sample quantile}$\;
}{
\ForEach{$lb < 0.05$ with $ub - lb = 1 - \alpha$}{
Candidate interval $(lb, ub)$\;
calculate length $l_i = ub - lb$\;
}
$(LB, UB)$: pick up the interval with the smallest length $l_i$\;
}
\Output{$(LB, UB)$}
\caption{Empirical confidence interval by Monte Carlo method}
\end{algorithm}
### Empirical confidence level
On the contrary, we can estiamte confidence level given confidence interval.
```{example, civar, name = "Confidence interval for variance"}
If $X_1, \ldots, X_n \iid N(\mu, \sigma^2)$, then
$$T = \frac{(n - 1)S^2}{\sigma^2} \sim \chi^2(n - 1)$$
Thus, $100(1 - \alpha)\%$ confidence interval is given by
$$(0, \frac{(n -1)S^2}{\chi^2_{\alpha}(n - 1)})$$
```
For each MC sample, compute confidence interval. Just check if *known true parameter* is in the interval. Its proportion becomes the confidence level. It is simpler that estimate confidence interval itself.
\begin{algorithm}[H] \label{alg:algcilev}
\SetAlgoLined
\SetKwInOut{Input}{input}
\SetKwInOut{Output}{output}
\Input{distribution $f$ with parameter $\theta$}
\For{$m \leftarrow 1$ \KwTo $M$}{
Generate $X_1^{(m)}, \ldots, X_n^{(m)} \iid f$\;
Compute the confidence interval $C_m$\;
Compute $Y_j = I(\theta \in C_m)$, i.e. whether $\theta$ is in the CI\;
}
Empirical confidence level $\overline{Y} = \sum\limits_{m = 1}^M Y_m$\; \label{alg:cilevlast}
\Output{$\overline{Y}$}
\caption{Empirical confidence level by Monte Carlo method}
\end{algorithm}
Let $\mu = 0$, $\sigma = 2$, $N = 20$, and let $M = 1000$.
```{r}
ci_var <- function(x, variance, alpha) {
n <- length(x)
s2 <- var(x)
(n - 1) * s2 / qchisq(alpha, df = n - 1) > variance
}
#---------------------------
ci_lev <-
mc_data(rnorm, N = 20, M = 1000, mean = 0, sd = 2)[,
.(hat = mean(ci_var(x, variance = 4, alpha = .05))),
by = sam]
```
```{r ciin, fig.cap="Proportion of $\\sigma^2$ in confidence intervals"}
ci_lev[,
.N,
by = hat][,
proportion := N / sum(N)] %>%
ggplot(aes(x = hat, y = proportion, fill = factor(hat))) +
geom_bar(stat = "identity") +
scale_fill_discrete(
name = "CI",
labels = c("out", "in")
) +
xlab(expression(y))
```
This leads to empirical confidence level, i.e. *sample proportion*. Just follow the last step $\ref{alg:cilevlast}$ of Algorithm $\ref{alg:algcilev}$.
```{r}
(ci_lev <-
ci_lev[,
.(level = mean(hat))])
```
It is very close to $0.95$. One of advantages of simulation study is we can assume various situation. For example, *violation of Gausiannity*.
```{example, nonnormal, name = "Violation of Normal distribution assumption"}
Refer to Example \@ref(exm:civar). This has assumed that $X_i \iid N(\mu = 2, \sigma^2 = 4)$. What if not? For instance,
$$X_1, \ldots, X_n \iid \chi^2(df = 2)$$
```
Just change random numbers.
```{r}
ci_lev2 <-
mc_data(rchisq, N = 20, M = 1000, df = 2)[,
.(hat = mean(ci_var(x, variance = 4, alpha = .05))),
by = sam][,
.(non_normal = mean(hat))]
```
```{r emlevpop, echo=FALSE}
cbind(ci_lev, ci_lev2) %>%
knitr::kable(col.names = c("Normal", "Chisq"), caption = "Empirical confidence level for each population", longtable = TRUE)
```
From Table \@ref(tab:emlevpop), we found that *non-normality lowers confidence level* from `r as.numeric(ci_lev)` to `r as.numeric(ci_lev2)`.
## Hypothesis tests
Using MC method, we have done point estimation and interval estimation. Now consider *hypothesis testing*.
$$H_0: \theta \in \Theta_0 \qquad \text{vs} \qquad H_1: \theta \in \Theta_1$$
where $\{ \Theta_0, \Theta_1 \}$ is a partition of the parameter space $\Theta$. First of all, we have *test statistic*
$$T(\mathbf{X}) \hsim f$$
and $f$ is called *null distribution*. Given observed data, we compute this test statistic $T_0$. Where $T_0$ is located in the null distribution $f$ decides whether we reject or accept $H_0$. If $T_0$ is very far from the middle, we can say that the realized data set is very rare event under $H_0$. In this case, we reject $H_0$. Otherwise, accept it. This is why we compute the tail probability, p-value.
### Empirical p-value
```{r, include=FALSE}
xexp <- c(1.77, 0.78, 0.02, 0.18, 1.34, 0.15, 2.28, 0.65, 0.55, 0.46, 2.40)
```
```{example, exptest}
Suppose that $X_1, \ldots, X_{10} \iid Exp(\lambda = 1)$, which are observed as follows
$$`r xexp`$$
Let $\theta = E(X) = \frac{1}{\lambda}$.
$$H_0: \theta = 0.5 \qquad \text{vs} \qquad H_1: \theta > 0.5$$
Test using $T = \frac{\overline{X} - \theta_0}{S / \sqrt{n}}$ statistic.
```
Before looking at p-value, briefly look at *empirical null distribution* of test statistic.
```{r expemp, fig.cap="Emprirical Null Distribution"}
mc_data(rexp, rate = 2)[,
.(tstat = t.test(x, mu = .5)$statistic),
by = sam] %>%
ggplot(aes(x = tstat)) +
geom_histogram(bins = 30, col = gg_hcl(1), alpha = .7) +
geom_vline(xintercept = t.test(xexp, mu = .5)$statistic, col = I("red")) + # xexp: observed data
geom_vline(xintercept = -t.test(xexp, mu = .5)$statistic, col = I("red")) +
xlab("T")
```
By proceeding the similar way, we can get empirical distribution of test statistics. Some are out of observed $T_0$, some are not. Motivation is that we just count these. Proportion of these would estimate p-value. Recap what p-value is.
```{definition, pval, name = "p-value"}
Let $T$ be test statistic and let $T_0$ be observed test statistic given data. Then p-value is
$$
p-value := \begin{cases}
P(\lvert T \rvert \ge T_0 \mid H_0) & \text{both sided} \\
P(T \ge T_0 \mid H_0) & \text{one sided} \\
P(T \le T_0 \mid H_0) & \text{one sided}
\end{cases}
$$
```
Denote that p-value is probability. So in MC setting, we can estimate this by computing *sample mean of identity function*.
```{lemma, emppval, name = "Empirical p-value"}
Let $T_0$ be observed test statistic and let $\{ T_1, \ldots, T_M \}$ be test statistic computed in each MC sample.
$$
\text{Empirical p-value} = \begin{cases}
\frac{\Big\lvert \{ T_j : (T_j > \lvert T_0 \rvert) \:\text{or}\: (T_j < -\lvert T_0 \rvert) \} \Big\rvert}{M} & \text{both-sided} \\
\frac{\Big\lvert \{ T_j : (T_j > T_0 ) \} \Big\rvert}{M} \:\text{or}\: \frac{\Big\lvert \{ T_j : (T_j < T_0 ) \} \Big\rvert}{M} & \text{one-sided}
\end{cases}
$$
```
\begin{algorithm}[H] \label{alg:algpval}
\SetAlgoLined
\SetKwInOut{Input}{input}
\SetKwInOut{Output}{output}
\Input{Given observed data, compute $T_0$}
\For{$m \leftarrow 1$ \KwTo $M$}{
Generate $X_1^{(m)}, \ldots, X_n^{(m)} \hsim f$\;
Compute $T_m(\mathbf{X}^{(m)})$\;
}
Empirical p-value $\hat{p} = \begin{cases} \frac{\Big\lvert \{ T_j : (T_j > \lvert T_0 \rvert) \:\text{or}\: (T_j < -\lvert T_0 \rvert) \} \Big\rvert}{M} & \text{both-sided} \\ \frac{\Big\lvert \{ T_j : (T_j > T_0 ) \} \Big\rvert}{M} \:\text{or}\: \frac{\Big\lvert \{ T_j : (T_j < T_0 ) \} \Big\rvert}{M} & \text{one-sided} \end{cases}$\; \label{alg:empp}
\Output{$\hat{p}$}
\caption{Empirical p-value by Monte Carlo method}
\end{algorithm}
Go back to Example \@ref(exm:exptest). Only left is computing $\ref{alg:empp}$ of Algorighm $\ref{alg:algpval}$. (Denote that `xexp` in the code is vector object of observed data).
```{r}
(tt_exp <-
mc_data(rexp, rate = 2)[,
.(tstat = t.test(x, mu = .5)$statistic),
by = sam][,
.(pval = mean(tstat > abs(t.test(xexp, mu = .5)$statistic)))])
```
It is smaller that `0.05`, so we reject $H_0$.
### Comparing several tests
MC method would be used in comparing tests rather than conducting test itself. By generating random number, we can evaluate tests.
$$H_0: \theta \in \Theta_0 \qquad \text{vs} \qquad H_1: \theta \in \Theta_1$$
As mentioned earlier, $\{ \Theta_0, \Theta_1 \}$ is a partition of the parameter space $\Theta$. For this test, we can perform several tests. Test method 1, test method 2, et cetera. All these methods produce error, but these errors might be different. So we try to compare this.
|what is true|accept $H_0$|reject $H_0$|
|:----------:|:----------:|:----------:|
| $H_0$ | correct decision | *Type I error* |
| $H_1$ | *Type II Error* | correct decision |
In most tests, we aims to reject $H_0$. By rejecting it, we can evidently say that $H_0$ is not true. In this sense, we treat type I error more importantly that type II error in general. Test strategy becomes to control type I error probability first and then lower type II error probabilty.
```{definition, bpower, name = "Power function"}
Let $\theta \in \Theta$ be a parameter of a test.
$$\beta(\theta) := P(\text{reject}\: H_0 \mid \theta)$$
```
With this power function, each type I error and type II error probability is given.
```{lemma, typeerr, name = "typeerr"}
\begin{enumerate}
\item $P(\text{Type I error}) = \beta(\theta_0), \quad \theta_0 \in \Theta_0$
\item Power $\beta(\theta_1) = 1 - P(\text{Type II error}), \quad \theta_1 \in \Theta_1$
\end{enumerate}
```
Following our test strategy, fixing $P(\text{Type I error})$ and maximizing $\beta(\theta_1)$, we construct following test.
```{definition, sizetest, name = "Size $\\alpha$ Test"}
A test with $\beta(\theta)$ is called size $\alpha$ test if and only if
$$\alpha := \sup_{\theta \in \Theta_0} \beta(\theta), \quad 0 \le \alpha \le 1$$
```
```{r sizealpha, echo=FALSE, fig.cap="Size $\\alpha$ Test"}
bcurve <- function(x) {
exp(x) / (1 + exp(x))
}
#-----------------------
tibble(x = seq(-6, 6, by = .01)) %>%
mutate(
y = bcurve(x),
hyp = x <= -3
) %>%
ggplot(aes(x = x)) +
geom_line(aes(y = y, colour = hyp, group = 1)) +
geom_segment(
aes(x = -3, y = bcurve(-3), xend = -6, yend = bcurve(-3)),
arrow = arrow(length = unit(.2, "cm")),
col = I("red"),
alpha = .5
) +
annotate(geom = "text", x = -6.3, y = bcurve(-3), label = "alpha", parse = TRUE) +
scale_colour_discrete(
name = "Hypothesis",
labels = c(expression(Theta[1]), expression(Theta[0]))
) +
theme(axis.text.x = element_blank()) +
labs(
x = expression(theta),
y = element_blank()
)
```
Then how to compare tests? Look at the following example. Three columns of the middle part are type I error rate.
|test methods| $\alpha = 0.01$ | $\alpha = 0.05$ | $\alpha = 0.01$ | Power |
|:----------:|:---------------:|:---------------:|:---------------:|:-----:|
| Test 1 | 0.09 | 0.04 | 0.01 | 0.7 |
| Test 2 | 0.11 | 0.06 | 0.01 | 0.65 |
| Test 3 | 0.15 | 0.07 | 0.02 | 0.9 |
Here, we will choose **Test 1**.
1. $\text{Type I error rate} \approx \alpha$
- before looking at power, this should be satisfied.
- So Test 3 is excluded
2. Larger power
- Thus, we select Test 1.
### Empirical type-I error rate
Recall Lemma \@ref(lem:typeerr). As in p-value, we just compute sample proportion for each type I error rate and power under null and alternative distribution.
```{lemma, testnull}
Consider $H_0: \theta \in \Theta_0 \qquad \text{vs} \qquad H_1: \theta \in \Theta_1$.
Define $I(\mathbf{X})$ by
$$
I(\mathbf{X}) = \begin{cases}
1 & H_0 \:\text{is rejected} \mid H_0 \\
0 & otherwise
\end{cases}
$$
For each MC sample, compute this statistic $I_m = I(\mathbf{X}^{m})$. Then empirical type I error rate can be computed as
$$\frac{1}{M}\sum_{m = 1}^M I_m$$
```
\begin{algorithm}[H] \label{alg:algtype1}
\SetAlgoLined
\SetKwInOut{Input}{input}
\SetKwInOut{Output}{output}
\Input{$H_0: \theta \in \Theta_0 \quad \text{vs} \quad H_1: \theta \in \Theta_1$}
\For{$m \leftarrow 1$ \KwTo $M$}{
Generate $X_1^{(m)}, \ldots, X_n^{(m)} \hsim f$\; \label{alg:gentype1}
Compute $T_m(\mathbf{X}^{(m)})$\;
Compute $I_m = \begin{cases} 1 & H_0 \:\text{is rejected} \mid H_0 \\ 0 & \text{otherwise} \end{cases}$\;
}
Empirical Type I error rate $\hat\alpha = \frac{1}{M}\sum\limits_{m = 1}^M I_m$\;
\Output{compare $\hat\alpha$ with $\alpha$}
\caption{Empirical type I error rate by Monte Carlo method}
\end{algorithm}
```{example, ttest, name = "Testing normal mean"}
Suppose that $X_1, \ldots, X_{20} \iid N(\mu, \sigma^2 = 100)$. Test
$$H_0: \mu = 500 \qquad \text{vs} \qquad H_1: \mu > 500$$
\begin{enumerate}
\item $Z$-test: $Z = \frac{\overline{X} - 500}{\sigma^2 / \sqrt{20}} \hsim N(0, 1)$
\item $t$-test: $T = \frac{\overline{X} - 500}{S / \sqrt{20}} \hsim t(20 - 1)$
\end{enumerate}
```
```{r}
test_list <- function(x, mu, sig, a = .05) {
n <- length(x)
xbar <- mean(x) - mu
list(
z = xbar / (sig / sqrt(n)) > qnorm(a, lower.tail = FALSE),
t = xbar / (sd(x) / sqrt(n)) > qt(a, df = n - 1, lower.tail = FALSE)
)
}
#--------------------
err_mc <-
mc_data(rnorm, N = 20, mean = 500, sd = 10)[,
lapply(.SD, test_list, mu = 500, sig = 10) %>%
unlist() %>%
as.list(),
by = sam][,
lapply(.SD, mean),
.SDcols = -"sam"]
```
```{r errmc, echo=FALSE}
knitr::kable(err_mc, col.names = c("Z-test", "T-test"), caption = "Empirical Type I error for Z and T")
```
Both test have Type I error close to $\alpha$, but $Z$-test seems bit better.
### Empirical power
Next step is power. See Figure \@ref(fig:sizealpha). Power is different in that this is computed in *alternative distribution, not null distribution*.
$$\beta(\theta_1) = P(\text{reject}\: H_0 \mid \theta_1 \in \Theta_1)$$
```{lemma, testalt}
Consider $H_0: \theta \in \Theta_0 \qquad \text{vs} \qquad H_1: \theta \in \Theta_1$.
Define $I(\mathbf{X})$ by
$$
I(\mathbf{X}) = \begin{cases}
1 & H_0 \:\text{is rejected} \mid H_1 \\
0 & otherwise
\end{cases}
$$
For each MC sample, compute this statistic $I_m = I(\mathbf{X}^{m})$. Then empirical power can be computed as
$$\frac{1}{M}\sum_{m = 1}^M I_m$$
```
Process will be same but we test under $H_1$. However, this makes a lot difference due to structure of each hypothesis. In many cases, $H_0$ is simple, i.e. $\mu = 500$. In $\ref{alg:gentype1}$ of Algorithm $\ref{alg:algtype1}$, we can consider only $N(\mu = 500, 100)$. Since $\Theta_0$ and $\Theta_1$ form partition, alternative hypothesis usually is not simple. In this example, $\mu > 500$. We cannot specify one distribution for alternatrive. How to deal with this?
Trying many points for $\mu_1 \in \Theta_1 = \{ \mu : \mu > 500 \}$ might be possible. Our goal is finding larger power. So *find test with larger power for all points in* $\Theta_1$.
```{r powercomp, echo=FALSE, fig.cap="Comparing power between two test methods"}
bcurve <- function(x) {
exp(x) / (1 + exp(x))
}
bcurve2 <- function(x) {
exp(x) / (1 + exp(x - .5))
}
#-----------------------
tibble(x = seq(-6, 6, by = .01)) %>%
mutate(
y = bcurve(x),
y2 = bcurve2(x),
hyp = x <= -3
) %>%
ggplot(aes(x = x)) +
geom_line(aes(y = y, colour = hyp, group = 1)) +
geom_line(aes(y = y2, colour = hyp, group = 1)) +
geom_segment(
aes(x = -3, y = bcurve(-3), xend = -6, yend = bcurve(-3)),
arrow = arrow(length = unit(.2, "cm")),
col = I("red"),
alpha = .5
) +
annotate(geom = "text", x = -6.3, y = bcurve(-3), label = "alpha", parse = TRUE) +
scale_colour_discrete(
name = "Hypothesis",
labels = c(expression(Theta[1]), expression(Theta[0]))
) +
theme(axis.text.x = element_blank()) +
labs(
x = expression(theta),
y = element_blank()
)
```
See Figure \@ref(fig:powercomp). One test method has higher $\beta(\theta)$ function curve in $\Theta_1$. This test is *powerful than the other*. We would choose this test in this step. So what we have to do is choose some points $\theta_1 \in \Theta_1$, and draw the power curve.
\begin{algorithm}[H] \label{alg:algpower}
\SetAlgoLined
\SetKwInOut{Input}{input}
\SetKwInOut{Output}{output}
\Input{$H_0: \theta \in \Theta_0 \quad \text{vs} \quad H_1: \theta \in \Theta_1$}
\ForEach{$\theta_1 \in \Theta_1$}{
\For{$m \leftarrow 1$ \KwTo $M$}{
Generate $X_1^{(m)}, \ldots, X_n^{(m)} \hsim f$\;
Compute $T_m(\mathbf{X}^{(m)})$\;
Compute $I_m = \begin{cases} 1 & H_0 \:\text{is rejected} \mid H_1 \\ 0 & \text{otherwise} \end{cases}$\;
}
Empirical power $\hat\beta = \frac{1}{M}\sum\limits_{m = 1}^M I_m$\;
}
Draw a power curve $\hat\beta$ against $\theta_1$
\Output{curve and $\{ \hat\beta \}$}
\caption{Empirical power by Monte Carlo method}
\end{algorithm}
In fact, we can try every $\theta \in \Theta$ and *draw entire power curve*. Refer to Example \@ref(exm:ttest).
<!-- ```{r, eval=FALSE} -->
<!-- library(foreach) -->
<!-- ``` -->
<!-- ```{r} -->
<!-- (pw_mc <- -->
<!-- foreach(mu1 = seq(450, 650, by = 10), .combine = rbind) %do% { -->
<!-- mc_data(rnorm, N = 20, mean = mu1, sd = 10)[, -->
<!-- h1 := mu1] -->
<!-- }) -->
<!-- ``` -->
```{r}
pw_mc <-
lapply(seq(450, 650, by = 10), function(mu) {
mc_data(rnorm, N = 20, mean = mu, sd = 10)[,
h1 := mu]
})
pw_mc <- rbindlist(pw_mc)
```
One column is added from previous process. This is group for $H_1$. So we should specify `by = .(h1, sam)`.
```{r}
pw_mc <-
pw_mc[,
lapply(.SD, test_list, mu = 500, sig = 10) %>%
unlist() %>%
as.list(),
by = .(h1, sam)][,
lapply(.SD, mean),
by = h1, .SDcols = -"sam"]
```
```{r mupwcurve, fig.cap="Empirical power curve of each z-test and t-test"}
pw_mc %>%
melt(id.vars = "h1", variable.name = "test") %>%
ggplot(aes(x = h1, y = value, colour = test)) +
geom_path() +
geom_point() +
scale_colour_discrete(
name = "Test",
labels = c("Z", "T")
) +
labs(
x = expression(mu),
y = expression(beta)
)
```
Recall that we are estimating power. Instead of `mean()`, we can use `sd()`. This would give us *standard error* of our estimator for power. Since it is sample proportion,
$$\widehat{SE}(\hat{p}) = \sqrt{\frac{\hat{p}(1 - \hat{p})}{M}}$$
Consider $T$-test.
<!-- ```{r} -->
<!-- pw_mc2 <- -->
<!-- foreach(mu1 = seq(450, 650, by = 10), .combine = rbind) %do% { -->
<!-- mc_data(rnorm, N = 20, mean = mu1, sd = 10)[, -->
<!-- h1 := mu1] -->
<!-- } -->
<!-- ``` -->
```{r}
pw_mc2 <- lapply(seq(450, 650, by = 10), function(mu) {
mc_data(rnorm, N = 20, mean = mu, sd = 10)[,
h1 := mu]
})
pw_mc2 <- rbindlist(pw_mc2)
#------------------
pw_mc2 <-
pw_mc2[,
.(te = t.test(x, alternative = "greater", mu = 500)$p.value <= .05),
by = .(h1, sam)][,
.(te = mean(te)),
by = h1][,
se := sqrt(te * (1 - te) / 1000)]
```
```{r pwse, fig.cap="Empirical power curve $\\hat{p} \\pm \\widehat{SE}(\\hat{p})$ for t-test"}
pw_mc2 %>%
ggplot(aes(x = h1, y = te)) +
geom_ribbon(aes(ymin = te - se, ymax = te + se), col = gg_hcl(1)) +
geom_path(alpha = .7) +
geom_point() +
labs(
x = expression(mu),
y = expression(beta)
)
```
### Count Five test for equal variance
Commonly, F-test is used for equality of two population variances. @McGrath:2005kx suggests nonparametric testing without Normal assumption, so called *Count Five*. Instead, this method requires some conditions.
1. same mean
2. same sample size
\begin{algorithm}[H] \label{alg:algcfive}
\SetAlgoLined
\SetKwInOut{Input}{input}
\SetKwInOut{Output}{output}
\Input{$X_1, \ldots, X_{n_x} \ind Y_1, \ldots, Y_{n_y}$ \\ $H_0: \sigma_X^2 = \sigma_Y^2$}
Compute $C_X = \Big\lvert \{ i : \lvert X_i - \overline{X} \rvert > \max_j \lvert Y_j - \overline{Y} \rvert \} \Big\rvert$\;
\uIf{$C_X \ge 5$}{
\Return reject $H_0$\;
}
\Else{
\Return accept $H_0$\;
}
\caption{Count Five test}
\end{algorithm}
```{r}
gauss <-
tibble(
x1 = rnorm(20, mean = 0, sd = 1),
x2 = rnorm(20, mean = 0, sd = 1.5)
)
```
```{r sigbox, fig.cap="Side-by-side boxplot"}
gauss %>%
gather(key = "variable", value = "value") %>%
ggplot(aes(x = variable, y = value, fill = variable)) +
geom_boxplot() +
geom_point(alpha = .5)
```
We would perform *Count Five* test for multiple simulated data sets such as in Figure \@ref(fig:sigbox).
$$X_1^{(m)}, \ldots, X_{20}^{(m)} \sim N(0, 1) \ind Y_1^{(m)}, \ldots, Y_{20}^{(m)} \sim N(0, 1.5)$$
```{r}
count5test <- function(x, y) {
X <- x - mean(x)
Y <- x - mean(y)
outx <- sum(X > max(Y)) + sum(X < min(Y))
outy <- sum(Y > max(X)) + sum(Y < min(X))
max(c(outx, outy)) > 5
}
```
Apply MC method to get *empirical type I error*.
```{r}
mc_data(rnorm, N = 20, M = 1000)[,
x2 := rnorm(20 * 1000)][,
.(chat = count5test(x = x, y = x2)),
by = sam][,
.(chat = mean(chat))]
```
<!-- ## Statistical Methods -->
## Bootstrap {#bootest}
### Resampling
Bootstrap is a class of nonparametric Monte Carlo methods that estimate the distribution of a population by *resampling*. Different with previous MC method, we do not know population distribution. Instead, resampling methods treat an observed sample as a finte population. This is called *pseudo-population* in that this is regarded as having the same characteristics as the true population.
```{r resample, echo=FALSE, fig.cap="Resampling"}
knitr::include_graphics("images/resample.png")
```
See Figure \@ref(fig:resample). From the observed sample, which is pseudo-population, resampling generates multiple bootstrap samples by *sampling with replacement*. Surprisingly, this simple sampling procedure approximate the true population distribution quite successful.
### Approximations in bootstrap {#bootapprox}
How does bootstrap work? @Efron:1983bw provides simple example $T = \overline{x}$, i.e. sample average.
```{example, bootave, name = "Estimation of sample mean"}
Having observed $X_1 = x_1, \ldots, X_n = x_n$, compute
$$\overline{x} = \frac{1}{n} \sum_{i = 1}^n x_i$$
Using bootstrap, we try to see the empirical distribution of this.
```
Note that
$$X_1, \ldots, X_n \iid F$$
where $F$ is true unknown distribution. Having observed $X_1 = x_1, \ldots, X_n = x_n$, we get *empirical distribution function* by computing the sample average.
\begin{equation}
\hat{F}(x) = \frac{1}{n} \sum_{i = 1}^n I(X_i \le x_i)
(\#eq:edistn)
\end{equation}
This works for estimator of $F$. $\hat{F}$ endows mass $\frac{1}{n}$ on each observed point $x_i, \: i = 1, \ldots, n$. In other words, pseudo-distribution becomes *discrete uniform*.
\begin{equation}
\hat{F} \stackrel{d}{=} unif(x_1, \ldots, x_n)
(\#eq:discunif)
\end{equation}
We have set the population distribution which is bogus. Now we can apply previous MC sampling with $\frac{1}{n}$. Write $\{ X_1^{\ast}, \ldots, X_n^{\ast} \}$ as *bootstrap sample* by resampling. Then
$$P(X^{\ast} = x_i) = \frac{1}{n}$$
i.e.
\begin{equation}
X^{\ast} \iid unif(x_1, \ldots, x_n)
(\#eq:bootdistn)
\end{equation}
This gives *bootstrap cdf*, cdf of bootstrap samples, by
\begin{equation}
F^{\ast}(x) = \text{cdf of}\: unif(x_1, \ldots, x_n) = \hat{F}
(\#eq:bootcdf)
\end{equation}
One proceeds in a similar way for estimating cdf that
\begin{equation}
\hat{F}^{\ast} = \frac{1}{n} \sum_{i = 1}^n I(X^{\ast} \le x_i)
(\#eq:bootecdf)
\end{equation}
This is called *ecdf of bootstrap replicates*.
```{remark}
For any data points $X_1, \ldots, X_n$,
\begin{enumerate}
\item \textbf{\textit{Empirical Distribution Function}} $\hat{F}(x) = \frac{1}{n} \sum_{i = 1}^n I(X_i \le x_i)$
\item \textbf{\textit{Bootstrap cdf}} $F^{\ast}(x) = \hat{F}$
\item \textbf{\textit{ECDF of bootstrap replicates}} $\hat{F}^{\ast} = \frac{1}{n} \sum_{i = 1}^n I(X^{\ast} \le x_i)$
\end{enumerate}
```
This remark can explain Figure \@ref(fig:resample) in a distribution way.
```{r bootapprox, echo=FALSE, fig.cap="Empirical distribution of bootstrap"}
knitr::include_graphics("images/bootapprox.png")
```
Figure \@ref(fig:bootapprox) shows how each sample is distributed, approximately. We get the data set from true $F$. From this finite population, we first estimate $F$ by $\hat{F}$. Resampling multiple bootstrap samples, each sample estimates $\hat{F}$ by $\hat{F}^{\ast}$.
```{theorem, twoapprox, name = "Two approximations in bootstrap"}
There are two approximations in bootstrap. For large $B$, bootstrap samples approximate bootstrap replicates. For large $n$, bootstrap replicates approximate true population.
$$\mathbf{X}^{(b)} \vertarrowbox[3ex]{\rightarrow}{\text{large}\: B} \hat{f} \vertarrowbox{\rightarrow}{\text{large}\: n} f$$
```
```{proof}
Since
$$E\hat{F} = \frac{1}{n} \sum_{i = 1}^n P(X_i \le x_i)$$
$$\hat{F} \stackrel{a.s.}{\rightarrow} F$$
as $n \rightarrow \infty$ by the strong law of large numbers. Let
$$\overline{\hat{F}^{\ast}} := \frac{1}{B} \sum_b \hat{F}_b^{\ast}$$
where $\hat{F}_b^{\ast}$ is ecdf of $b$-th bootstrap replicate. Since
$$E\hat{F}_b^{\ast} = \frac{1}{n} \sum_{i = 1}^n P(X^{(b)} \le x_i)$$
$$\overline{\hat{F}^{\ast}} \stackrel{a.s.}{\rightarrow} F^{\ast} = \hat{F}$$
as $B \rightarrow \infty$ by S.L.L.N.
```
Denote that Theorem \@ref(thm:twoapprox) can be also expressed as
\begin{equation}
\overline{\hat{F}^{\ast}} \vertarrowbox[3ex]{\rightarrow}{\text{large}\: B} \hat{F} \vertarrowbox{\rightarrow}{\text{large}\: n} F
(\#eq:twoapprox2)
\end{equation}
This approximation not only justifies the bootstrap procedure but also shows the problem of it. We can always increase $B$ if we want. Then we earn $\overline{\hat{F}^{\ast}} \approx \hat{F}$, i.e. bootstrap samples approximate pseudo-population. However, $n$ is fixed. For $\hat{F}$ to approximate $F$, large $n$ is required. It is not under control. If small $n$ is given, $\hat{F}$ will not be close to $F$. Then the bootstrap samples will not be close to $F$ finally.
```{corollary, bootprob}
Resampling the large number of replicates, i.e. large $B$ produces a good estimates of $\hat{F}$ but it does not guarantee a good estimate of $F$.
```
```{r, include=FALSE}
bootpoisx <- c(2, 2, 1, 1, 5, 4, 4, 3, 2, 1)
```
```{example, bootpois, name = "Poisson population"}
Suppose that $\{ 2, 2, 1, 1, 5, 4, 4, 3, 2, 1 \} \sim Poisson(\lambda = 2)$. Resampling from this pseudo-population, can we appropriately explain the population?
```
```{r bootpoisemp, echo=FALSE, results='asis'}
tibble(x = bootpoisx) %>%
count(x) %>%
mutate(n = n / sum(n)) %>%
spread(x, n) %>%
knitr::kable(caption = "Empirical distribution", longtable = TRUE)
```
Table $\ref{tab:bootpoisemp}$ is just a result of averaging, emprical distribution $\hat{F}$. General bootstrap will resample by distribution. We can see the problem at once.
$$P(X = 0) = e^{-2} = `r dpois(0, lambda = 2)`$$
However, we did not observe $0$, so the bootstrap sample will never include zero, i.e. not a full domain. In sum,
$$\overline{\hat{F}^{\ast}} \rightarrow \hat{F} {\color{red}{\not}}{\rightarrow} F$$
### Bootstrap standard error
Look at the Figure \@ref(fig:bootapprox) again. For each sample, we calculate esimator of our interest. For instance, Example \@ref(exm:bootave) - sample average $\overline{x}$. After that, we get empirical distribution of $\overline{x}$ such as *standard error*.
Before looking at the empirical distribution, let's review sample estimation.
```{theorem, samplemean, name = "Standard error of sample mean"}
Standard error of $\overline{X} = \overline{x} = \frac{1}{n} \displaystyle\sum_{i = 1}^n x_i$, i.e. the \textit{root mean squred error} is estimated by
$$\hat\sigma = \bigg[ \frac{1}{n (n - 1)} \sum_{i = 1}^n (x_i - \overline{x})^2 \bigg]^{\frac{1}{2}}$$
```
Here, $n - 1$ was divided for *unbiasedness*. Recall that
$$Var(\overline{X}) = \frac{\sigma^2}{n}$$
It follows that