-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path404-paquete-inla.Rmd
218 lines (166 loc) · 7.13 KB
/
404-paquete-inla.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
# Paquete **INLA**
El paquete **INLA** (integrated nested Laplace approximation) se utiliza para hacer inferencia bayesiana aproximada de diversos modelos. Al visitar este [enlace](https://www.r-inla.org/home) se encontrará un gran contenido que le podría servir para conocer más sobre INLA.
En el enlace de abajo se puede acceder a un libro muy interesante sobre modelos mixtos con INLA.
https://becarioprecario.bitbucket.io/inla-gitbook/index.html
## Ejemplo: modelo Poisson con intercepto aleatorio {-}
En este ejemplo vamos a simular $n_i=50$ observaciones para $G=10$ grupos (en total 500 obs) que tengan la estructura mostrada abajo. El objetivo del ejemplo es ilustrar el uso de la función `inla` para estimar los parámetros del modelo.
\begin{align*}
y_{ij} | b_0 &\sim Poisson(\mu_{ij}) \\
\log(\mu_{ij}) &= 4 - 6 x_{ij} + b_{0i} \\
b_{0} &\sim N(0, \sigma^2_{b0}=4) \\
x_{ij} &\sim U(0, 1)
\end{align*}
El vector de parámetros de este modelo es $\boldsymbol{\Theta}=(\beta_0=4, \beta_1=-6, \sigma^2_{b0}=4)^\top$.
<div style="-moz-box-shadow: 1px 1px 3px 2px #000000;
-webkit-box-shadow: 1px 1px 3px 2px #000000;
box-shadow: 1px 1px 3px 2px #000000;">
```{block2, type='rmdexercise'}
Solución.
```
</div>
El código para simular las observaciones se muestra a continuación. Se fijó la semilla con `set.seed(1234)` para que el lector pueda replicar el ejemplo.
```{r}
gen_data_1 <- function() {
ni <- 50
G <- 10
nobs <- ni * G
grupo <- factor(rep(x=1:G, each=ni))
obs <- rep(x=1:ni, times=G)
x <- runif(n=nobs, min=0, max=1)
b0 <- rnorm(n=G, mean=0, sd=sqrt(4)) # Intercepto aleatorio
b0 <- rep(x=b0, each=ni) # El mismo intercepto aleatorio pero repetido
media <- exp(4 - 6 * x + b0)
y <- rpois(n=nobs, lambda=media)
datos <- data.frame(obs, grupo, b0, x, y)
datos
}
set.seed(1234)
datos <- gen_data_1()
head(datos)
```
Para estimar los parámetros del modelo con INLA se usa el siguiente código.
```{r eval = FALSE, echo = TRUE}
library(INLA)
fit1 <- inla(y ~ x + f(grupo, model = "iid"),
data = datos, family = "poisson")
```
Aplicando la función `summary` sobre el objeto `fit1` se obtiene:
```{r eval=FALSE}
summary(fit1)
```
```
Time used:
Pre = 0.321, Running = 1.7, Post = 0.0978, Total = 2.12
Fixed effects:
mean sd 0.025quant 0.5quant 0.975quant mode kld
(Intercept) 4.402 0.555 3.292 4.403 5.509 NA 0
x -6.007 0.048 -6.102 -6.007 -5.913 NA 0
Random effects:
Name Model
grupo IID model
Model hyperparameters:
mean sd 0.025quant 0.5quant 0.975quant mode
Precision for grupo 0.40 0.175 0.138 0.374 0.787 NA
Marginal log-Likelihood: -1110.13
is computed
Posterior summaries for the linear predictor and the fitted values are computed
(Posterior marginals needs also 'control.compute=list(return.marginals.predictor=TRUE)')
```
De la salida anterior se tiene que $\hat{\boldsymbol{\Theta}}=(\hat{\beta_0}=4.402, \hat{\beta_1}=-6.007, \hat{\sigma}^2_{b0}=(1/0.40)^2=2.5^2)^\top$ mientras que $\boldsymbol{\Theta}=(\beta_0=4, \beta_1=-6, \sigma^2_{b0}=4)^\top$.
## Ejemplo: modelo Poisson con intercepto y pendiente aleatoria {-}
En este ejemplo vamos a simular $n_i=50$ observaciones para $G=10$ grupos (en total 500 obs) que tengan la estructura mostrada abajo. El objetivo del ejemplo es ilustrar el uso de la función `inla` para estimar los parámetros del modelo.
\begin{align*}
y_{ij} | b_0, b_1 &\sim Poisson(\mu_{ij}) \\
\log(\mu_{ij}) &= 2 - 3 x_{ij} + b_{0i} + b_{1i} x_{ij} \\
\left (
\begin{matrix}
b_{0} \\ b_{1}
\end{matrix}
\right ) &\sim
N\left ( \left [ \begin{matrix}
0 \\ 0
\end{matrix} \right ],
\left [ \begin{matrix}
\sigma^2_{b0}=0.7 & \sigma_{b01}=0.5 \\
\sigma_{b01} & \sigma^2_{b1}=0.6
\end{matrix} \right ]
\right ) \\
x_{ij} &\sim U(0, 1)
\end{align*}
El vector de parámetros de este modelo es $\boldsymbol{\Theta}=(\beta_0=2, \beta_1=-3, \sigma_{b0}^2=0.7, \sigma_{b1}^2=0.6, \sigma_{b01}=0.5)^\top$.
<div style="-moz-box-shadow: 1px 1px 3px 2px #000000;
-webkit-box-shadow: 1px 1px 3px 2px #000000;
box-shadow: 1px 1px 3px 2px #000000;">
```{block2, type='rmdexercise'}
Solución.
```
</div>
El código para simular las observaciones se muestra a continuación.
```{r}
gen_data_2 <- function() {
ni <- 50
G <- 30
nobs <- ni * G
grupo <- factor(rep(x=1:G, each=ni))
obs <- rep(x=1:ni, times=G)
x <- runif(n=nobs, min=0, max=1)
Sigma <- matrix(c(0.7, 0.5, # Matriz de var-cov
0.5, 0.6), ncol=2, nrow=2)
b <- MASS::mvrnorm(n=G, mu=rep(0, 2), Sigma=Sigma) # Simulando b0 y b1
b <- apply(b, MARGIN=2, function(c) rep(c, each=ni)) # Replicando
b0 <- as.vector(b[, 1]) # Separando los b0
b1 <- as.vector(b[, 2]) # Separando los b1
media <- exp(2 - 3 * x + b0 + b1 * x)
y <- rpois(n=nobs, lambda=media)
datos <- data.frame(obs, grupo=as.factor(grupo), b0, b1, x, y)
datos
}
set.seed(1234)
datos <- gen_data_2()
head(datos)
```
Debemos preparar la base de datos para que se pueda ajustar un modelo con intercepto y pendiente aleatoria. Para mayores detalles de la preparación se puede consultar @wang2018bayesian página 110.
```{r}
n_groups <- length(levels(datos$grupo))
datos$numid <- as.numeric(datos$grupo)
datos$slopeid <- datos$numid + n_groups
```
Para estimar los parámetros del modelo con INLA se usa el siguiente código.
```{r eval = FALSE, echo = TRUE}
library(INLA)
formula <- y ~ x + f(numid, model="iid2d", n = 2*n_groups) +
f(slopeid, x, copy="numid")
fit2 <- inla(formula,
data = datos, family = "poisson",
control.predictor = list(compute = TRUE))
```
Aplicando la función `summary` sobre el objeto `fit2` se obtiene:
```{r eval=FALSE}
summary(fit2)
```
```
Time used:
Pre = 0.251, Running = 0.404, Post = 0.243, Total = 0.898
Fixed effects:
mean sd 0.025quant 0.5quant 0.975quant mode kld
(Intercept) 1.930 0.133 1.665 1.931 2.190 1.931 0
x -3.069 0.186 -3.453 -3.063 -2.717 -3.063 0
Random effects:
Name Model
numid IID2D model
slopeid Copy
Model hyperparameters:
mean sd 0.025quant 0.5quant
Precision for numid (component 1) 2.170 0.601 1.200 2.099
Precision for numid (component 2) 1.427 0.500 0.679 1.349
Rho1:2 for numid 0.688 0.122 0.402 0.705
0.975quant mode
Precision for numid (component 1) 3.549 1.970
Precision for numid (component 2) 2.623 1.207
Rho1:2 for numid 0.873 0.742
Marginal log-Likelihood: -2437.24
is computed
Posterior summaries for the linear predictor and the fitted values are computed
(Posterior marginals needs also 'control.compute=list(return.marginals.predictor=TRUE)')
```
De la salida anterior se tiene que $\hat{\boldsymbol{\Theta}}=(\hat{\beta_0}=1.930, \hat{\beta_1}=-3.069, \hat{\sigma}^2_{b0}=1/2.170=0.4608, \hat{\sigma}^2_{b1}=1/1.427=0.7001, \hat{\sigma}_{b01}=0.688 * (1/2.170) * (1/1.427)=0.2222)^\top$ mientras que $\boldsymbol{\Theta}=(\beta_0=2, \beta_1=-3, \sigma_{b0}^2=0.7, \sigma_{b1}^2=0.6, \sigma_{b01}=0.5)^\top$.