[英]write CSV file from output of nloptr in 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文件。 這個怎么做? 謝謝
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.