-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathBayesian_Notes_520.R
More file actions
61 lines (48 loc) · 1.47 KB
/
Copy pathBayesian_Notes_520.R
File metadata and controls
61 lines (48 loc) · 1.47 KB
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
#Inference for Binomial with Beta Prior
BBB<-function(n,p,alpha,beta)
{
require(ggplot2)
require(reshape2)
xx<-rbinom(1,n,p)
p_hat<-xx/n
print("Observed Proportion, Posterior Mean")
p_hat_Post<-(alpha+xx)/(n+alpha+beta)
print(c(p_hat,p_hat_Post))
x <- seq(0, 1, 0.01)
Prior <- dbeta(x,alpha,beta)
Posterior <- dbeta(x,alpha+xx,n+beta-xx)
df <- data.frame(x, Prior, Posterior)
# melt the data to a long format
df2 <- reshape2::melt(data = df, id.vars = "x")
# plot, using the aesthetics argument 'colour'
ggplot(data = df2, aes(x = x, y = value, colour = variable)) + geom_line() + geom_vline(xintercept=p_hat)
}
n<-1
p<-0.3
alpha<-1
beta<-1
BBB(n,p,alpha,beta)
#Inference for Normal with Normal Prior
BNN<-function(n,mu,sigma,theta,tau)
{
require(ggplot2)
require(reshape2)
xx<-rnorm(n,mu,sigma)
xbar<-mean(xx)
theta_post<-(theta*sigma^2+n*xbar*tau^2)/(sigma^2+n*tau^2)
tau_post<-(sigma^2*tau^2)/(sigma^2+n*tau^2)
print("Observed Mean, Posterior Mean")
xbar_Post<-theta_post
print(c(xbar,xbar_Post))
a<-min(xx)-1
b<-max(xx)+1
x <- seq(a, b, 0.01)
Prior <- dnorm(x,theta,tau)
Posterior <- dnorm(x,theta_post,tau_post)
df <- data.frame(x, Prior, Posterior)
# melt the data to a long format
df2 <- reshape2::melt(data = df, id.vars = "x")
# plot, using the aesthetics argument 'colour'
ggplot(data = df2, aes(x = x, y = value, colour = variable)) + geom_line() + geom_vline(xintercept=xbar)
}
BNN(10,20,5,12,4)