-
Notifications
You must be signed in to change notification settings - Fork 219
/
bayesian_lm.Rmd
335 lines (215 loc) · 5.46 KB
/
bayesian_lm.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
# 贝叶斯线性回归 {#bayesian-lm}
```{r, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
warning = FALSE,
message = FALSE,
fig.showtext = TRUE
)
```
## 加载宏包
```{r message = FALSE, warning = FALSE}
library(tidyverse)
library(tidybayes)
library(rstan)
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
```
## 案例
数据是不同天气温度冰淇淋销量,估计气温与销量之间的关系。
```{r}
icecream <- data.frame(
temp = c( 11.9, 14.2, 15.2, 16.4, 17.2, 18.1,
18.5, 19.4, 22.1, 22.6, 23.4, 25.1),
units = c( 185L, 215L, 332L, 325L, 408L, 421L,
406L, 412L, 522L, 445L, 544L, 614L)
)
icecream
```
```{r}
icecream %>%
ggplot(aes(temp, units)) +
geom_point()
```
```{r}
icecream %>%
ggplot(aes(units)) +
geom_density()
```
### lm()
```{r}
fit_lm <- lm(units ~ 1 + temp, data = icecream)
summary(fit_lm)
```
```{r}
confint(fit_lm, level = 0.95)
```
```{r}
# Confidence Intervals
# coefficient +- qt(1-alpha/2, degrees_of_freedom) * standard errors
coef <- summary(fit_lm)$coefficients[2, 1]
err <- summary(fit_lm)$coefficients[2, 2]
coef + c(-1,1)*err*qt(0.975, nrow(icecream) - 2)
```
### 线性模型
线性回归需要满足四个前提假设:
1. **Linearity **
- 因变量和每个自变量都是线性关系
2. **Indpendence **
- 对于所有的观测值,它们的误差项相互之间是独立的
3. **Normality **
- 误差项服从正态分布
4. **Equal-variance **
- 所有的误差项具有同样方差
这四个假设的首字母,合起来就是**LINE**,这样很好记
把这**四个前提**画在一张图中
```{r, out.width = '80%', fig.align='center', echo = FALSE}
knitr::include_graphics(here::here("images", "LINE.png"))
```
### 数学表达式
$$
y_n = \alpha + \beta x_n + \epsilon_n \quad \text{where}\quad
\epsilon_n \sim \operatorname{normal}(0,\sigma).
$$
等价于
$$
y_n - (\alpha + \beta X_n) \sim \operatorname{normal}(0,\sigma),
$$
进一步等价
$$
y_n \sim \operatorname{normal}(\alpha + \beta X_n, \, \sigma).
$$
因此,我们**推荐**这样写线性模型的数学表达式
$$
\begin{align}
y_n &\sim \operatorname{normal}(\mu_n, \,\, \sigma)\\
\mu_n &= \alpha + \beta x_n
\end{align}
$$
## stan 代码
```{r, warning=FALSE, message=FALSE}
stan_program <- "
data {
int<lower=0> N;
vector[N] y;
vector[N] x;
}
parameters {
real alpha;
real beta;
real<lower=0> sigma;
}
model {
y ~ normal(alpha + beta * x, sigma);
alpha ~ normal(0, 10);
beta ~ normal(0, 10);
sigma ~ exponential(1);
}
"
```
```{r, warning=FALSE, message=FALSE}
stan_data <- list(
N = nrow(icecream),
x = icecream$temp,
y = icecream$units
)
fit_normal <- stan(model_code = stan_program, data = stan_data)
```
- 检查 Traceplot
```{r}
traceplot(fit_normal)
```
- 检查结果
```{r}
fit_normal
```
## 理解后验概率
提取后验概率的方法很多
- `rstan::extract()`函数提取样本
```{r}
post_samples <- rstan::extract(fit_normal)
```
`post_samples`是一个列表,每个元素对应一个系数,每个元素都有4000个样本,我们可以用ggplot画出每个系数的后验分布
```{r}
tibble(x = post_samples[["beta"]] ) %>%
ggplot(aes(x)) +
geom_density()
```
- 用`bayesplot`宏包可视化
```{r}
posterior <- as.matrix(fit_normal)
bayesplot::mcmc_areas(posterior,
pars = c("alpha", "beta", "sigma"),
prob = 0.89)
```
- 用`tidybayes`宏包提取样本并可视化,我喜欢用这个,因为它符合`tidyverse`的习惯
```{r}
fit_normal %>%
tidybayes::spread_draws(alpha, beta, sigma) %>%
ggplot(aes(x = beta)) +
tidybayes::stat_halfeye(.width = c(0.66, 0.95)) +
theme_bw()
```
```{r}
fit_normal %>%
tidybayes::spread_draws(alpha, beta, sigma) %>%
ggplot(aes(beta, color = "posterior")) +
geom_density(size = 1) +
stat_function(fun = dnorm,
args = list(mean = 0,
sd = 10),
aes(colour = 'prior'), size = 1) +
xlim(-30, 30) +
scale_color_manual(name = "",
values = c("prior" = "red", "posterior" = "black")
) +
ggtitle("系数beta的先验和后验概率分布") +
xlab("beta")
```
## 小结
```{r, out.width = '80%', fig.align = 'center', echo = FALSE}
knitr::include_graphics(here::here("images", "from_model_to_code.jpg"))
```
## 作业与思考
- 去掉stan代码中的先验信息,然后重新运行,然后与`lm()`结果对比。
- 调整stan代码中的先验信息,然后重新运行,检查后验概率有何变化。
```{md}
alpha ~ normal(100, 5);
beta ~ normal(20, 5);
```
- 修改stan代码,尝试推断上一章的身高分布
```{r, eval=FALSE}
d <- readr::read_rds(here::here('demo_data', "height_weight.rds"))
```
```{r, eval=FALSE}
stan_program <- "
data {
int N;
vector[N] y;
}
parameters {
real mu;
real<lower=0> sigma;
}
model {
mu ~ normal(168, 20);
sigma ~ uniform(0, 50);
y ~ normal(mu, sigma);
}
"
stan_data <- list(
N = nrow(d),
y = d$height
)
fit <- stan(model_code = stan_program, data = stan_data,
iter = 31000,
warmup = 30000,
chains = 4,
cores = 4
)
```
## 参考
- <https://www.tylervigen.com/spurious-correlations>
```{r, echo = F, message = F, warning = F, results = "hide"}
pacman::p_unload(pacman::p_loaded(), character.only = TRUE)
```