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 likelihood.

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

# There are 2  posterior distribution given in above example where μ and σ those.

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

#\[Pr(\mu,\sigma |y) =\frac{\prod_{i}Normal(y_{i}|\mu,\sigma)Normal(\mu|0,10)Uniform(\sigma|0,10)}{\int\int\prod_{i}Normal(h_{i}|\mu,\sigma)Normal(\mu|0,10)Uniform(\sigma|0,10)d\mu d\sigma}\]

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}\]

# Linear model : μ_i = α + βx_i

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

# there are 3 posterior distribution given above while α, β, σ are the posterior distribution.

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}\]

mu_sample <- rnorm(10000, 0, 10)
sigma_sample <- runif(10000, 0, 10)
prior_sample <- rnorm(10000, mu_sample, sigma_sample)
dens(prior_sample)

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

quap_formula <- alist(
  y ~ dnorm(mu_sample, sigma_sample),
  mu_sample ~ dnorm(0, 10),
  sigma_sample ~ dexp(1))
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 )

#\[\begin{align} \ y_i ∼ Normal(μ, σ) \\ \ μ_i ∼ α + βx_i \\ \ α ∼ Normal(0, 10) \\ \ β ∼ Uniform(0, 1) \\ \ σ ∼ Exponential(1) \\ \end{align}\]

flist = alist(
  y ~ dnorm(mu_sample, sigma_sample),
  mu_sample = a + b*x,
  a ~ dnorm(0, 50),
  b ~ dunif(0, 10),
  sigma_sample ~ 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?

n <- 10000
a <- rnorm(n, 175, 15)
b <- rnorm(n, 0, 15)
sigma <- runif(n, 3, 50)
height <- rnorm(n, a + b * 0, sigma)
dens(height)

#By below plot,  α follows a normal distribution of 175cm ( approximatly, choosing 15 as standard deviation). I choosed the model to repeat for 1000 times. 
#A point to make sure about the sample that we choose is what kind of data it is I meant what kind of students are included in data and what can be their age, gender ? Age plays an important feature while calculating the statistic.

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.

Sim <- 10000
a <- rnorm(Sim, 130, 15)
b <- rnorm(Sim, 0, 15)
sigma <- runif(Sim, 3, 50)
height <- rnorm(Sim, a + b * 0, sigma)
dens(height)

# Yes, every year that students get taller and this leads to change my priors. I would suggest start by using a smaller average number ( positive ) or may be by using log-normal distribution.

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?

#As we know the variance is square product of σ, 
# hence σ that never exceeds sqrt(64)=8 and can update our prior accordingly:
# σ ∼ Uniform(0,8)
dens(runif(1000, 0, 8))

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.

data(Howell1)

d<-Howell1
d2<-d[d$age>=18, ]
xbar <- mean(d2$weight)

m4.3 <-quap(
alist(
height ~dnorm(mu,sigma),
mu <-a+b*(weight-xbar),
a ~dnorm(178,20),
b ~dlnorm(0,1),
sigma ~dunif(0,50)
) ,data=d2)
precis(m4.3)
##              mean         sd        5.5%       94.5%
## a     154.6013673 0.27030769 154.1693634 155.0333712
## b       0.9032807 0.04192364   0.8362786   0.9702827
## sigma   5.0718815 0.19115484   4.7663791   5.3773838
m4.3n <-quap(alist(
height ~dnorm(mu,sigma),
mu <-a+b,
a ~dnorm(178,20),
b ~dlnorm(0,1),
sigma ~dunif(0,50)
) ,data=d2)
precis(m4.3n)
##              mean        sd        5.5%       94.5%
## a     154.2479651 0.5443298 153.3780209 155.1179094
## b       0.3599195 0.3559849  -0.2090132   0.9288521
## sigma   7.7299088 0.2912519   7.2644321   8.1953856
#By above mean values, by removing weight- xbar the alpha values didn't change much. Infact Beta value is lower ins econd model and sigma is higher in second model.

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?

data(cherry_blossoms) 

my_df <- cherry_blossoms
df_main <- my_df[complete.cases(my_df$doy), ]

library(splines)

num_knots <- 60
knot_list <- quantile(df_main$year, probs=seq(0,1,length.out=num_knots))
B <- bs(df_main$year, knots=knot_list[-c(1,num_knots)] ,degree=3, intercept=TRUE)
ms <- quap(
  alist(
    D ~ dnorm(mu, sigma),
    mu <- a + B %*% w,
    a ~ dnorm(100, 10),
    w ~ dnorm(0, 10),
    sigma ~ dexp(1)
  ), data=list(D=df_main$doy, B=B),
  start = list(w=rep(0, ncol(B)))
)
plot(NULL, xlim=range(df_main$year), ylim=c(0,1), xlab="year", ylab="basis value")
for (i in 1:ncol(B)) lines(df_main$year, B[,i])

ms <- quap(
  alist(
    D ~ dnorm(mu, sigma),
    mu <- a + B %*% w,
    a ~ dnorm(100, 10),
    w ~ dnorm(0, 100),
    sigma ~ dexp(1)
  ), data=list(D=df_main$doy, B=B),
  start = list(w=rep(0, ncol(B)))
)

# The plot clearly states that increasing the number of knots makes the chart look more compressed as because it tries to fit more arches in same area and makes human eye difficult to read. One way to fix is by increasing its width, chart expands and looks better to understand.

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.

data(Howell1)

df <- Howell1
df_main <- df[df$age < 18, ]
nrow(df_main)
## [1] 192
mean_weight <- mean(df_main$weight)
mean_weight
## [1] 18.41419
model_ml <- quap(
  alist(
    height ~ dnorm(mu, sigma),
    mu <- a + b * (weight - xbar),
    a ~ dnorm(156, 20),
    b ~ dlnorm(0, 1),
    sigma ~ dunif(0, 50)
  ),
  data=df_main
)
precis(model_ml)
##             mean         sd       5.5%      94.5%
## a     180.294745 1.90660109 177.247629 183.341862
## b       2.709122 0.06804841   2.600367   2.817876
## sigma   8.437700 0.43064505   7.749446   9.125954
# (A) beta mean for the model is 2.72, this means that for every 10 units, the child is expected to grow 10*2.72 = 27.2cm by above statistic.

# (B)  
# Data for plot
plot(height ~ weight, data = df_main, col = col.alpha(rangi2, 0.3))
weight.seq <- seq(from = min(df_main$weight), to = max(df_main$weight), by = 1)
mu <- link(model_ml, 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(model_ml, data = list(weight = weight.seq))

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

# (C) For question (c) based on above plat, seems like linear machine model did a good job of predicting the line that fits most of its points with its inclination initially. 
# but a bit to concern where the weight > 30 we can observe that the model line didn't predict well.
# we can try to improve this model, by giving more data where weight > 30 or check of these points are outliers of so we need to remove few outliers and re-run the model and see if we can improve the model. 
# An another option would be adding more features or parameter tuning can silghtly help us in this case.
# we can definely choose another model like polynomial and see how it fits the data.