Chapter 4 - Geocentric Models

This chapter introduced the simple linear regression model, a framework for estimating the association between a predictor variable and an outcome variable. The Gaussian distribution comprises the likelihood in such models, because it counts up the relative numbers of ways different combinations of means and standard deviations can produce an observation. To fit these models to data, the chapter introduced quadratic approximation of the posterior distribution and the tool quap. It also introduced new procedures for visualizing prior and posterior distributions.

Place each answer inside the code chunk (grey box). The code chunks should contain a text response or a code that completes/answers the question or activity requested. Make sure to include plots if the question requests them. Problems are labeled Easy (E), Medium (M), and Hard(H).

Finally, upon completion, name your final output .html file as: YourName_ANLY505-Year-Semester.html and publish the assignment to your R Pubs account and submit the link to Canvas. Each question is worth 5 points.

Questions

4E1. In the model definition below, which line is the likelihood? \[\begin{align} \ y_i ∼ Normal(μ, σ) \\ \ μ ∼ Normal(0, 10) \\ \ σ ∼ Exponential(1) \\ \end{align}\]

#y_i ∼ Normal(μ, σ is the likelihood.

4E2. In the model definition just above, how many parameters are in the posterior distribution?

#There are two parameters to be estimated in this model: 𝜇 and 𝜎. 

4E3. Using the model definition above, write down the appropriate form of Bayes’ theorem that includes the proper likelihood and priors.

#Pr(𝜇,𝜎|𝑦)=∏𝑖Normal(𝑦𝑖|𝜇,𝜎)Normal(𝜇|0,10)Uniform(𝜎|0,10)/∫∫∏𝑖Normal(ℎ𝑖|𝜇,𝜎)Normal(𝜇|0,10)Uniform(𝜎|0,10)𝑑𝜇𝑑𝜎 

4E4. In the model definition below, which line is the linear model? \[\begin{align} \ y_i ∼ Normal(μ, σ) \\ \ μ_i = α + βx_i \\ \ α ∼ Normal(0, 10) \\ \ β ∼ Normal(0, 1) \\ \ σ ∼ Exponential(2) \\ \end{align}\]

#the linear model is μ_i = α + βx_i

4E5. In the model definition just above, how many parameters are in the posterior distribution?

#There are 3 parameters in the posterior distribution: 𝛼, 𝛽, and 𝜎.

4M1. For the model definition below, simulate observed y values from the prior (not the posterior). Make sure to plot the simulation. \[\begin{align} \ y_i ∼ Normal(μ, σ) \\ \ μ ∼ Normal(0, 10) \\ \ σ ∼ Exponential(1) \\ \end{align}\]

sample_mu <- rnorm(1e4, 0, 10)
sample_sigma <- runif(1e4, 0, 10)
prior_y <- rnorm(1e4, sample_mu, sample_sigma)
dens(prior_y)

4M2. Translate the model just above into a quap formula.

formula <- alist(
  y ~ dnorm(mu, sigma),
  mu ~ dnorm(0, 10),
  sigma ~ dunif(0, 10)
)
4M3. Translate the quap model formula below into a mathematical model definition:

y ~ dnorm( mu , sigma ),
mu <- a + b*x,
a ~ dnorm( 0 , 10 ),
b ~ dunif( 0 , 1 ),
sigma ~ dexp( 1 )

flist <- alist(
  y ~ dnorm(mu, sigma),
  mu <- a + b*x,
  a ~ dnorm(0, 50),
  b ~ dunif(0, 10),
  sigma ~ dunif(0, 50)
)

4M4. A sample of students is measured for height each year for 3 years. After the third year, you want to fit a linear regression predicting height using year as a predictor. Write down the mathematical model definition for this regression, using any variable names and priors you choose. Be prepared to defend your choice of priors. Simulate from the priors that you chose to see what the model expects before it sees the data. Do this by sampling from the priors. Then consider 50 students, each simulated with a different prior draw. For each student simulate 3 years. Plot the 50 linear relationships with height(cm) on the y-axis and year on the x-axis. What can we do to make these priors more likely?

#linear model μ = α + βx
#1. for α, center at 160cm with an SD of 20cm
#2. for β, 4/year with a SD of 2cm a year
#3. for μ, distribution from 0-50cm

4M5. Now suppose I remind you that every student got taller each year. Does this information lead you to change your choice of priors? How? Again, simulate from the priors and plot.

# for α, center at 165cm with an SD of 20cm

4M6. Now suppose I tell you that the variance among heights for students of the same age is never more than 64cm. How does this lead you to revise your priors?

# it means the variance of α never more than 8cm, so the priors will not be revised.

