-
Notifications
You must be signed in to change notification settings - Fork 1
/
house_price.Rmd
312 lines (218 loc) · 5.44 KB
/
house_price.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
# 房屋价格 {#house-price}
```{r}
library(tidyverse)
library(tidybayes)
library(rstan)
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
```
```{r}
d <- read_csv("./rawdata/house_train.csv")
glimpse(d)
```
```{r}
# Load data, select variables, apply log transformation
df <- read_csv("./rawdata/house_train.csv") %>%
select("SalePrice", "LotArea", "Neighborhood") %>%
mutate(
log_sales_price = log(SalePrice),
log_lot_area = log(LotArea),
neighbourhood = as.integer(as.factor(Neighborhood))
)
head(df)
```
```{r}
df %>% count(neighbourhood)
```
```{r}
df %>%
ggplot(aes(x = log_lot_area, y = log_sales_price)) +
geom_point(colour = "blue") +
geom_smooth(method = lm, se = FALSE, formula = "y ~ x")
```
```{r}
df %>%
ggplot(aes(x = log_lot_area, y = log_sales_price)) +
geom_point(aes(colour = neighbourhood)) +
geom_smooth(method = lm, se = FALSE, formula = "y ~ x")
```
```{r}
df %>%
ggplot(aes(x = log_lot_area, y = log_sales_price)) +
geom_point(colour = "blue") +
geom_smooth(method = lm, se = FALSE, formula = "y ~ x", fullrange = TRUE) +
facet_wrap(~Neighborhood) +
theme(strip.background = element_blank())
```
$$
\begin{align}
y_i &\sim Normal(\mu_i, \sigma) \\
\mu_i &= \alpha_{j} + \beta * x_i \\
\alpha_j & \sim Normal(0, 1)\\
\beta & \sim Normal(0, 1) \\
\sigma &\sim \exp(1)
\end{align}
$$
```{r}
df <- df %>%
mutate(
log_lot_area_z = as.vector(scale(log_lot_area)),
log_sales_price_z = as.vector(scale(log_sales_price))
)
df
```
```{r, warning=FALSE, message=FALSE}
stan_program <- "
data {
int<lower=1> n;
int<lower=1> n_neighbour;
int<lower=1> neighbour[n];
vector[n] lot;
vector[n] price;
int<lower = 0, upper = 1> run_estimation;
}
parameters {
vector[n_neighbour] alpha;
real beta;
real<lower=0> sigma;
}
model {
vector[n] mu;
for (i in 1:n) {
mu[i] = alpha[neighbour[i]] + beta * lot[i];
}
sigma ~ exponential(1);
alpha ~ normal(0, 1);
beta ~ normal(0, 1);
if(run_estimation==1) {
target += normal_lpdf(price | mu, sigma);
}
}
generated quantities {
vector[n] log_lik; //log likelihood
vector[n] y_hat;
for (j in 1:n) {
log_lik[j] = normal_lpdf(price | alpha[neighbour[j]] + beta * lot[j], sigma);
y_hat[j] = normal_rng(alpha[neighbour[j]] + beta * lot[j], sigma);
}
}
"
stan_data <- df %>%
tidybayes::compose_data(
n_neighbour = n_distinct(neighbourhood),
neighbour = neighbourhood,
price = log_sales_price_z,
lot = log_lot_area_z,
run_estimation = 0
)
mod_only_prior <- stan(model_code = stan_program, data = stan_data)
```
```{r}
df_random_draw <-
as.data.frame(mod_only_prior) %>%
slice_sample(n = 1)
y_sim <- df_random_draw %>%
select(contains("y_hat")) %>%
pivot_longer(everything()) %>%
pull(value)
y_sim %>%
as.vector() %>%
length()
```
```{r}
true_parameters <- df_random_draw %>%
select(contains(c("alpha", "beta", "sigma")))
true_parameters
true_parameters %>%
pivot_longer(everything()) %>%
rename(parameters = name)
```
先验概率检测:模型能否(还原或者包括)模拟时用的参数?
- 第一次先不likelihood运算, 只是用**指定的先验概率**模拟 `y_hat` 数据
- 然后用模拟的 `y_hat` 数据**替换**原始`y`数据
- 这次**真**运行
- 看模型输出的**后验概率**,能否(还原或者包括)模拟时**指定的先验概率**
```{r}
stan_data <- df %>%
tidybayes::compose_data(
n_neighbour = n_distinct(neighbourhood),
neighbour = neighbourhood,
price = y_sim %>% as.vector(),
lot = log_lot_area_z,
run_estimation = 1
)
mod_on_fake_dat <- stan(model_code = stan_program, data = stan_data)
```
```{r}
parameter_df <- mod_on_fake_dat %>%
as.data.frame() %>%
select(contains(c("alpha", "beta", "sigma"))) %>%
pivot_longer(everything()) %>%
rename(parameters = name)
parameter_df %>% head()
```
```{r}
parameter_df %>%
ggplot(aes(x = value)) +
geom_density(colour = "blue") +
facet_wrap(vars(parameters), scales = "free") +
geom_vline(
data = true_parameters %>%
pivot_longer(everything()) %>%
rename(parameters = name),
aes(xintercept = value), colour = "red"
) +
labs(
title = 'Model Checking - red lines are "true" parameters',
x = ""
) +
theme(strip.background = element_blank())
```
感觉tidybayes::add_fit 比较类似的思想
## now, Estimate model on real data
`run_estimation=1` and run the code to fit the model.
```{r}
stan_data <- df %>%
tidybayes::compose_data(
n_neighbour = n_distinct(neighbourhood),
neighbour = neighbourhood,
price = log_sales_price_z,
lot = log_lot_area_z,
run_estimation = 1
)
mod <- stan(model_code = stan_program, data = stan_data)
```
```{r}
mcmc_combo(
as.array(mod),
combo = c("dens_overlay", "trace"),
pars = c("alpha[1]", "beta", "sigma"),
gg_theme = legend_none()
)
```
```{r}
stan_plot(mod,
show_density = FALSE,
unconstrain = TRUE,
pars = c("alpha", "beta", "sigma")
) +
labs(title = "Posterior distributions of fitted parameters")
```
```{r}
print(mod,
pars = c("alpha", "beta", "sigma"),
probs = c(0.025, 0.50, 0.975),
digits_summary = 3
)
```
## Posterior predictive check
```{r}
df %>%
ggplot(aes(x = log_sales_price_z)) +
geom_density()
```
```{r}
yrep <- extract(mod)[["y_hat"]]
samples <- sample(nrow(yrep), 300)
ppc_dens_overlay(as.vector(df$log_sales_price_z), yrep[samples, ])
```