R中optim()函数的行为 [英] Behavior of optim() function in R

查看:487
本文介绍了R中optim()函数的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用R optim函数进行最大似然估计.

I'm doing maximum likelihood estimation using the R optim function.

我使用的命令是

optim(3, func, lower=1.0001, method="L-BFGS-B")$par

如果参数为1,则函数func具有无限值. 因此,我将较低的值设置为1.0001. 但是有时会发生错误.

The function func has infinite value if the parameter is 1. Thus I set the lower value to be 1.0001. But sometime an error occurs.

Error in optim(3, func, lower = 1.0001, method = "L-BFGS-B", sx = sx,  : 
  L-BFGS-B needs finite values of 'fn'

接下来发生的事情很难理解. 如果我再次运行相同的命令,则结果为1.0001,这是下限. 似乎optim函数了解" 1不是正确的答案. optim函数如何在我第一次运行时给出答案1.0001?

What happened next is hard to understand. If I run the same command again, then it gives the result 1.0001 which is lower limit. It seems that the optim function 'learns' that 1 is not the proper answer. How can the optim function can give the answer 1.0001 at my first run?

P.S. 我只是发现仅在独立的R-console中会出现此问题.如果我在R Studio中运行相同的代码,则不会发生.很奇怪.

P.S. I just found that this problem occurs only in stand-alone R-console. If I run the same code in R Studio, it does not occur. Very strange.

推荐答案

方法"L-BFGS-B"要求该函数的所有计算值都是有限的.
出于某种原因,似乎优化者正在将函数的值评估为1.0,给您一个inf值,然后抛出一个错误.

The method "L-BFGS-B" requires all computed values of the function to be finite.
It seems, for some reason, that optim is evaluating your function at the value of 1.0, giving you an inf, then throwing an error.

如果您想快速攻克,请尝试定义一个新函数,该函数对于输入1给出非常高的值(如果试图最大化,则给出低的值).

If you want a quick hack, try defining a new function that gives a very high value(or low if you're trying to maximize) for inputs of 1.

func2 <- function(x){
  if (x == 1){
    return -9999
  }
  else{
    return func(x)
  }
}

optim(3, func2, lower=1.0001, method="L-BFGS-B")$par

这篇关于R中optim()函数的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