4M7. Refit model m4.3 from the chapter, but omit the mean weight xbar this time. Compare the new model’s posterior to that of the original model. In particular, look at the covariance among the parameters. Show the pairs() plot. What is different? Then compare the posterior predictions of both models.

# load data
data(Howell1)
data1 <- Howell1
data2 <- data1[data1$age >= 18 , ]
mean_bar <- mean(data2$weight)
# model m4.3
model_1 <- quap(
                alist(
                      height ~ dnorm( mu , sigma ) , 
                      mu <- alpha + beta*( weight - mean_bar ) , 
                      alpha ~ dnorm( 178 , 20 ) ,
                      beta ~ dlnorm( 0 , 1 ) ,
                      sigma ~ dunif( 0 , 50 )), 
                data=data2 )

summary(model_1)
##              mean         sd        5.5%       94.5%
## alpha 154.6013675 0.27030764 154.1693636 155.0333713
## beta    0.9032809 0.04192363   0.8362788   0.9702829
## sigma   5.0718805 0.19115474   4.7663783   5.3773827
# Compared to the model with xbar, a is with a much smaller mean but higher sd.
post <- extract.samples(model_1)
mu.link <- function(weight) post$alpha + post$beta*( weight - mean_bar ) 
weight.seq <- seq( from=25 , to=70 , by=1 )
mu <- sapply( weight.seq , mu.link )
mu.mean <- apply( mu , 2 , mean )
mu.CI <- apply( mu , 2 , PI , prob=0.89)
mu.HPDI <- apply( mu , 2 , HPDI , prob=0.89)
sim.height <- sim( model_1 , data=list(weight=weight.seq) )
height.PI <- apply( sim.height , 2 , PI , prob=0.89 )

plot( height ~ weight , data2 , col=col.alpha(rangi2,0.5) )
#model m4.7
model_2 <- quap(
              alist(
                    height ~ dnorm( mu , sigma ) , 
                    mu <- alpha + beta*weight, 
                    alpha ~ dnorm( 178 , 20 ) ,
                    beta ~ dlnorm( 0 , 1 ) ,
                    sigma ~ dunif( 0 , 50 )
                    ), 
              data=data2 )

summary(model_2)
##             mean         sd        5.5%       94.5%
## alpha 114.534315 1.89774618 111.5013497 117.5672796
## beta    0.890730 0.04175796   0.8239927   0.9574673
## sigma   5.072716 0.19124864   4.7670634   5.3783679
post <- extract.samples(model_2)
mu.link <- function(weight) post$alpha + post$beta*weight 
weight.seq <- seq( from=25 , to=70 , by=1 )
mu <- sapply( weight.seq , mu.link )
mu.mean <- apply( mu , 2 , mean )
mu.CI <- apply( mu , 2 , PI , prob=0.89)
mu.HPDI <- apply( mu , 2 , HPDI , prob=0.89)
sim.height <- sim( model_2 , data=list(weight=weight.seq) )
height.PI <- apply( sim.height , 2 , PI , prob=0.89 )

plot( height ~ weight , data2 , col=col.alpha(rangi2,0.5) )

lines( weight.seq , mu.mean )

shade( mu.HPDI , weight.seq )

4M8. In the chapter, we used 15 knots with the cherry blossom spline. Increase the number of knots and observe what happens to the resulting spline. Then adjust also the width of the prior on the weights—change the standard deviation of the prior and watch what happens. What do you think the combination of knot number and the prior on the weights controls?

library(splines)
data(cherry_blossoms)
d <- cherry_blossoms
d2 <- d[complete.cases(d$temp),]

# 15 knots
numknots<-15
knots<-quantile(d2$year,probs=seq(0,1,length.out=numknots))
B <- bs(d2$year, knots=knots[-c(1,numknots)], degree=3, intercept=TRUE)

m4.7 <- quap(alist(T ~ dnorm(mu, sigma), 
                   mu <- a + B%*%w, 
                   a ~ dnorm(6, 10), 
                   w ~ dnorm(0, 1), 
                   sigma ~ dexp(1)), 
             data=list(T=d2$temp, B=B), 
             start=list(w=rep(0, ncol(B))))

post <- extract.samples(m4.7) 
w <- apply(post$w, 2, mean) 
plot(NULL, xlim=range(d2$year), ylim=c(-2,2), xlab="year", ylab="basis * weight") 
for (i in 1:ncol(B)) 
   lines(d2$year, w[i]*B[,i])

mu <- link(m4.7) 
mu_PI <- apply(mu, 2, PI, 0.97) 
plot(d2$year, d2$temp, col=col.alpha(rangi2,0.3), pch=16) 
shade(mu_PI, d2$year, col=col.alpha("black",0.5))

