forked from corriebar/Statistical-Rethinking
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapter5a.R
286 lines (225 loc) · 7.03 KB
/
chapter5a.R
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
# Chapter 5 - Spurious Associations
library(rethinking)
data("WaffleDivorce")
d <- WaffleDivorce
# standardize predictior (MedianAgeMarrige)
d$MedianAgeMarriage.s <- (d$MedianAgeMarriage - mean(d$MedianAgeMarriage)) / sd(d$MedianAgeMarriage)
# fit model
m5.1 <- map(
alist(
Divorce ~ dnorm( mu, sigma),
mu <- a + bA*MedianAgeMarriage.s,
a ~ dnorm(10, 10),
bA ~ dnorm(0, 1),
sigma ~ dunif(0,10)
), data=d
)
# compute shaded confidence region
MAM.seq <- seq(from=-3, to=3.5, length.out = 30)
mu <- link(m5.1, data=data.frame(MedianAgeMarriage.s=MAM.seq ) )
mu.PI <- apply(mu, 2, PI)
# plot it all
plot( Divorce ~ MedianAgeMarriage.s, data=d, col=rangi2 )
abline( m5.1 )
shade( mu.PI, MAM.seq)
precis(m5.1)
# same for Marriage Rate
# standardize predictior (Marriage Rate)
d$Marriage.s <- (d$Marriage - mean(d$Marriage)) / sd(d$Marriage)
# fit model
m5.2 <- map(
alist(
Divorce ~ dnorm( mu, sigma),
mu <- a + bR*Marriage.s,
a ~ dnorm(10, 10),
bR ~ dnorm(0, 1),
sigma ~ dunif(0, 10)
), data=d
)
# compute shaded confidence region
mu <- link(m5.2, data=data.frame(Marriage.s=MAM.seq ) )
mu.PI <- apply(mu, 2, PI)
# plot it all
plot( Divorce ~ Marriage.s, data=d, col=rangi2 )
abline( m5.2)
shade( mu.PI, MAM.seq)
# Fit a model with BOTH predictors
m5.3 <- map(
alist(
Divorce ~ dnorm( mu , sigma),
mu <- a + bR*Marriage.s + bA*MedianAgeMarriage.s,
a ~ dnorm( 10, 10) ,
bR ~ dnorm( 0, 1 ) ,
bA ~ dnorm( 0, 1 ) ,
sigma ~ dunif( 0, 10 )
), data=d
)
precis(m5.3)
plot( precis(m5.3) )
# Different plots
# Predictor residual plots
# predict Marriage rate by Median Age Marriage
m5.4 <- map(
alist(
Marriage.s ~ dnorm( mu, sigma) ,
mu <- a + b*MedianAgeMarriage.s ,
a ~ dnorm( 0, 10),
b ~ dnorm(0, 1),
sigma ~ dunif(0, 10)
), data = d
)
# compute residuals:
# comüpute expected value at MAP, for each state
mu.R <- coef(m5.4)['a'] + coef(m5.4)['b']*d$MedianAgeMarriage.s
# compute residuals for each state
m.resid.R <- d$Marriage.s - mu.R
# plot residuals
plot( Marriage.s ~ MedianAgeMarriage.s, d, col=rangi2 )
abline( m5.4 )
# loop over states
for ( i in 1:length(m.resid) ){
x <- d$MedianAgeMarriage.s[i] # x location of line segment
y <- d$Marriage.s[i] # observed endpoint of line segment
# draw the line segment
lines( c(x,x), c(mu.R[i], y), lwd=0.5, col=col.alpha("black", 0.7))
}
# predictor plot (Marriage rate)
plot( d$Divorce ~ m.resid.R, col=rangi2 )
abline( a=coef(m5.3)['a'], b=coef(m5.3)['bR'] )
abline(v=0, lty=2)
# the other way round: predict median age using marriage rate
m5.5 <- map(
alist(
MedianAgeMarriage.s ~ dnorm( mu, sigma) ,
mu <- a + b*Marriage.s ,
a ~ dnorm( 0, 10),
b ~ dnorm(0, 1),
sigma ~ dunif(0, 10)
), data = d
)
# compute residuals:
# compute expected value at MAP, for each state
mu.A <- coef(m5.5)['a'] + coef(m5.4)['b']*d$Marriage.s
# compute residuals for each state
m.resid.A <- d$MedianAgeMarriage.s - mu.A
# plot residuals
plot( MedianAgeMarriage.s ~ Marriage.s, d, col=rangi2 )
abline( m5.5 )
# loop over states
for ( i in 1:length(m.resid) ){
x <- d$Marriage.s[i] # x location of line segment
y <- d$MedianAgeMarriage.s[i] # observed endpoint of line segment
# draw the line segment
lines( c(x,x), c(mu.A[i], y), lwd=0.5, col=col.alpha("black", 0.7))
}
# predictor plot (Median Age)
plot( d$Divorce ~ m.resid.A, col=rangi2)
abline(a=coef(m5.3)['a'], b=coef(m5.3)['bA'])
abline(v=0, lty=2)
# counterfactual plots
# prepare new counterfactual data, holding Median Age fixed, vary Marriage rate
A.avg <- mean( d$MedianAgeMarriage.s )
R.seq <- seq( from=-3, to=3, length.out = 30)
pred.data <- data.frame(Marriage.s = R.seq,
MedianAgeMarriage.s=A.avg)
# compute counterfactual mean divorce (mu)
mu <- link( m5.3, data=pred.data )
mu.mean <- apply(mu, 2, mean )
mu.PI <- apply(mu, 2, PI)
# simulate counterfactual divorce outcomes
R.sim <- sim( m5.3, data=pred.data, n=1e4 )
R.PI <- apply( R.sim, 2, PI)
# display predictions, hiding raw data wit type="n"
plot(Divorce ~ Marriage.s, data=d, type="n")
mtext("MedianAgeMarriage.s = 0")
lines( R.seq, mu.mean )
shade( mu.PI, R.seq )
shade( R.PI, R.seq )
# same the other way, holding Rate fixed, vary Median Age
R.avg <- mean( d$Marriage.s )
A.seq <- seq( from=-3, to=3, length.out = 30)
pred.data <- data.frame(Marriage.s = R.avg,
MedianAgeMarriage.s=A.seq)
# compute counterfactual mean divorce (mu)
mu <- link( m5.3, data=pred.data )
mu.mean <- apply(mu, 2, mean )
mu.PI <- apply(mu, 2, PI)
# simulate counterfactual divorce outcomes
A.sim <- sim( m5.3, data=pred.data, n=1e4 )
A.PI <- apply( A.sim, 2, PI)
# display predictions, hiding raw data wit type="n"
plot(Divorce ~ MedianAgeMarriage.s, data=d, type="n")
mtext("Marriage.s = 0")
lines( A.seq, mu.mean )
shade( mu.PI, A.seq )
shade( A.PI, A.seq )
# Posterior prediction plots
# call link without specifying new data
# so it uses original data
mu <- link( m5.3 )
# summarize samples accross cases
mu.mean <- apply(mu, 2, mean)
mu.PI <- apply( mu, 2, PI )
# simulate observations
# again, no new data, so uses original data
divorce.sim <- sim( m5.3, n=1e4 )
divorce.PI <- apply(divorce.sim, 2, PI)
# plot observed vs predicted (mean) divrorce rate
plot( mu.mean ~ d$Divorce, col=rangi2, ylim=range(mu.PI),
xlab="Observed divorce", ylab="Predicted divroce")
abline(a=0, b=1, lty=2 )
for ( i in 1:nrow(d) )
lines( rep(d$Divorce[i], 2), c(mu.PI[1, i], mu.PI[2, i]), col=rangi2)
identify( x=d$Divorce, y=mu.mean, labels=d$Loc, cex=0.8 )
# residual plot showing the mean prediction error
# compute residuals
divorce.resid <- d$Divorce - mu.mean
# get ordering by divorce rate
o <- order(divorce.resid)
# make the plot
dotchart( divorce.resid[o], labels=d$Loc[o], xlim=c(-6,5), cex=0.6 )
abline(v=0, col=col.alpha("black", 0.2))
for (i in 1:nrow(d) ) {
j <- o[i] # which State in order
lines( d$Divorce[j] - c(mu.PI[1, j], mu.PI[2, j]), rep(i,2) )
points( d$Divorce[j] - c(divorce.PI[1,j], divorce.PI[2, j]), rep(i,2) ,
pch=3, cex=0.6, col="gray")
}
# novel predictor residual plot
d$d.resid <- divorce.resid
d$WaffleHouses.d <- d$WaffleHouses / d$Population
m5.6 <- map(
alist(
d.resid ~ dnorm( mu, sigma) ,
mu <- a + b*WaffleHouses.d ,
a ~ dnorm( 0, 10),
b ~ dnorm(0, 1),
sigma ~ dunif(0, 10)
), data = d
)
waffle.seq <- seq(from=-1, to=42, length.out = 30)
mu <- link(m5.6, data.frame(WaffleHouses.d=waffle.seq) )
mu.mean <- apply(mu, 2, mean)
mu.PI <- apply(mu, 2, PI)
plot(divorce.resid ~ d$WaffleHouses.d, col=rangi2,
xlab="Waffles per capita", ylab="Divorce error")
lines(waffle.seq, mu.mean)
shade(mu.PI, waffle.seq )
# simulate spurious associations
N <- 100
x_real <- rnorm( N)
x_spur <- rnorm( N, x_real )
y <- rnorm( N, x_real )
d <- data.frame(y, x_real, x_spur)
pairs(d)
m5.7 <- map(
alist(
y ~ dnorm( mu, sigma) ,
mu <- a + bR*x_real + bS*x_spur,
a ~ dnorm( 0, 10 ),
bR ~ dnorm(0, 1),
bS ~ dnorm(0, 1),
sigma ~ dunif(0,10)
), data = d
)
plot( precis(m5.7))