首页 > 解决方案 > R optim() 约束优化没有找到第一个最好的

问题描述

我的问题总结为找到一个具有最佳解决方案的向量 X:L 是利润,R 是限制,P 是约束参数矩阵,

或最大值(t(L)%*%X)

或 P%*%X <= R。

我找到了 X 的解决方案,但不是最好的,即 fb = c(.217,0,0,23,2865,0,13,427)。如何找到最佳解决方案?

代码:


X<-matrix(rep(1,6),6,1)
P<-matrix(c(
    1, 1, 1, 2, 0, 0,
    0, 1, 1, 2, 1, 1,
    99.4, 37.75, 19.75, 54.40, 74.75, 53,
    2.400, 1.540, 0, 0, 0, 0,
    2.400, 1.960, 0, 0, 0, 0,
    1.800, 3.300, 5.330, 0, 0, 0,
    0, 0, 2.070, 0, 8.700, 0,
    0, 0, .436, 0, 19.100, 12.363,
    0, 3.000, .364, 0, 9.100, 26.737  ), 
9,6,1)

L <- matrix(c(83.4, 72.35, 27.3, 72.05, 217.25, 455), 6,1)
R <- matrix(c(60,60,2000,351,448,479,338,424,359),9,1)

farm<- function(par, P,R,  L){
   trues<- P%*%par<=R
 if (min(trues)==1 && min(par)>=0) {
    return(-t(L)%*%par)
     }
 else{
     return(0)
 }
}

mtds = c("Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN","Brent")
out <- optim(par = X,  # initial guess
             fn  = farm,
             P   = P,
             R   = R ,
             L   = L,
             method  = mtds[5]) 


# my result
t(L)%*%out$par
#A matrix: 1 × 1 of type dbl
#7419.596

# the first best
fb<- matrix(c(.217,0,0,23.2865,0,13.427),6,1)
t(L)%*%fb
#A matrix: 1 × 1 of type dbl
#7805.175

标签: rmatrixoptimization

解决方案


我想你可以fmincon从包中尝试pracma

library(pracma)
objfun <- function(x) -t(L)%*%x
res <- fmincon(x0 = X,fn = objfun,A = P,b = R,lb = rep(0,length(X)))

你会看到

> res$par
[1]  4.201711e-16 -1.239088e-15  1.863081e-17  2.310286e+01
[5]  5.566620e-01  1.323762e+01

> -res$value
         [,1]
[1,] 7808.615

推荐阅读