# 30 knots
numknots<-30
knots<-quantile(d2$year,probs=seq(0,1,length.out=numknots))
B <- bs(d2$year, knots=knots[-c(1,numknots)], degree=3, intercept=TRUE)

m4.7 <- quap(alist(T ~ dnorm(mu, sigma), 
                   mu <- a + B%*%w, 
                   a ~ dnorm(6, 10), 
                   w ~ dnorm(0, 1), 
                   sigma ~ dexp(1)), 
             data=list(T=d2$temp, B=B), 
             start=list(w=rep(0, ncol(B))))

post <- extract.samples(m4.7)

w <- apply(post$w, 2, mean) 
plot(NULL, xlim=range(d2$year), ylim=c(-2,2), xlab="year", ylab="basis * weight") 
for (i in 1:ncol(B)) 
   lines(d2$year, w[i]*B[,i])

mu <- link(m4.7) 
mu_PI <- apply(mu, 2, PI, 0.97) 
plot(d2$year, d2$temp, col=col.alpha(rangi2,0.3), pch=16) 
shade(mu_PI, d2$year, col=col.alpha("black",0.5))

# 30 knots with SD of B increased to 10
numknots<-30
knots<-quantile(d2$year,probs=seq(0,1,length.out=numknots))
B <- bs(d2$year, knots=knots[-c(1,numknots)], degree=3, intercept=TRUE)

m4.7 <- quap(alist(T ~ dnorm(mu, sigma), 
                   mu <- a + B%*%w, 
                   a ~ dnorm(6, 10), 
                   w ~ dnorm(0, 10), 
                   sigma ~ dexp(1)), 
             data=list(T=d2$temp, B=B), 
             start=list(w=rep(0, ncol(B))))

post <- extract.samples(m4.7)

w <- apply(post$w, 2, mean) 
plot(NULL, xlim=range(d2$year), ylim=c(-2,2), xlab="year", ylab="basis * weight") 
for (i in 1:ncol(B)) 
   lines(d2$year, w[i]*B[,i])

mu <- link(m4.7) 
mu_PI <- apply(mu, 2, PI, 0.97) 
plot(d2$year, d2$temp, col=col.alpha(rangi2,0.3), pch=16) 
shade(mu_PI, d2$year, col=col.alpha("black",0.5))

# more number of knots makes the line less smooth, bigger SD of the parameter makes the line thicker.

4H2. Select out all the rows in the Howell1 data with ages below 18 years of age. If you do it right, you should end up with a new data frame with 192 rows in it.

  1. Fit a linear regression to these data, using quap. Present and interpret the estimates. For every 10 units of increase in weight, how much taller does the model predict a child gets?

  2. Plot the raw data, with height on the vertical axis and weight on the horizontal axis. Superimpose the MAP regression line and 89% interval for the mean. Also superimpose the 89% interval for predicted heights.

  3. What aspects of the model fit concern you? Describe the kinds of assumptions you would change, if any, to improve the model. You don’t have to write any new code. Just explain what the model appears to be doing a bad job of, and what you hypothesize would be a better model.

d2 <- Howell1[Howell1$age < 18, ]
nrow(d2)
## [1] 192
#a
formula <- alist(
  height ~ dnorm(mu, sigma),
  mu <- a + b * weight,
  a ~ dnorm(110, 30),
  b ~ dnorm(0, 10),
  sigma ~ dunif(0, 60)
)
m <- map(formula, data = d2)
precis(m, corr = TRUE)
##            mean        sd      5.5%     94.5%
## a     58.335129 1.3956937 56.104540 60.565717
## b      2.715296 0.0682320  2.606248  2.824344
## sigma  8.437019 0.4305465  7.748922  9.125115
# For every 10 units of increase in weight, the child is expected to be 2.71 * 10 = 27.1 cm taller.
#b
plot(height ~ weight, data = d2, col = col.alpha(rangi2, 0.3))

weight.seq <- seq(from = min(d2$weight), to = max(d2$weight), by = 1)
mu <- link(m, data = data.frame(weight = weight.seq))
mu.mean <- apply(mu, 2, mean)
mu.HPDI <- apply(mu, 2, HPDI, prob = 0.89)
lines(weight.seq, mu.mean)
shade(mu.HPDI, weight.seq)

sim.height <- sim(m, data = list(weight = weight.seq))
height.HPDI <- apply(sim.height, 2, HPDI, prob = 0.89)
shade(height.HPDI, weight.seq)

#c
#It overestimates height at both lower (<10) and higher (>30) weights and underestimates height for most middle (10-30) weights.
#The assumption is that that the relationship between 𝜇 and weight is linear. A polynomial regression might have a better performance.