MASS 包的 "fitdistr":处理被操纵的随机数据时出错

MASS packages' "fitdistr": Error when dealing with manipulated random data

背景:

下面我使用 R 生成了一些随机的 beta 数据并稍微操纵数据的形状以达到我所说的"Final" 在我的代码中。我在我的代码中直方图 "Final"

问题:

我想知道为什么在尝试使用 MASS 包“ 将 "beta" 分布拟合到 Final 数据时fitdistr" 函数,我收到以下错误(关于如何避免此错误的任何建议)?

Error in stats::optim(x = c(0.461379379270288, 0.0694261016478062, 0.76934266883081, : initial value in 'vmmin' is not finite

这是我的 R 代码:

 require(MASS)

## Generate some data and manipulate it
set.seed(47)

Initial = rbeta(1e5, 2, 3)
d <- density(Initial)

b.5 <- dbeta(seq(0, 1, length.out = length(d$y)), 50, 50)
b.5 <- b.5 / (max(b.5) / max(d$y))    # Scale down to max of original density

 b.6 <- dbeta(seq(0, 1, length.out = length(d$y)), 60, 40)
 b.6 <- b.6 / (max(b.6) / max(d$y))

 # Collect maximum densities at each x to use as sample probability weights
 p <- pmax(d$y, b.5, b.6)


Final <- sample(d$x, 1e4, replace = TRUE, prob = p) ## THIS IS MY FINAL DATA

hist(Final, freq = F, ylim = c(0, 2))               ## HERE IS A HISTOGRAM

 m <- MASS::fitdistr(Final, "beta",          ## RUN THIS TO SEE HOW THE ERROR COMES UP
                start = list(shape1 = 1, shape2 = 1))

这是代码。

和你的代码一样,我只是去掉了负的 beta 值。

library(MASS)

set.seed(47)

Initial = rbeta(1e5, 2, 3)
d <- density(Initial)

b.5 <- dbeta(seq(0, 1, length.out = length(d$y)), 50, 50)


b.5 <- b.5 / (max(b.5) / max(d$y))    # Scale down to max of original 
density

b.6 <- dbeta(seq(0, 1, length.out = length(d$y)), 60, 40)
b.6 <- b.6 / (max(b.6) / max(d$y))

# Collect maximum densities at each x to use as sample probability weights
p <- pmax(d$y, b.5, b.6)


Final <- sample(d$x, 1e4, replace = TRUE, prob = p) ## THIS IS MY FINAL DATA

hist(Final, freq = F, ylim = c(0, 2))               ## HERE IS A HISTOGRAM

# replace negative beta values with smallest value > 0
Final[Final<= 0] <- min(Final[Final>0])

hist(Final, freq = F, ylim = c(0, 2))

m <- MASS::fitdistr(x = Final, densfun = "beta",          
                start = list(shape1 = 1, shape2 = 1))

形状参数如下:

> m
     shape1       shape2  
  1.99240852   2.90219720 
 (0.02649853) (0.04010168)

注意它给出了一些警告。