如何从R中的分位数经验CDF估计密度经验pdf 问题这是我到目前为止所拥有的原始密度逆变换样本摘要统计

问题描述

问题

说我的密度为a

我所知道的只是分位数(probs)的概率网格(quants)。

如何从未知密度生成随机样本?

这是我到目前为止所拥有的。

我正在尝试剔除采样,但是我并不局限于这种方法在这里,我对分位数拟合了多项式(6递减)。目的是将离散的分位数转换为平滑的连续函数。这给了我一个经验CDF。然后,我使用剔除采样从CDF获取实际样本。 R中是否有一种方便的方法可以将样本从CDF转换为密度样本,还是在有更好的选择时以复杂的方式进行处理?

# unkNown and probably not normal,but I use rnorm here because it is easy
a <- c(exp(rnorm(200,5,.8)))
probs <- seq(0.05,0.95,0.05)
quants <- quantile(a,probs)
df_quants <- tibble::tibble(cum_probs,quants)
df_quants <- df_quants
fit <- lm(quants ~ poly(cum_probs,6),df_quants)
df_quants$fit <- predict(fit,df_quants)

p <- df_quants %>%
  ggplot(aes(x = cum_probs,y = quants))+
  geom_line(aes(y = quants),color = "black",size = 1) +
  geom_line(aes(y = fit),color = "red",size = 1)

CDF

cdf

count = 1
accept = c()
X <- runif(50000,1)
U <- runif(50000,1)
estimate <- function(x){
  new_x <- predict(fit,data.frame(cum_probs = c(x)))
  return(new_x)
while(count <= 50000 & length(accept) < 40000){
  test_u = U[count]
  test_x = estimate(X[count])/(1000*dunif(X[count],1))
  if(test_u <= test_x){
    accept = rbind(accept,X[count])
    count = count + 1
  }
    count = count + 1
}
p2 <- as_tibble(accept,name = V1) %>%
  ggplot(aes(x = V1)) +
  geom_histogram(bins = 45)
}

CDF样本

enter image description here

解决方法

我认为不需要拒绝采样,通过Bsp​​line拟合,我可以通过逆变换生成明智的采样,但是我还需要一个更高分辨率的网格。尾巴有点脱落。

我在这里所做的假设是,适合于紧密网格的Bspline近似于CDF逆函数。一旦这条曲线成立,我就可以使用随机制服U[0,1]

library(splines2)

a <- c(exp(rnorm(200,5,.8)))
cum_probs <- seq(0.01,0.99,0.01)
quants <- quantile(a,cum_probs)
df_quants <- tibble::tibble(cum_probs,quants)
fit_spline <- lm(quants ~ bSpline(cum_probs,df = 9),df_quants)
df_quants$fit_spline <- predict(fit_spline,df_quants)
estimate <- function(x){
  new_x <- predict(fit_spline,data.frame(cum_probs = c(x)))
  return(new_x)
}
e <- runif(10000,1)
y <-(estimate(e))
df_density <- tibble(y)
df_densitya <- tibble(a)
py <- df_density %>%
  ggplot(aes(x = y)) +
  geom_histogram()
pa <- df_densitya %>%
  ggplot(aes(x = a)) +
  geom_histogram(bins = 45)

原始密度

enter image description here

逆变换样本

enter image description here

摘要统计

原始dist a
Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
20.36   80.84  145.25  195.72  241.22 1285.24
从分位数y生成
Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
28.09   81.78  149.53  189.07  239.62  667.27