Skip to content

Commit

Permalink
Add conjugate priors plot
Browse files Browse the repository at this point in the history
  • Loading branch information
aaaakshat committed Nov 3, 2021
1 parent 968b587 commit 4db0e9c
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions ch08.r
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,40 @@ lines(t, prior, lwd = 4, col="green")
lines(t, q, lwd = 4, col="purple")
grid()

## Conjugate priors

# R code
sigma0 = 0.25
mu0 = 0.0

mu = 1
sigma = 0.25

Nset = c(0, 1, 2, 5, 8, 12, 20)
x0 = sigma * rnorm(100)
posterior = list()

for (i in 1:7) {
N = Nset[i]
x = x0[1:N]
t = seq(-1, 1.5, 2.5/1000)

p0 = dnorm(t, 0, 1)
theta = mu*(N*sigma0^2)/(N*sigma0^2+sigma^2) + mu0*(sigma^2)/(N*sigma0^2+sigma^2)
sigmaN = sqrt(1/(1/sigma0^2+N/sigma^2));
posterior[[i]] = dnorm(t, theta, sigmaN)
}

plot(t, posterior[[7]], type="n", xlab="", ylab="")
lines(t, posterior[[1]], lwd=3, col="red")
lines(t, posterior[[2]], lwd=3, col="orange")
lines(t, posterior[[3]], lwd=3, col="yellow")
lines(t, posterior[[4]], lwd=3, col="green")
lines(t, posterior[[5]], lwd=3, col="turquoise")
lines(t, posterior[[6]], lwd=3, col="blue")
lines(t, posterior[[7]], lwd=3, col="purple")

legend(-0.9, 7, legend=c("N = 0", "N = 1", "N = 2", "N = 5", "N = 8", "N = 12", "N = 20"), col=c("red", "orange", "yellow", "green", "turquoise", "blue", "purple"), lty=1:1, lwd=3)
grid()

#############

0 comments on commit 4db0e9c

Please sign in to comment.