我试图回答Evaluate integral with Importance sampling method in R的问题。基本上,用户需要计算
使用指数分布作为重要性分布
并找到这可以更好地近似积分(它是self-study)。我将问题改写为对平均值的评估的超过: 积分就是.
因此,让成为的pdf, 然后让: 现在的目标是估计
使用重要性抽样。我在 R 中进行了模拟:
# clear the environment and set the seed for reproducibility
rm(list=ls())
gc()
graphics.off()
set.seed(1)
# function to be integrated
f <- function(x){
1 / (cos(x)^2+x^2)
}
# importance sampling
importance.sampling <- function(lambda, f, B){
x <- rexp(B, lambda)
f(x) / dexp(x, lambda)*dunif(x, 0, pi)
}
# mean value of f
mu.num <- integrate(f,0,pi)$value/pi
# initialize code
means <- 0
sigmas <- 0
error <- 0
CI.min <- 0
CI.max <- 0
CI.covers.parameter <- FALSE
# set a value for lambda: we will repeat importance sampling N times to verify
# coverage
N <- 100
lambda <- rep(20,N)
# set the sample size for importance sampling
B <- 10^4
# - estimate the mean value of f using importance sampling, N times
# - compute a confidence interval for the mean each time
# - CI.covers.parameter is set to TRUE if the estimated confidence
# interval contains the mean value computed by integrate, otherwise
# is set to FALSE
j <- 0
for(i in lambda){
I <- importance.sampling(i, f, B)
j <- j + 1
mu <- mean(I)
std <- sd(I)
lower.CB <- mu - 1.96*std/sqrt(B)
upper.CB <- mu + 1.96*std/sqrt(B)
means[j] <- mu
sigmas[j] <- std
error[j] <- abs(mu-mu.num)
CI.min[j] <- lower.CB
CI.max[j] <- upper.CB
CI.covers.parameter[j] <- lower.CB < mu.num & mu.num < upper.CB
}
# build a dataframe in case you want to have a look at the results for each run
df <- data.frame(lambda, means, sigmas, error, CI.min, CI.max, CI.covers.parameter)
# so, what's the coverage?
mean(CI.covers.parameter)
# [1] 0.19
该代码基本上是重要性采样的简单实现,遵循此处使用的符号。然后重复重要性采样多次估计,并且每次检查 95% 区间是否覆盖实际平均值。
如您所见,对于实际覆盖率仅为 0.19。并且越来越到值,例如没有帮助(覆盖范围更小,0.15)。为什么会这样?

