Toy R code on Bayesian pin for mean normal distribution [snowfall data]

I have a number of snowfall observations:

x <- c(98.044, 107.696, 146.050, 102.870, 131.318, 170.434, 84.836, 154.686,
       162.814, 101.854, 103.378, 16.256)

and I was told that it follows a normal distribution with a known standard deviation at 25.4, but an unknown mean mu. I have to conclude on muusing a Bayesian formula.

This is information about the previous mu

mean of snow |  50.8  | 76.2  | 101.6 | 127.0 |  152.4 | 177.8  
---------------------------------------------------------------
probability  |   0.1  | 0.15  | 0.25  |0.25   |  0.15  |  0.1 
---------------------------------------------------------------

Below I tried to do so, but the last line about postdoes not work correctly. The resulting storylines give a horizontal line.

library(LearnBayes)
midpts <- c(seq(50.8, 177.8, 30))
prob <- c(0.1, 0.15, 0.25, 0.25, 0.15, 0.1)
p <- seq(50, 180, length = 40000)
histp <- histprior(p, midpts, prob)
plot(p, histp, type = "l")

# posterior density
post <- round(histp * dnorm(x, 115, 42) / sum(histp * dnorm(x, 115, 42)), 3)
plot(p, post, type = "l")
+4
source share
1 answer

: , , .

post <- round(histp * dnorm(x, 115, 42) / sum(histp * dnorm(x, 115, 42)), 3)

, . , -, , .

## likelihood function: `L(obs | mu)`
## standard error is known (to make problem easy) at 25.4
Lik <- function (obs, mu) prod(dnorm(obs, mu, 25.4))

, mu , ; , . , , mu = 100

Lik(x, 100)
# [1] 6.884842e-30

R Lik. , mu, . sapply :

vecLik <- function (obs, mu) sapply(mu, Lik, obs = obs)

vecLik(x, c(80, 90, 100))
# [1] 6.248416e-34 1.662366e-31 6.884842e-30

mu. , , , histprior R LearnBayes.

## prior distribution for `mu`: `prior(mu)`
midpts <- c(seq(50.8, 177.8, 30))
prob <- c(0.1, 0.15, 0.25, 0.25, 0.15, 0.1)
mu_grid <- seq(50, 180, length = 40000)  ## a grid of `mu` for discretization
library(LearnBayes)
prior_mu_grid <- histprior(mu_grid, midpts, prob)  ## discrete prior density
plot(mu_grid, prior_mu_grid, type = "l")

previous distribution

, NC . Lik(obs | mu) * prior(mu). prior(mu), .

delta <- mu_grid[2] - mu_grid[1]    ## division size
NC <- sum(vecLik(x, mu_grid) * prior_mu_grid * delta)    ## Riemann sum
# [1] 2.573673e-28

, , :

posterior(mu | obs) = Lik(obs | mu) * prior(mu) / NC

, prior(mu) , posterior(mu) .

post_mu <- vecLik(x, mu_grid) * prior_mu_grid / NC

-, mu, :

plot(mu_grid, post_mu, type = "l")

back density

, !!

+15

Source: https://habr.com/ru/post/1658523/


All Articles