【发布时间】:2016-10-30 12:47:18
【问题描述】:
我的 Metropolis-Hastings 问题有一个平稳的二项分布,并且所有提案分布 q(i,j) 都是 0.5。参考图和直方图,算法是否应该如此清晰地以二项分布的概率0.5为中心?
pi <- function(x, n, p){
# returning value from binomial distribution
result <- (factorial(n) / (factorial(x) * factorial(n - x))) *
p^x * (1 - p)^(n - x)
return(result)
}
metropolisAlgorithm <- function(n, p, T){
# implementation of the algorithm
# @n,p binomial parameters
# @T number of time steps
X <- rep(runif(1),T)
for (t in 2:T) {
Y <- runif(1)
alpha <- pi(X[t - 1], n, p) / pi(Y, n, p)
if (runif(1) < alpha) X[t] <- Y
else X[t] < X[t - 1]
}
return(X)
}
# calling M-H algorithm and plotting result
test <- metropolisAlgorithm(40,0.5,5000)
par(mfrow=c(2,1))
plot(test, type = "l")
hist(test, breaks = 40)
【问题讨论】:
-
这是一个很好的问题,我什至没有考虑寻找原生函数:/ 感谢您的提示!
-
当我反复运行您的代码时,我通常看不到您声称的内容。我看到一些东西似乎集中在生成的第一个随机数附近,通常离 0.5 很远。因此,您的实施存在问题。您的提案分布似乎很奇怪。
-
不应该
X采用整数值而不是[0,1]中的值吗? -
试试
X <- runif(T)而不是X <- rep(runif(1),T)?? -
X[t] < X[t - 1]应该是X[t] <- X[t - 1],尽管存在X似乎是成功次数的语义问题(在 1:40 中离散),但您正试图通过随机走进[0,1]
标签: r markov-chains