从R中的nloptr输出写入CSV文件

时间:2018-03-18 18:34:40

标签: r

我想从R中的nloptr输出中写出变量的最佳值。例如,我有这个程序,如何从res获取x向量的最佳值并将其打印在CSV文件中?

library('nloptr')
eval_f <- function( x ) {
  yx = x[1]*x[4]*(x[1] + x[2] + x[3]) + x[3];
  return( list( "objective" = yx,
                "gradient" = c( x[1] * x[4] + x[4] * (x[1] + x[2] + x[3]),
                                x[1] * x[4],
                                x[1] * x[4] + 1.0,
                                x[1] * (x[1] + x[2] + x[3]) ) ) );
}
local_opts <- list( "algorithm" = "NLOPT_LD_MMA",
                    "xtol_rel" = 1.0e-7 );

opts <- list( "algorithm" = "NLOPT_LD_AUGLAG",
              "xtol_rel" = 1.0e-7,
              "maxeval" = 1000,
              "local_opts" = local_opts );

x0 <- c( 1, 5, 5, 1 );
lb <- c( 1, 1, 1, 1 );
ub <- c( 5, 5, 5, 5 );
res <- nloptr( x0=x0, eval_f=eval_f,lb=lb,ub=ub,opts=opts);
print(res)

打印

## Call:
## nloptr(x0 = x0, eval_f = eval_f, lb = lb, ub = ub, opts = opts)
## 
## Minimization using NLopt version 2.4.2 
## 
## NLopt solver status: 3 ( NLOPT_FTOL_REACHED: Optimization stopped because
## ftol_rel or ftol_abs (above) was reached. )
## 
## Number of Iterations....: 6 
## Termination conditions:  xtol_rel: 1e-07 maxeval: 1000 
## Number of inequality constraints:  0 
## Number of equality constraints:    0 
## Optimal value of objective function:  4 
## Optimal value of controls: 1 1 1 1

我想将矢量[1,1,1,1]写入csv文件。这该怎么做? 感谢

1 个答案:

答案 0 :(得分:2)

nloptr::nloptr()函数返回一个列表,其中一个元素 ($solution)是您想要的值的向量。

如果res如上所述:

# ...
x0 <- c(1, 5, 5, 1)
lb <- c(1, 1, 1, 1)
ub <- c(5, 5, 5, 5)
res <- nloptr(x0=x0, eval_f=eval_f, lb=lb, ub=ub, opts=opts)

然后,您可以使用str(res)查看其中包含的内容:

str(res)
## ...
## $ iterations            : int 6
## $ objective             : num 4
## $ solution              : num [1:4] 1 1 1 1     <~~~ the thing we want
## $ version               : chr "2.4.2"
## - attr(*, "class")= chr "nloptr"

然后提取您想要的值并将它们写为csv(如果这是您想要的格式):

values <- res$solution
write.csv(values, "nloptr_soln.csv", row.names=FALSE)