![](/img/trans.png)
[英]R: Error in is.nloptr(ret) : inequality constraints in x0 returns NA
[英]R: Error in is.nloptr(ret) : objective in x0 returns NA
我正在尝试使用nloptr包来找到使非线性函数F = b0 + b1 * x + b2 * x ^ 2 + b3 * x ^ 3最大化的最佳x值。
我将以下代码与apply()函数一起使用,以使其在回归数据帧的每一行中循环,并为每一行获取函数的最佳值:
F <- function(x,b0,b1,b2,b3){return(b0+b1*x+b2*x^2+b3*x^3)}
Optimal <- apply(Regression,1,function(i){
nloptr( x0 <- c(0)
,eval_f <- F
,eval_g_ineq = NULL
,eval_g_eq = NULL
,eval_grad_f = NULL
,eval_jac_g_ineq = NULL
,eval_jac_g_eq = NULL
,lb <- c(-Inf)
,ub <- c(Inf)
,opts <- list( "algorithm" = "NLOPT_LD_AUGLAG",
"xtol_rel" = 1.0e-7,
"maxeval" = 1000)
,b0=Regression$b0[i]
,b1=Regression$b1[i]
,b2=Regression$b2[i]
,b3=Regression$b3[i])})
代码调用b0,b1,b2,b3值的回归数据帧具有以下格式:
Tag bo b1 b2 b3
A 5 6 1 3
B 8 8 7 3
C 9 2 7 5
D 1 6 1 3
E 3 6 2 1
.. .. .. .. ..
运行脚本时出现以下错误:
Error in is.nloptr(ret) : objective in x0 returns NA
In addition: Warning message:
In if (is.na(f0)) { :
如果您还打算访问该函数中的项目,则不应使用apply
传递“ Regression”行。 apply
强制Regression
应用于单个类型时,也会出现问题。 这将是字符而不是数字。 相反,它应该是:
library(nloptr)
F <- function(x,b0,b1,b2,b3){return(b0+b1*x+b2*x^2+b3*x^3)}
Optimal <- apply(Regression[-1], #removes first column
1, function(i){ # i-variable gets values
nloptr( x0 <- c(0)
,eval_f <- F
,eval_g_ineq = NULL
,eval_g_eq = NULL
,eval_grad_f = NULL
,eval_jac_g_ineq = NULL
,eval_jac_g_eq = NULL
,lb <- c(-Inf)
,ub <- c(Inf)
,opts <- list( "algorithm" = "NLOPT_LD_AUGLAG",
"xtol_rel" = 1.0e-7,
"maxeval" = 1000)
,b0=i[1]
,b1=i[2]
,b2=i[3]
,b3=i[4])})
用您的“回归”对象进行了测试。 (我担心尝试三次多项式时会出现最小值还是最大值。)不幸的是,您选择的参数不一致:
Error in is.nloptr(ret) :
A gradient for the objective function is needed by algorithm NLOPT_LD_AUGLAG
but was not supplied.
不过,应该可以很容易地计算出多项式的梯度。
构建梯度函数后,我得到:
grad_fun <- function(x,b0,b1,b2,b3) { b1 + x*b2/3 +x^2*b3/3 }
> F <- function(x, b0,b1,b2,b3){return(b0+b1*x+b2*x^2+b3*x^3)}
> Optimal <- apply(Regression[-1],
+ 1, function(i){
+ nloptr( x0 <- c(0)
+ ,eval_f <- F
+ ,eval_g_ineq = NULL
+ ,eval_g_eq = NULL
+ ,eval_grad_f = grad_fun
+ ,eval_jac_g_ineq = NULL
+ ,eval_jac_g_eq = NULL
+ ,lb <- c(-Inf)
+ ,ub <- c(Inf)
+ ,opts <- list( "algorithm" = "NLOPT_LD_AUGLAG",
+ "xtol_rel" = 1.0e-7,
+ "maxeval" = 1000)
+ ,b0=i[1]
+ ,b1=i[2]
+ ,b2=i[3]
+ ,b3=i[4])})
Error in is.nloptr(ret) :
The algorithm NLOPT_LD_AUGLAG needs a local optimizer; specify an algorithm and termination condition in local_opts
在我看来,我已经使您克服了几个障碍,因此,这还不是真正的答案,但它似乎很有用,并且发表评论的时间太长了。
编辑; 将算法更改为"algorithm" = "NLOPT_LD_LBFGS"
进一步实验使代码运行无误,但据我所知,这4条运行了所有带有$ message : chr "NLOPT_FAILURE: Generic failure code."
返回列表$ message : chr "NLOPT_FAILURE: Generic failure code."
。 我的猜测是,优化三次多项式通常会在没有约束的情况下失败,而我在您的问题说明中没有发现任何约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.