15

Suppose I have 2 data.frame objects:

df1 <- data.frame(x = 1:100)
df1$y <- 20 + 0.3 * df1$x + rnorm(100)
df2 <- data.frame(x = 1:200000)
df2$y <- 20 + 0.3 * df2$x + rnorm(200000)

I want to do MLE. With df1 everything is ok:

LL1 <- function(a, b, mu, sigma) {
    R = dnorm(df1$y - a- b * df1$x, mu, sigma) 
    -sum(log(R))
}
library(stats4)
mle1 <- mle(LL1, start = list(a = 20, b = 0.3,  sigma=0.5),
        fixed = list(mu = 0))

> mle1
Call:
mle(minuslogl = LL1, start = list(a = 20, b = 0.3, sigma = 0.5), 
fixed = list(mu = 0))

Coefficients:
      a           b          mu       sigma 
23.89704180  0.07408898  0.00000000  3.91681382 

But if I would do the same task with df2 I would receive an error:

LL2 <- function(a, b, mu, sigma) {
    R = dnorm(df2$y - a- b * df2$x, mu, sigma) 
    -sum(log(R))
}
mle2 <- mle(LL2, start = list(a = 20, b = 0.3,  sigma=0.5),
              fixed = list(mu = 0))
Error in optim(start, f, method = method, hessian = TRUE, ...) : 
  initial value in 'vmmin' is not finite

How can I overcome it?

4

3 回答 3

8

当最小化对数似然函数时,我遇到了同样的问题。经过一些调试,我发现问题出在我的起始值上。它们导致一个特定矩阵的行列式 = 0,这在对其进行日志记录时会导致错误。因此,它找不到任何“有限”值,但那是因为该函数向 optim 返回了一个错误。

底线:考虑您的函数在使用起始值运行时是否没有返回错误。

PS.:Marius Hofert 是完全正确的。永远不要压制警告。

于 2015-09-07T20:12:36.563 回答
7

的值R在某个点变为零;它导致函数的非有限值被最小化并返回错误。

使用参数log=TRUE可以更好地处理这个问题,请参见LL3下面的函数。以下给出了一些警告,但返回了一个结果,参数估计值接近真实参数。

require(stats4)
set.seed(123)
e <- rnorm(200000)
x <- 1:200000
df3 <- data.frame(x)
df3$y <- 20 + 0.3 * df3$x + e
LL3 <- function(a, b, mu, sigma) {
  -sum(dnorm(df3$y - a- b * df3$x, mu, sigma, log=TRUE))
}
mle3 <- mle(LL3, start = list(a = 20, b = 0.3,  sigma=0.5),
  fixed = list(mu = 0))
Warning messages:
1: In dnorm(df3$y - a - b * df3$x, mu, sigma, log = TRUE) : NaNs produced
2: In dnorm(df3$y - a - b * df3$x, mu, sigma, log = TRUE) : NaNs produced
3: In dnorm(df3$y - a - b * df3$x, mu, sigma, log = TRUE) : NaNs produced
4: In dnorm(df3$y - a - b * df3$x, mu, sigma, log = TRUE) : NaNs produced
5: In dnorm(df3$y - a - b * df3$x, mu, sigma, log = TRUE) : NaNs produced
6: In dnorm(df3$y - a - b * df3$x, mu, sigma, log = TRUE) : NaNs produced
7: In dnorm(df3$y - a - b * df3$x, mu, sigma, log = TRUE) : NaNs produced
8: In dnorm(df3$y - a - b * df3$x, mu, sigma, log = TRUE) : NaNs produced

> mle3
Call:
mle(minuslogl = LL3, start = list(a = 20, b = 0.3, sigma = 0.5), 
    fixed = list(mu = 0))

Coefficients:
        a         b        mu     sigma 
19.999166  0.300000  0.000000  1.001803 
于 2014-06-24T10:32:43.707 回答
1

R 中的已知错误,bugzilla ID 17703。众所周知,难以重现。

于 2020-05-18T05:15:09.623 回答