-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnitedProject_def.Rmd
2316 lines (1761 loc) · 104 KB
/
UnitedProject_def.Rmd
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
---
output:
pdf_document:
includes:
in_header: mystyles.sty
before_body: title.sty
# please, modify title.sty for your title page
number_sections: yes
toc: yes
citation_package: natbib
word_document: default
html_document: default
documentclass: book
classoption: a4paper
bibliography: bibtexexample.bib
biblio-style: apalike
header-includes:
\usepackage{float}
\floatplacement{figure}{H}
---
# Introduction
```{r setup, include=FALSE}
knitr::opts_chunk$set(
fig.path = 'figs/',
tidy = TRUE,
fig.align = 'center',
fig.show = 'hold',
par = TRUE,
warning = FALSE,
message = FALSE
)
RNGkind("default")
```
```{r}
food <- read.csv("Food_Production.csv")
food[1:9, 1:5]
```
The Food Production dataset contains 43 most common food types and several variables about their CO2 production across different stages in the lifecycle of production, such as, processing, transport, packaging and so on.
CO2 outputs of each stage are expressed in kg per kg of food product.
\hfill\break
In our analysis we will only deal with the variable `Total_emissions` which summarizes all the other variables regarding CO2 production for each food type. The dataset will be divided into 9 groups based on food type regardless of `Total_emissions`'s value. \hfill\break
The groups are: "Grain_Products", "Vegetables", "Oils", "Fruit",
"Dairy_Products&Eggs", "Legumes&Nuts", "Meat",
"Fish", "Others".
```{r}
food <- cbind(food, Group = rep(NA, dim(food)[1]))
food <- dplyr::relocate(food, Group, .before = Land.use.change)
food$Group <- c(1,1,1,1,1,2,2,9,9,6,2,6,6,6,6,3,3,3,3,3,2,6,2,
2,2,4,4,4,4,9,4,9,9,7,7,7,7,7,5,5,5,8,8)
food1 <- food[,c(1,2,10)]
y_bar <- as.vector(tapply(food1$Total_emissions, food$Group, mean))
m <- length(y_bar)
sv_j <- as.vector(tapply(food1$Total_emissions, food1$Group, var))
nj <- as.vector(table(food1$Group))
table(food$Group)
```
In the code above we modified the dataset adding the column `Group` and keeping just the column of interest `Total_emissions`. \hfill\break
Unfortunately the dataset has few observations and so when splitting it into groups we obtain fairly small subsets, this means we can count on small information from the data. \hfill\break
All our results will be clearly affected by this fact, nevertheless we managed to carry out an analysis using weakly-informative priors anyway. \hfill\break
Of this grouped dataset we can compute the sample means for each food group and the resulting vector is `r toString(round(y_bar, 2))`.
The sample means are quite heterogeneous, hence we have groups polluting much more than others on average. This can be noticed looking at the boxplot representing CO2 emissions
```{r}
my_col=hcl.colors(n=9, palette = "BrBG")
boxplot(food1$Total_emissions ~ food1$Group, col= my_col,
main = "Data boxplots", xlab= "Groups",
ylab = "CO2 emissions")
```
\hfill\break
The core of our analysis is to implement a hierarchical Bayesian model to make inference on average level of C02 group emissions and
therefore check whether the differences between means are a feature of our sample or can be assumed as true for the groups' populations. \hfill\break
Our final goal though is prediction: we want to compute the probability that new observations from the meat group are more polluting than those from others'. \hfill\break
A Bayesian hierarchical model is perfect to cope with this problem as perhaps having a few more high or low polluting observations within certain group could drastically change a Frequentist test, while having a rather negligible impact in a Bayesian setting.
# Model I
The first model we implemented is a hierarchical two levels model as units are considered to be nested within groups. \hfill\break
Model assumptions are the following
\begin{itemize}
\item data $y_{1,j}, \ ... \ ,y_{nj,j}$ are Normally distributed \\
$$y_{1,j}, \ ... \ ,y_{nj,j}|\theta_j, \sigma^2 \sim N(\theta_j, \sigma^2)$$
\item $\theta_j$, $\sigma^2$ are each assigned a prior
\begin{enumerate}
\item $\theta_j|\mu, \tau^2 \ \sim \ i.i.d. N(\mu, \tau^2)$ Each prior hyperparameter is assigned yet another prior
\begin{itemize}
\item $\mu|\mu_0,\gamma_0^2 \ \sim \ N(\mu_0,\gamma_0^2)$
\item $\tau^2|\eta_0, \tau_0^2 \ \sim \ I-Gamma(\eta_0, \tau_0^2)$
\end{itemize}
\item $\sigma^2|\nu_0, \sigma_0^2 \ \sim \ I-Gamma(\frac{\nu_0}{2}, \frac{\nu_0\sigma_0^2}{2})$
\end{enumerate}
\item the priors on $\theta_j, \sigma^2$ are assumed independent
$$p(\boldsymbol{\theta} ,\sigma^2) = p(\boldsymbol{\theta}) \cdot p(\sigma^2)$$
\end{itemize}
## Posterior inference
### Full conditional of $\theta_j$
The prior of $\theta_j$ is semi-conjugate to the Normal likelihood and hence the full conditional is available in close form
\begin{gather}
p(\theta_j|y_1, \ ,...,\ y_{nj}, \sigma^2) \propto \underbrace{p(y_1, \ ,...,\ y_{nj}| \theta_j, \sigma^2)}_{Likelihood} \cdot \underbrace{p(\theta_j)}_{prior} \qquad \text{because of prior independence} \nonumber \\
=\prod^n_{i=1} \left\{\frac{1}{\sqrt{2\pi}\sigma^2} \ exp\left\{\frac{1}{2\sigma^2}(y_{ij}-\theta_j)^2\right\} \right\} \cdot \frac{1}{\sqrt{2\pi}\sigma^2} \ exp\left\{\frac{1}{2\sigma^2}(\theta_j-\mu)^2\right\} \nonumber
\end{gather}
From theory we know the full conditional is
$$\theta_j|\sigma^2,y_{1,j}, \ ... \ ,y_{nj,j}, \sim N\left( \frac{n_j\bar{y_j}/\sigma^2 + \mu/\tau^2}{n_j/\sigma^2 + 1/\tau^2}, \ (n_j/\sigma^2 + 1/\tau^2)^{-1} \right)$$
### Full conditional of $\sigma^2$
The prior of $\sigma^2$ is semi-conjugate to the likelihood too, and due to prior independence between $\theta_j, \sigma^2$ we have
\begin{gather}
p(\sigma^2|y_1, \ ,...,\ y_{nj}, \theta_j) \propto \underbrace{p(y_1, \ ,...,\ y_{nj}| \theta_j, \sigma^2)}_{Likelihood} \cdot \underbrace{p(\sigma^2)}_{prior} \nonumber \\
=\prod^n_{i=1} \left\{\frac{1}{\sqrt{2\pi}\sigma^2} \ exp\left\{-\frac{1}{2\sigma^2}(y_{ij}-\theta_j)^2\right\} \right\}
\frac{\frac{\nu_0\sigma_0^2}{2}^{\frac{\nu_0}{2}}}{\Gamma(\frac{\nu_0}{2})}\left(
\frac{1}{\sigma^2}\right)^{\frac{\nu_0}{2}-1} exp\left\{-\frac{\nu_0\sigma_0^2}{2}\frac{1}{\sigma^2} \right\} \nonumber \\
\propto \left(\frac{1}{\sigma^2}\right)^{\frac{nj}{2}} exp\left\{-\frac{1}{2\sigma^2}\sum^{nj}_{i=1} (y_{ij}-\theta_j)^2 \right\} \cdot \left(
\frac{1}{\sigma^2}\right)^{\frac{\nu_0}{2}-1} exp\left\{-\frac{\nu_0\sigma_0^2}{2}\frac{1}{\sigma^2} \right\} \nonumber \\
\propto \left(\frac{1}{\sigma^2}\right)^{\frac{nj + \nu_0}{2}-1} \cdot exp\left\{-\frac{1}{2\sigma^2}\left[\sum^{nj}_{i=1} (y_{ij}-\theta_j)^2 + \nu_0\sigma_0^2\right] \right\} \nonumber \\
\propto \left(\frac{1}{\sigma^2}\right)^{\frac{\nu_n}{2}-1} \cdot exp\left\{-\frac{1}{2\sigma^2}\nu_n \frac{1}{\nu_n} \left((nj-1)S^2 + \nu_0\sigma_0^2 \right) \right\} \nonumber \\
\text{With} \nonumber \\
\nu_n = \nu_0 + nj \qquad \qquad \text{and} \nonumber \\
\sigma_n^2 = \frac{1}{\nu_n} \left((nj-1)S^2 + \nu_0\sigma_0^2 \right) \nonumber
\end{gather}
### Posterior on $\mu$
The Normal prior on $\mu$ is conjugate to the Normal joint distribution of $\theta_1, \ ... \ ,\theta_j$ so can derive analytically its posterior
\[
p(\mu|\theta_1, \ ... \ ,\theta_j) \propto p(\theta_1, \ ... \ ,\theta_j|\mu, \tau^2) \cdot p(\mu) \qquad \text{Supposing prior independece between} \ \mu, \ \tau^2
\]
\[
\mu|\theta_1, \ ... \ ,\theta_j \ \sim \ N \left(\frac{\mu_0/\gamma_0^2 + m/\tau^2 \bar{y_j}}{1/\gamma_0^2 + m/\tau^2},\left(\frac{1}{\gamma_0^2} + \frac{m}{\tau^2}\right)^{-1} \right)
\]
### Full conditional on $\tau^2$
Assuming prior independece between $\mu, \tau^2$ we have that the $I-Gamma$ prior on $\tau^2$ is semi-conjugate to the joint distribution of $\theta_1, \ ... \ ,\theta_j$. Hence can derive
\[
p(\tau^2|\mu,\theta_1, \ ... \ ,\theta_j) \propto p(\theta_1, \ ... \ ,\theta_j|\mu, \tau^2) \cdot p(\tau^2)
\]
Which results
\[
\tau^2|\mu,\theta_1, \ ... \ ,\theta_j \ \sim \ I-Gamma \left(\frac{\eta_0+m}{2}, \frac{\eta_0 + \sum_{j=1}^m(\theta_j - \mu)^2}{2} \right)
\]
## R implementation
In `R` we wrote the function `Hierarchical_1` which implements the following algorithm
\begin{itemize}
\item As a preliminary step we assigned all prior hyperparameters to $\theta_j$, $\sigma_j^2$, $\mu$, $\tau^2$
\begin{itemize}
\item $\theta_j$:
\begin{itemize}
\item set $\theta_j = \bar{y_j}$ as initial value
\item assigned $\mu = \mathbb{E}(\bar{y_j})$ and $\tau^2 = Var(\bar{y_j})$
\end{itemize}
\item $\sigma_j^2$:
\begin{itemize}
\item $\sigma_j^2 = \mathbb{E}(S_j^2)$ with $S_j^2$ sample variance for the $j-th$group
\item we set $\nu_0 = 1$ and $\sigma_0^2 = 100$ to be weakly-informative on variance
\end{itemize}
\item $\tau^2$: $\eta_0 = 1$ and $\tau_0^2 = 100$ for weakly informativness
\item $\mu$: to set its hyperparameters we checked the `summary` of the sample means $\bar{y_j}$ and assigned hyperparameters to cover the whole "range" of the sample means, i.e. $\mu_0 = 12$ and $\gamma_0^2 = 6^2$
\end{itemize}
\item for $s=1, ..., S$:
\begin{enumerate}
\item sample $\mu^{(s)}$ from $p(\mu^{(s)}|\rho_n, \gamma_n^2) = N(\rho_n, \gamma_n^2)$
\item sample $\tau^{2(s)}$ from $p(\tau^{2(s)}|\eta_n, \lambda_n) = I-Gamma(\eta_n, \lambda_n)$
\item draw $\theta_j^{(s)}$ from $p(\theta_j^{(s)}| \mu_n^{(s)}, \tau_n^{2(s)}) = N(\mu_n^{(s)},\tau_n^{2(s)})$
\item draw $\sigma^{2(s)}$ from $p(\sigma^{2(s)}|y_1, \ ,...,\ y_{nj},\theta_j^{(s)})$
\end{enumerate}
\end{itemize}
```{r}
Hierarchical_1 <- function(S, dati) {
## Prior hyperparameters
# Prior on sigma_sq
sigma2 <- mean(sv_j)
nu0 <- 1
s02 <- 100
# Prior tau_sq
eta0 <- 1
tau02 <- 100
# Prior on mu
# Check summary(y_bar) #########
mu0 <- 12
g02 <- 6^2
# Prior on theta ****
theta <- y_bar
mu <- mean(y_bar)
tau_sq <- var(y_bar)
Theta_post <- matrix(NA, S, m)
Musita_post <- matrix(NA, S, 3)
for(s in 1:S) {
# 1. Draw theta
for (j in 1:m) {
mean_1 <- (mu*(1/tau_sq) + y_bar[j]*
(nj[j]/sigma2))/((1/tau_sq)+ (nj[j]/sigma2))
var_1 <- ((1/tau_sq) + (nj[j]/sigma2))^(-1)
theta[j] <- rnorm(1, mean_1, sqrt(var_1))
}
Theta_post[s,] <- theta
# 2. Draw sigma2
alpha_1 <- (nu0 + nrow(dati))
beta_1 <- nu0*s02
for(j in 1:m) {
beta_1 <- beta_1 + sum((dati$Total_emissions[dati$Group == j] -
theta[j])^2)
}
sigma2 <- 1/rgamma(1, alpha_1/2, beta_1/2)
# 3. Sample mu
mean_2 <- (1/g02 * mu0 + m/tau_sq * mean(theta))/(1/g02 + m/tau_sq)
var_2 <- (1/g02 + m/tau_sq)^(-1)
mu <- rnorm(1, mean_2, sqrt(var_2))
# 4. Sample tau_sq
alpha_2 <- (eta0+m)
beta_2 <- eta0 + sum((theta - mu)^2)
tau_sq <- 1/rgamma(1, alpha_2/2, beta_2/2)
Musita_post[s,] <- c(mu, sigma2, tau_sq)
}
return(list(Theta_post = Theta_post, Musita_post = Musita_post))
}
```
Above is the function that we will run for `5000` iterations, assigning
the results to a list that can be split into matrices.
```{r}
set.seed(12345)
out = Hierarchical_1(S=5000, dati = food1)
Theta_post = out$Theta_post
Musita_post = out$Musita_post
```
Now we can check the traceplots and Autocorrelation functions of $\mu, \ \sigma^2, \ \tau^2$
```{r}
# Traceplot Musita_post
S=5000
par(mfrow = c(3,1))
for (i in 1:3) {
plot(1:S, Musita_post[,i], type = "l", xlim = c(0, 2000),col="deepskyblue4")
abline(h = mean(Musita_post[,i]),col="chocolate3", lwd=0.8 )
mode_1 <- density(Musita_post[,i])$x[which.max(density(Musita_post[,i])$y)]
abline(h = mode_1,col="darkolivegreen1", lwd=0.8 )
}
#acf Musita_post
par(mfrow = c(3,1))
for(i in 1:3) {
acf(Musita_post[,i], 100, main = "")
}
```
The acf's do not look too good. We have quite some autocorrelation between values. We can run again the function `Hierarchical_1` for `25000` iterations and procede to thinning the chains.
```{r}
out2 = Hierarchical_1(S=25000, dati=food1)
Theta_post = out2$Theta_post
Musita_post= out2$Musita_post
#Theta
Theta_post2 <- Theta_post[seq(1,25000, by = 5),]
# Musita
Musita_post2 <- Musita_post[seq(1, 25000, by = 5),]
```
Can now check again the acf's
```{r}
S <- 25000
par(mfrow = c(3,1))
for(i in 1:3) {
acf(Musita_post2[,i], 100, main = "")
}
```
The situation has indeed improved.
### Final plots
Can now plot the histogram of empirical distributions of $\theta_j$ obtained in the algorithm
```{r}
par(mfrow = c(2,2))
idx <- c(1,3,7,9)
for(i in idx) {
hist(Theta_post2[,i], breaks = 100, col = "aquamarine3",
border = "deepskyblue4", main = "")
abline(v = mean(Theta_post2[,i]),col="chocolate3", lwd=2 )
mode_1 <- density(Theta_post2[,i])$x[which.max(density(Theta_post2[,i])$y)]
abline(v = mode_1,col="darkolivegreen1", lwd=2 )
abline(v = apply(Theta_post2, 2, quantile, 0.05)[i], lty = 2)
abline(v = apply(Theta_post2, 2, quantile, 0.95)[i], lty = 2)
}
```
Chose to plot just those of ... groups because they will the most representative of all the groups in further analysis we will make.
#### Prior vs. posterior plots
We now want to plot \textbf{prior vs posterior} distributions of $\theta_j$.
Before proceeding we need to get a sample that approximates the marginal prior distribution of $\theta_j$. This is done by using the function `marginal_prior_H1H2`. Accordingly to our model assumptions we have that $\theta_j| \mu, \tau^2 \sim N \left(\mu, \tau^2 \right)$, where $\mu, \tau^2$ are not considered as fixed, but they are random. Indeed, we have assumed that: $\mu \sim N \left(\mu_0, \gamma_0^2 \right)$ and $\frac{1}{\tau^2} \sim Gamma \left( \eta_0/2, \eta_0 \tau_0^2/2\right)$.
Hence to get a sample that approximates the marginal prior distribution of $\theta_j$ we need to:
$\forall s=1,..,S$
\begin{enumerate}
\item Sample $\mu^{(s)}$ from $N \left(\mu_0, \gamma_0^2 \right)$
\item Sample $\tau^{2(s)}$ from $I-Gamma \left( \eta_0/2, \eta_0 \tau_0^2/2\right)$
\item Sample $\theta_j^{(s)}$ from $N \left(\mu^{(s)}, \tau^{2(s)} \right)$
\end{enumerate}
At the end we will obtain a sample of $S$ draws that approximates the marginal prior distribution of $\theta_j$ and we can plot it against its posterior distribution.
```{r}
marginal_prior_H1H2 <- function(N) {
Theta_marg_H1 = matrix(NA, N, m)
for (j in 1:m){
mu_marg = rnorm(N, 12, 6)
tau_marg = 1/rgamma(N,1,100)
Theta_marg_H1[,j] = rnorm(N, mu_marg, sqrt(tau_marg))
}
return(Theta_marg_H1 = Theta_marg_H1)
}
Theta_marg_H1 = marginal_prior_H1H2(N = 5000) # draws from the marginal prior
# of theta_j
# Prior vs. posterior plots
par(mfrow = c(2,2))
for(j in idx){
plot(density(Theta_post2[,j],adj=2),main="",
xlab=expression(theta[j]), ylab="density",lwd=2, col="darkgreen")
lines(density(Theta_marg_H1[,j], adj = 2),
lwd=2, col="darkolivegreen3")
legend("topleft",legend=c("posterior","prior"),lwd=c(2,2),
col=c("darkgreen","darkolivegreen3"),bty="n")
}
```
From the plots above we can notice how spread the priors are with respect to the much more concentrated posteriors. Furthermore looking closely at the third plot, that of the meat group's approximate posterior mean, we see it is almost bimodal. \hfill\break
This is because the posterior took information from the data which are very homogeneous in this group, ranging from the low polluting poultry meat to the extremely polluting beef herd.
### Boxplot of posterior draws of $\theta_j$
```{r}
{boxplot(Theta_post2, col = my_col, main = expression(
paste("H1 Posterior on ",theta[j])), xlab = "Groups",
ylab= "")
title(ylab = expression(paste("p(",theta[j], "|", mu,",", sigma^2, ",",
italic(y[1]),"...",italic(y[m]),")") ),
mgp = c(2,1,0))
library(plotrix)
draw.circle(7,17,0.5, border ="red", lwd = 2)}
```
In this boxplot are represented the approximated posterior group means. At first glance we can see that even though the posterior means are quite similar to the sample means the different within group variances are not at all respected by our posterior distributions. We will solve this problem in the next models. \hfill\break
Furthermore it is clear that some groups' distributions have too many negative values to be considered totally reliable: such as the second, fourth and sixth. This problem does not affect our analysis too much as considering $90\%$ empirical confidence intervals for the empirical distributions of $\theta_j$, we see that most of them are always positive and that those that are not have just few negative values. Nevertheless this issue will be tackled in the last model.
```{r, echo=FALSE}
res_H1 = matrix(NA, 9, 3)
rownames(res_H1) <- 1:9
colnames(res_H1) <- c("LB 90% CI", "UB 90% CI", "Post Exp theta_j")
res_H1[,1] <- apply(Theta_post2, 2, quantile, 0.05)
res_H1[,2] <- apply(Theta_post2, 2, quantile, 0.95)
res_H1[,3] <- apply(Theta_post2, 2, mean)
knitr::kable(res_H1)
```
## Shrinkage
Shrinkage effect moves the posterior mean $\mathbb{E}(\theta_j|\mathbf{y}, \mu,\tau^2, \sigma^2)$ away from the sample mean $\bar{y_j}$ towards the sampled values of the overall average of group means ($\mu$). \hfill\break
We will check for the presence of shrinkage through a graphical analysis.
```{r}
# Shrinkage effect
par(mfrow = c(1,2))
plot(y_bar, res_H1[,3], xlab=expression(bar(italic(y))),
ylab="")
title(ylab = expression(paste("E[",theta[j], "|", mu,",", sigma^2, ",",
italic(y[1]),"...",italic(y[m]),"]")),
mgp = c(2,1,0))
for(i in 1:m) {
if(i == 4) {
text(y_bar[i], res_H1[i,3]+0.6, labels = i)
}
else if(i == 9){
text(y_bar[i], res_H1[i,3]-0.6, labels = i)
}
else {
text(y_bar[i]+0.6, res_H1[i,3], labels = i)
}
}
abline(a=0, b=1, col = "darkred")
#Shrinkage
plot(nj, (y_bar - res_H1[,3]), xlab = "sample size", ylab = "")
title(ylab = expression(bar(italic(y)) - hat(theta)), mgp = c(2,1,0))
for(i in 1:m) {
if(i == 4) {
text(nj[i]-0.2, (y_bar[i] - res_H1[i,3]), labels = i)
}
else {
text(nj[i]+0.2, (y_bar[i] - res_H1[i,3]), labels = i)
}
}
abline(h = 0, col="darkred")
```
These plots seem good, even though there is some shrinkage, it is negligible for most groups. Group 7 is slightly more problematic but still the shrinkage is about $25\%$ of its sample mean. The situation will worsen changing some assumptions later on.
## Prediction
```{r}
# P(theta_meat > theta_dairy)
prob_1 <- NULL
pred_1 <- NULL
for (j in 1:m){
if (j != 7){
prob_1 <- c(prob_1, mean(Theta_post2[,7]>Theta_post2[,j]))
pred_1 <- c(pred_1, mean(rnorm(5000, Theta_post2[,7], sqrt(Musita_post2[,2])) >
rnorm(5000, Theta_post2[,j], sqrt(Musita_post2[,2]))) )
}
}
res_P_1 <- cbind(prob_1, pred_1)
colnames(res_P_1) <- c("P(Theta_7 > Theta_j)", "P(Y*_7 > Y*_j)")
knitr::kable(res_P_1)
```
We can see from the first column of the table the probabilities for $\theta_7$ meat's group average to be higher than the group mean of others'. \hfill\break
In the second column instead we have $p(y_7^* > y_j^*) \ \ \forall j\neq7$, the probability for a new observation from meat group to be higher than that from another group. \hfill\break
Both the columns show remarkably high probabilities, but the second's are slightly lower, this is due to the variance of prediction being higher than that of inference. In prediction indeed individual variability has to be taken into account.
## Model cheking
Here we perform model checking. To check if our model was appropriate for the data we chose as statistic the expected value of new predicted values $y^*$ to make comparisons with the sample mean $\bar{y_j}$.
```{r}
T_mc <- matrix(NA, 5000, m)
for (j in 1:m){
for (i in 1:5000){
y_star = rnorm(100, Theta_post2[i,j], Musita_post2[i,2])
T_mc[i,j] = mean(y_star)
}
}
```
```{r, echo=FALSE}
# Comparison of the distribution of T_mc VS y_bar
res_mod_check = matrix(NA, m, 3)
colnames(res_mod_check) <-c("90% LB", "90% UB", "y_bar")
res_mod_check[,1] <- apply(T_mc, 2, quantile, 0.05)
res_mod_check[,2] <- apply(T_mc, 2, quantile, 0.95)
res_mod_check[,3] <- y_bar
#knitr::kable(res_mod_check)
```
```{r}
par(mfrow = c(2,2))
for(i in idx) {
hist(T_mc[,i], breaks = 100, col = "chartreuse2",
border = "chartreuse4", main = "")
abline(v = y_bar[i],col="darkorange", lwd=3 )
abline(v = res_mod_check[i,1], col ="darkorange4", lty=2)
abline(v = res_mod_check[i,2], col ="darkorange4", lty=2)
}
```
To decide whether our model is good and whether our data are unusual or not we can look where the sample mean lies in the empirical distribution of expected value of predicted data. In this case there seem to be no issues.
# Model II
From the boxplot of data we notice there are different variances for each group. The first hierarchical model implemented above does not take into account these differences in variances within groups but just the differences in means. \hfill\break
If the population means vary across groups it would be sensible to allow also the population variances to do so in our model.
\hfill\break
```{r, echo=FALSE}
my_col=hcl.colors(n=9, palette = "BrBG")
boxplot(food1$Total_emissions ~ food1$Group, col= my_col,
main = "Data boxplots", xlab= "Groups",
ylab = "CO2 emissions")
```
Keeping the same prior on $\boldsymbol{\theta}$ we had in the previous case
\[
p(\theta_j|\mu_0, \tau_0^2) = N(\mu_0, \tau_0^2)
\]
let now $\sigma^2_j$ be the $j-th$ group's specific variance.\hfill\break
This way our model becomes
\[
Y_{1,j}, \ ... \ , Y_{nj,j} \sim i.i.d. \ N(\theta_j, \sigma^2_j) \quad \forall j = 1, ..., m
\]
The distribution assumption for our data stays unchanged if not for the fact that each group has now its own group mean and its own group variance.
The new assumption results in the same full conditional of $\theta_j$, but changes its posterior parameters which now both depend on the group specific variance $\sigma^2_j$
\[
\theta_j |y_{1,j}, ... , y_{nj,j}, \sigma^2_j \sim N \left( \frac{n_j\bar{y_j}/\sigma^2_j + \mu/\tau^2}{n_j/\sigma^2_j + 1/\tau^2}, \ (n_j/\sigma^2_j + 1/\tau^2)^{-1} \right)
\]
Group variances can be assigned the same prior we assigned to $\sigma^2$ in the previous model, reparametrized with $\alpha$ and $\beta$ for computational convenience. Therefore can write
\[
\sigma^2_1, \ ... \ ,\sigma^2_m| \alpha, \beta \sim i.i.d. \ I-Gamma(\alpha, \beta)
\]
As opposite to the previous setting though, here we assign a prior to $\alpha$ and $\beta$ parameters. This is because if we kept prior hyperparameters fixed the sample information we have about within group variances would have gone wasted. Now instead we are interested in using the sample information on $\sigma^2_j$'s to improve their estimation.
## Prior on $\alpha$ and $\beta$ hyperparameters
We can put a Gamma prior on both $\alpha$ and $\beta$, i.e.
\begin{gather}
\alpha|a,b \sim Gamma(a,b) \nonumber \\
p(\alpha|a,b) \propto \alpha^{a-1} \cdot exp\{ -b \alpha \} \nonumber
\end{gather}
and
\begin{gather}
\beta|c,d \sim Gamma(c,d) \nonumber \\
p(\beta|c,d) \propto \beta^{c-1} \cdot exp\{ -d \beta \} \nonumber
\end{gather}
We will also suppose prior independence between the two parameters
\[
p(\alpha, \beta) = p(\alpha) \cdot p(\beta) \nonumber
\]
This way the prior on $\beta$ is semi-conjugate to the joint "likelihood" (joint distribution of $\boldsymbol{\sigma^2}$)
\[
p(\boldsymbol{\sigma^2} |\alpha, \beta) = \left( \frac{\beta^\alpha}{\Gamma(\alpha)} \right)^m \left[ \prod_{j=1}^m \frac{1}{\sigma^2_j}\right]^{\alpha -1} \cdot \ exp\left\{- \beta \sum_{j=1}^m \frac{1}{\sigma^2_j}\right\}
\]
Hence can analytically derive the full conditional on $\beta$. \hfill\break
The prior on $\alpha$ instead is not semi-conjugate, hence we will have to implement a Metropolis Hastings algorithm to approximate its full conditional.
### Full conditional of $\beta$
Can compute the full conditional of $\beta$ as
\[
p(\beta| \boldsymbol{\sigma^2}, \alpha, c, d) \propto p(\boldsymbol{\sigma^2} |\alpha, \beta) p(\beta|c,d)
\]
where $p(\boldsymbol{\sigma^2} |\alpha, \beta)$ can be rewritten keeping just what depends on $\beta$. Hence
\begin{gather}
p(\beta| \boldsymbol{\sigma^2}, \alpha)
\propto \beta^{m \alpha} \cdot exp\left\{- \beta \sum_{j=1}^m \frac{1}{\sigma^2_j}\right\} \cdot \beta^{c-1} \cdot exp\{ -d \beta \} \nonumber \\
= \beta^{m\alpha + c -1} \cdot exp\left\{ -\beta \left(\sum_{j=1}^m \frac{1}{\sigma^2_j} +d \right)\right\}
\end{gather}
Formula () is a Gamma, therefore we can easily sample $\beta$ from its full conditional conditionally on $\alpha, \boldsymbol{\sigma^2}$.
### Full conditional of $\alpha$
Let us now derive the full conditional distribution of $\alpha$:
\begin{gather}
p(\alpha| \boldsymbol{\sigma^2}, \beta, a, b) \propto p(\boldsymbol{\sigma^2} | \beta, \alpha) p(\alpha|a, b) \nonumber \\
\left( \frac{\beta^\alpha}{\Gamma(\alpha)} \right)^m \left[ \prod_{j=1}^m \frac{1}{\sigma^2_j}\right]^{\alpha -1} \cdot \alpha^{a-1} exp\{ -b \alpha \} \nonumber
\end{gather}
This time we have written only the parts depending on $\alpha$ in $p(\boldsymbol{\sigma^2} | \beta, \alpha)$ and multiplied by $p(\alpha|a,b)$, but the result can not be traced back to any well known distribution.
Hence even though the full conditional is analytically available, to draw $\alpha$ from it we need to implement a Metropolis Hastings algorithm.
Therefore we can approximate posterior draws of $(\alpha, \beta)$ from $p(\alpha, \beta| \boldsymbol{\sigma^2})$ implementing the following algorithm of Metropolis Hastings within a Gibbs sampler:
$\forall s=1,..,S:$
\begin{itemize}
\item Draw a value $\beta^{(s)}$ from its full conditional distribution: $p(\beta|\alpha, \boldsymbol{\sigma^2},c,d)$ \qquad\qquad\quad \textbf{Gibbs Sampler step}
\item Draw $\alpha$: \qquad\qquad\qquad \textbf{Metropolis Hastings step}
\begin{enumerate}
\item Propose $\alpha^*$ from its proposal: $q(\alpha^*| \alpha^{(s)})$
\item Compute the posterior ratio $r^{MH} = \frac{p(\alpha^*, \beta^{(s)}| \boldsymbol{\sigma^2})}{p(\alpha^{(s)}, \beta^{(s)}| \boldsymbol{\sigma^2})} \cdot \frac{q(\alpha^{(s)}| \alpha^*)}{q(\alpha^*| \alpha^{(s)})}$ \\
where $p(\alpha^{(s)}, \beta^{(s)}| \boldsymbol{\sigma^2}) \propto \left( \frac{\beta^\alpha}{\Gamma(\alpha)} \right)^m \left[ \prod_{j=1}^m \frac{1}{\sigma^2_j}\right]^{\alpha -1} \cdot \alpha^{a-1} exp\{ -b \alpha \} $
\item Set
\[
\left\{
\begin{array} {l}
\alpha^{(s+1)} = \alpha^* \quad \text{with probability} \quad min \{1, r^{MH}\}\\
\alpha^{(s+1)} = \alpha^{(s)} \quad \text{with probability} \quad 1- min \{1, r^{MH}\}
\end{array}
\right.
\]
\end{enumerate}
\end{itemize}
The output of this algorithm will be a sequence of draws $\{(\alpha^{(1)}, \beta^{(1)}),..,(\alpha^{(s)}, \beta^{(s)})\}$ that approximates draws from the joint posterior of $\alpha$ and $\beta$.
## Full conditional of $\sigma^2_j$
In this model we are letting each group have its own $\sigma^2_j$ but we also assume prior independence between $\theta_j$ and $\sigma^2_j$,
\[
p(\boldsymbol{\theta} ,\boldsymbol{\sigma^2}) = p(\boldsymbol{\theta}) \cdot p(\boldsymbol{\sigma^2})
\]
with this assumption, and having derived the full conditionals for $\alpha$ and $\beta$, can now write the full conditional of $\sigma^2_j$.
\begin{gather}
p(\sigma^2_j|y_1, \ ,...,\ y_{nj}, \theta_j) \propto \underbrace{p(y_1, \ ,...,\ y_{nj}| \theta_j, \sigma^2_j)}_{Likelihood} \cdot \underbrace{p(\sigma^2_j)}_{prior} \nonumber \\
=\prod^n_{i=1} \left\{\frac{1}{\sqrt{2\pi}\sigma^2_j} \ exp\left\{\frac{1}{2\sigma^2_j}(y_{ij}-\theta_j)^2\right\} \right\}
\frac{\beta^{\alpha}}{\Gamma(\alpha)}\left(
\frac{1}{\sigma^2_j}\right)^{\alpha-1} exp\left\{-\beta\frac{1}{\sigma^2_j} \right\} \nonumber \\
\propto \left(\frac{1}{\sigma^2_j}\right)^{\frac{nj}{2}} exp\left\{\frac{1}{2\sigma^2_j}\sum^{nj}_{i=1} (y_{ij}-\theta_j)^2 \right\} \cdot \left(
\frac{1}{\sigma^2_j}\right)^{\alpha-1} exp\left\{-\beta\frac{1}{\sigma^2_j} \right\} \nonumber \\
\propto \left(\frac{1}{\sigma^2_j}\right)^{\frac{nj}{2}+ \alpha-1} \cdot exp\left\{-\frac{1}{\sigma^2_j}\left[\frac{\sum^{nj}_{i=1} (y_{ij}-\theta_j)^2}{2} +\beta\right] \right\} \nonumber
\end{gather}
Whence we derive the full conditional of $\sigma^2_j$
\[
\frac{1}{\sigma^2_j} \sim Gamma\left(\frac{nj}{2}+ \alpha, \quad \frac{\sum^{nj}_{i=1} (y_{ij}-\theta_j)^2}{2} +\beta \right)
\]
## R implementation
In the `R` code, before implementing the algorithm, we defined some useful functions to perform the $MH$ part, namely:
\hfill\break
`full.cond.alpha` defines the full conditional of $\alpha$ found above, whereas `propose.alpha.star` is the function of the proposal we chose here to be
$$q(\alpha^*| \alpha^{(s)}) = Gamma (\alpha^{(s)} \delta, \ \delta)$$
```{r}
prod.prec <- prod(1/sv_j)
full.cond.alpha = function(alpha, beta, a, b, prod.prec, m){
((beta^alpha)/gamma(alpha))^m * prod.prec^(alpha-1) * alpha^(a-1) *
exp(-b*alpha)
}
propose.alpha.star = function(alpha, delta){
rgamma(1, alpha*delta, delta)
}
```
The algorithm implemented in `R` works as follows:
\begin{itemize}
\item As a preliminary step we assigned initial values to $\theta_j$, $\sigma_j^2$, $\mu$, $\tau^2$, $\alpha$, $\beta$ and all prior hyperparameters
\begin{itemize}
\item $\theta_j$:
\begin{itemize}
\item set $\theta_j = \bar{y_j}$ as initial value
\item assigned $\mu = \mathbb{E}(\bar{y_j})$ and $\tau^2 = Var(\bar{y_j})$
\end{itemize}
\item $\sigma_j^2$:
\begin{itemize}
\item $\sigma_j^2 = Var(y_{1:nj}) = S_j^2$ with $S_j^2$ sample variance for the $j-th$group
\item we set $\alpha = \frac{(\mathbb{E}(S_j^2))^2}{Var(S_j^2)}$ and $\beta = \frac{\mathbb{E}(S_j^2)}{Var(S_j^2)}$ this way the prior expectation is $\mathbb{E}(\sigma_j^2| \alpha, \beta) = \mathbb{E}(S_j^2)$
\end{itemize}
\item $\alpha$ and $\beta$: as prior hyperparameters set $a = b = c = d = 1$ to be weakly informative and because setting them lower would cause $\alpha$ and $\beta$ to go to $0$ too fast and break the algorithm
\item $\tau^2$: $\eta_0 = 1$ and $\tau_0^2 = 100$ for weakly informativness
\item $\mu$: to set its hyperparameters we checked the `summary` of the sample means $\bar{y_j}$ and assigned hyperparameters to cover the whole "range" of the sample means, i.e. $\mu_0 = 12$ and $\gamma_0^2 = 6^2$
\end{itemize}
\item for $s=1, ..., S$:
\begin{enumerate}
\item sample $\mu^{(s)}$ from $p(\mu^{(s)}|\rho_n, \gamma_n^2) = N(\rho_n, \gamma_n^2)$
\item sample $\tau^{2(s)}$ from $p(\tau^{2(s)}|\eta_n, \lambda_n) = I-Gamma(\eta_n, \lambda_n)$
\item draw $\theta_j^{(s)}$ from $p(\theta_j^{(s)}| \mu_n^{(s)}, \tau_n^{2(s)}) = N(\mu_n^{(s)},\tau_n^{2(s)})$
\item draw $\beta^{(s)}$ from $p(\beta^{(s)}| \boldsymbol{\sigma^2}, \alpha) = Gamma(c^*,d^*)$
\item draw $\alpha^{(s)}$:
\begin{enumerate}
\item Propose $\alpha^*$ from its proposal: $q(\alpha^*| \alpha^{(s)}) = Gamma (\alpha^{(s)} \delta, \ \delta)$
\item Compute the posterior ratio $r^{MH} = \frac{p(\alpha^*, \beta^{(s)}| \boldsymbol{\sigma^2})}{p(\alpha^{(s)}, \beta^{(s)}| \boldsymbol{\sigma^2})} \cdot \frac{q(\alpha^{(s)}| \alpha^*)}{q(\alpha^*| \alpha^{(s)})}$
\item Set
\[
\left\{
\begin{array} {l}
\alpha^{(s+1)} = \alpha^* \quad \text{with probability} \quad min \{1, r^{MH}\}\\
\alpha^{(s+1)} = \alpha^{(s)} \quad \text{with probability} \quad 1- min \{1, r^{MH}\}
\end{array}
\right.
\]
\end{enumerate}
\item draw $\sigma_j^{2(s)}$ from $p(\sigma^{2(s)}_j|y_1, \ ,...,\ y_{nj}, \theta_j^{(s)})$
\end{enumerate}
\end{itemize}
To perform the algorithm we wrote the function `Hierarchical_2`
```{r}
library(formatR)
Hierarchical_2 <- function(data, S, delta) {
# Starting value of sigma2
sv_j <- as.vector(tapply(food1$Total_emissions, food1$Group, var))
sigma2_j <- sv_j
# Prior on sigma2_j
alpha <- (mean(sv_j)^2)/var(sv_j)
beta <- mean(sv_j)/var(sv_j)
# Prior on alpha and beta
a <- b <- 1
c <- d <- 1
# Prior tau_sq
eta0 <- 1
tau02 <- 100
# Prior on mu
mu0 <- 12
g02 <- 6^2
# Prior on theta ****
theta <- y_bar
mu <- mean(y_bar)
tau_sq <- var(y_bar)
nj <- as.vector(table(food1$Group))
m <- length(nj)
Theta_post_H2 <- matrix(NA, S, m)
Sigma_post_H2 <- matrix(NA, S, m)
MuTaAlBet <- matrix(NA, S, 4)
accept <- NULL
for(s in 1:S) {
# 1. Sample mu
mean_2 <- (1/g02 * mu0 + m/tau_sq * mean(theta))/(1/g02 + m/tau_sq)
var_2 <- (1/g02 + m/tau_sq)^(-1)
mu <- rnorm(1, mean_2, sqrt(var_2))
# 2. Sample tau_sq
alpha_2 <- (eta0+m)
beta_2 <- eta0 + sum((theta - mu)^2)
tau_sq <- 1/rgamma(1, alpha_2/2, beta_2/2)
# 3. Draw theta
for (j in 1:m) {
mean_1 <- (mu*(1/tau_sq) + y_bar[j]*
(nj[j]/sigma2_j[j]))/((1/tau_sq)+ (nj[j]/sigma2_j[j]))
var_1 <- ((1/tau_sq) + (nj[j]/sigma2_j[j]))^(-1)
theta[j] <- rnorm(1, mean_1, sqrt(var_1))
}
Theta_post_H2[s,] <- theta
# 4. Draw beta
c_star <- m*alpha + c
d_star <- sum(1/sigma2_j) + d
beta <- rgamma(1, c_star, d_star)
# 5. Draw alpha
alpha.star = propose.alpha.star(alpha, delta)
r = full.cond.alpha(alpha.star, beta, a, b, prod.prec, m)/
full.cond.alpha(alpha, beta, a, b, prod.prec, m) *
dgamma(alpha, alpha.star*delta, delta) /
dgamma(alpha.star, alpha*delta, delta)
u = runif(1)
if(u < r){
alpha = alpha.star
accept[s] <- 1
}
else{accept[s] <- 0}
MuTaAlBet[s,] <- c(mu, tau_sq, alpha, beta)
# 6. Draw sigma2_j
for(j in 1:m) {
beta_fc <- (sum((food1$Total_emissions[food1$Group == j] -
theta[j])^2))/2 + beta
alpha_fc <- nj[j]/2 + alpha
sigma2_j[j] <- 1/rgamma(1, alpha_fc, beta_fc)
}
Sigma_post_H2[s,] <- sigma2_j
}
return(list(Theta_post_H2 = Theta_post_H2,
MuTaAlBet = MuTaAlBet,
Sigma_post_H2 = Sigma_post_H2,
accept = accept))
}
```
We now run the function for `25000` iterations to be able to perform thinning if necessary. Results are stored in a list to be accessible as matrices.
* `Theta_post_H2` is the matrix of draws from the posterior of $\theta_j$,
$$p(\theta_j^{(s)} |y_{1,j}, ... , y_{nj,j}, \sigma^{2(s-1)}_j) = N \left( \frac{n_j\bar{y_j}/\sigma^{2(s-1)}_j + \mu^{(s)}/\tau^{2(s)}}{n_j/\sigma^{2(s-1)}_j + 1/\tau^{2(s)}}, \ (n_j/\sigma^{2(s-1)}_j + 1/\tau^{2(s)})^{-1} \right)$$
* `MuTaAlBet` is the matrix of draws of $\mu$, $\tau^2$, $\alpha$ and $\beta$ each from its posterior and full conditional respectively.
* `Sigma_post_H2` is the matrix containing draws of $\sigma^2_j$ from its full conditional
\[
p(1/\sigma^{2(s)}_j|\theta_j^{(s)}, \alpha^{(s)}, \beta^{(s)}, \mathbf{y}) = Gamma\left(\frac{nj}{2}+ \alpha^{(s)}, \quad \frac{\sum^{nj}_{i=1} (y_{ij}-\theta_j^{(s)})^2}{2} +\beta^{(s)} \right)
\]
```{r}
Out <- Hierarchical_2(food1, 25000, 20)
Theta_post_H2 <- Out$Theta_post_H2
MuTaAlBet <- Out$MuTaAlBet
Sigma_post_H2 <- Out$Sigma_post_H2
accept <- Out$accept
prop <- round(mean(accept),2)*100
```
In the function `Hierarchical_2` we also stored the proportion of accepted values of $\alpha$ in the Metropolis Hastings step, to be able to tune $\delta$ accordingly. \hfill\break
After tuning, we set $\delta = 20$, a good value which allows for a `r toString(prop)`% acceptance rate of $\alpha$.
To analyze the output of our algorithm we have drawn some plots
```{r}
# Plot
# MuTaAlBet
S <- 25000
par(mfrow = c(2,2))
for (i in 1:4) {
plot(1:S, MuTaAlBet[,i], type = "l", xlim = c(0, 2000),col="deepskyblue4")
abline(h = mean(MuTaAlBet[,i]),col="chocolate3", lwd=0.8 )
mode_1 <- density(MuTaAlBet[,i])$x[which.max(density(MuTaAlBet[,i])$y)]
abline(h = mode_1,col="darkolivegreen1", lwd=0.8 )
}
```
Above are the traceplots of $\mu$, $\tau^2$, $\alpha$, $\beta$ respectively. There seems to be no issues with them but we proceed anyway in checking the autocorrelation functions (acf from here on) plots to be sure there is no autocorrelation.
```{r}
par(mfrow = c(2,2))
for(i in 1:4) {
acf(MuTaAlBet[,i], 100, main = "")
}
```
Unfortunately all four the parameters present us with a quite slowly decreasing acf, we should thin their chains to try to reduce autocorrelation.
```{r}
S = 25000
Theta_post_H2_T <- Theta_post_H2[seq(1,S, by = 5),]
MuTaAlBet_T <- MuTaAlBet[seq(1,S, by = 5),]
Sigma_post_H2_T <- Sigma_post_H2[seq(1,S, by = 5),]
```
After thinning the output by 5 observations, i.e., keeping just one observation in five, we can check again the acf plots
```{r}
par(mfrow = c(2,2))
for(i in 1:4) {
acf(MuTaAlBet_T[,i], 100, main = "")
}
```
The picture has greatly improved: the acf's shrinks much faster than before.
We can now take a look at the histograms of the approximated posterior distribution of $\theta_j$
```{r}
# Theta_post_H2_T
par(mfrow = c(2,2))
idx <- c(1,3,7,9)
for(i in idx) {
hist(Theta_post_H2_T[,i], breaks = 100, col = "aquamarine3",
border = "deepskyblue4", main = "")
abline(v = y_bar[i] ,col="chocolate3", lwd=2 )
mode_1 <- density(Theta_post_H2_T[,i])$x[which.max(density(Theta_post_H2_T[,i])$y)]
abline(v = mode_1,col="darkolivegreen1", lwd=2 )
abline(v = apply(Theta_post_H2_T, 2, quantile, 0.05)[i], lty = 2)
abline(v = apply(Theta_post_H2_T, 2, quantile, 0.95)[i], lty = 2)
}
```
These are the histograms of the first, third, seventh and ninth group, plotted along with group's sample mean and approximated posterior mode (orange and green lines respectively). \hfill\break
From the picture we can notice that the first, third and last group histograms are fairly concentrated around the sample mean value whereas the seventh group, that of meat, has quite a far distribution with respect to its sample mean.
This is because allowing each group having its own variance changes the posterior parameters of $\theta_j$ this way
$$\mu_n= \frac{n_j\bar{y_j}/\sigma^{2(s-1)}_j + \mu^{(s)}/\tau^{2(s)}}{n_j/\sigma^{2(s-1)}_j + 1/\tau^{2(s)}}$$
$$\tau_n^2= (n_j/\sigma^{2(s-1)}_j + 1/\tau^{2(s)})^{-1} $$
so the posterior expectation is a weighted average between the sample mean $\bar{y_j}$ and the sampled value of $\mu^{(s)}$, whom we assigned weakly informative prior parameters.
So the sampled value $\mu^{(s)}$ will be around its posterior expectation $\rho_n = \frac{\mu_0/\gamma_0 \ + \ m/\tau^2\mathbb{E}(\bar{y_j})}{1/\gamma_0 \ + \ m/\tau_0^2}$ = `r toString(mean(MuTaAlBet_T[,1]))`, even lower than the initial value $\mu_0 = 12$.
```{r}
{plot(density(MuTaAlBet_T[,1]), col = "aquamarine3",
border = "deepskyblue4", type = "l", xlim = c(0,25), lwd = 2,
main = "")
lines(seq(0, 25, by = 0.01), dnorm(seq(0, 25, by = 0.01), 12, 6),
col = "darkolivegreen3", lwd = 2)
legend("topright", legend = c("prior", "posterior"),
col = c("darkolivegreen3","aquamarine3"), lwd = c(2,2))}
post_mean_H2 <- apply(Theta_post_H2_T, 2, mean)
knitr::kable(rbind(Post_Exp = post_mean_H2[idx], S2 = sv_j[idx]))
```
Because of this the posterior expectation $\mu_n$ of high sample variance $S_j^2$ groups gets drawn towards $\mu^{(s)}$, weighting less the sample mean $\bar{y_j}$. \hfill\break
Indeed the drawn value $\sigma^{2(s-1)}_j$ is also from a weakly-informative full conditional and so will reflect the data information (i.e. the sample variance $S_j^2$).
To check this last fact we can look at draws of $\sigma_j^2$ from its full conditional.
```{r}
# Sigma_post_H2
par(mfrow = c(2,2))
# sigma2_j 1
hist(Sigma_post_H2[,1], breaks = 500, col = "aquamarine3",
border = "deepskyblue4", xlim = c(0,20), main = "")
abline(v = mean(Sigma_post_H2[,1]),col="chocolate3", lwd=3 )
mode_1 <- density(Sigma_post_H2[,1])$x[which.max(density(Sigma_post_H2[,1])$y)]
abline(v = mode_1,col="darkolivegreen1", lwd=3 )
# sigma2_j 3
hist(Sigma_post_H2[,3], breaks = 500, col = "aquamarine3",
border = "deepskyblue4", xlim = c(0,50), main = "")
abline(v = mean(Sigma_post_H2[,3]),col="chocolate3", lwd=3 )
mode_1 <- density(Sigma_post_H2[,3])$x[which.max(density(Sigma_post_H2[,3])$y)]
abline(v = mode_1,col="darkolivegreen1", lwd=3 )
# sigma2_j 7
hist(Sigma_post_H2[,7], breaks = 1000, col = "aquamarine3",
border = "deepskyblue4", xlim = c(0,5000), main = "")
abline(v = mean(Sigma_post_H2[,7]),col="chocolate3", lwd=3 )
mode_1 <- density(Sigma_post_H2[,7])$x[which.max(density(Sigma_post_H2[,7])$y)]
abline(v = mode_1,col="darkolivegreen1", lwd=3 )
# sigma2_j 9
hist(Sigma_post_H2[,9], breaks = 1000, col = "aquamarine3",
border = "deepskyblue4", xlim = c(0,200), main = "")
abline(v = mean(Sigma_post_H2[,9]),col="chocolate3", lwd=3 )
mode_1 <- density(Sigma_post_H2[,9])$x[which.max(density(Sigma_post_H2[,9])$y)]
abline(v = mode_1,col="darkolivegreen1", lwd=3 )
sv_j[idx]
```
From these histograms and the sample variances $S_j^2$ printed with them, we can clearly see how even if we have randomness we can state with a high degree of confidence that $\mu_n$ of high sample variance groups weight less $\bar{y_j}$ than small sample variance groups. \hfill\break
This fact can be noticed even looking at the plot of the empirical posterior expectation of $\sigma_j^2$ vs. the shrinkage where the difference between $\mu_n$ and $\bar{y_j}$ grows with variance
```{r}
{plot(log(apply(Sigma_post_H2_T, 2, mean)), (y_bar - post_mean_H2))
for(i in 1:m) {
if(i == 7){
text(log(apply(Sigma_post_H2_T, 2, mean))[i], (y_bar - post_mean_H2)[i]-0.8, labels = i)
}
else{
text(log(apply(Sigma_post_H2_T, 2, mean))[i], (y_bar - post_mean_H2)[i]+0.8, labels = i)
}
}
abline(h = 0, col="darkred")}
```
### Prior vs. posterior plots
```{r}
# Prior vs. posterior plots
Theta_marg_H2 = marginal_prior_H1H2(N = 5000) # draws from the marginal prior
# of theta_j
par(mfrow = c(2,2))
for(j in idx){
plot(density(Theta_post_H2_T[,j],adj=2),main="",