我正在尝试使用R中的包nloptr来解决优化问题.我不确定以下代码有什么问题,因为我不断收到此错误:
错误:nlopt_add_equality_mconstraint返回NLOPT_INVALID_ARGS.
这是问题(注意(A)^ T是矩阵A的Moore-Penrose逆的转置)
和代码:
library( MASS ) ## for the Moore-Penrose inverse ginv()
library( zoo )
library( nloptr )
A = matrix(runif(27, -0.5, 0.5), nc = 3)
sigma = diag(runif(3,0.001,0.002))
M = ncol(A)
b = 1 / M
n = nrow(A)
init_y = rep(1/M, M)
c = -ncol(A)*log(ncol(A))
#### Objective function
eval_f <- function(y)
{
return( sqrt( as.numeric( t(y) %*% sigma %*% y ) ) )
}
#### Gradient of objective function
eval_grad_f <- function(y)
{
return( ( 2* sigma %*% y) / as.numeric(sqrt( t(y) %*% sigma %*% y )) )
}
#### Equality Constraint
eval_g_eq <- function(y)
{
return( ( t(ginv(A)) %*% y ) - 1 )## ginv(a) is the Moore-Penrose inverse of A
}
#### Inequality constraint
eval_g_ineq <- function(y)
{
return( c - sum( log(y) * b ) )
}
#### Jacobian of equality constraint
eval_jac_g_eq <- function(y)
{
return( ginv(A) )
}
#### Jacobian of inequality constraint
eval_jac_g_ineq <- function(y)
{
return( (-1/y) * b )
}
opts <- list( "algorithm" = "NLOPT_LD_SLSQP",
"xtol_rel" = 1.0e-14)
res0 <- nloptr( x0=init_y,
eval_f=eval_f,
eval_grad_f=eval_grad_f,
lb = rep(0,ncol(A)),
ub = rep(Inf,ncol(A)),
eval_g_eq = eval_g_eq,
eval_jac_g_eq = eval_jac_g_eq,
eval_g_ineq = eval_g_ineq,
eval_jac_g_ineq = eval_jac_g_ineq,
opts = opts
)
最佳答案
I’ve seen this happen当人们用一个参数而不是两个参数声明一个lambda值时.问题可能与您如何设置约束有关.你可以查看
this document on the topic.
在这种情况下,问题似乎与您用于eval_g_eq的函数有关.如果我将此参数设置为NULL或the documentation页面上给出的示例函数,则没有错误.