r - R optim() 约束优化没有找到第一个最好的
问题描述
我的问题总结为找到一个具有最佳解决方案的向量 X:L 是利润,R 是限制,P 是约束参数矩阵,
- 最大 SUM_i (x_i * l_i)
或最大值(t(L)%*%X)
- 限制
- SUM_i(x_i*p_ij)<=r_j
或 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
解决方案
我想你可以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
推荐阅读
- vega-lite - 如何在 Vega Lite 中使用“乘法”或“自定义 fn”聚合?
- javascript - 为什么我的输入从这个 jQuery 语句中增加了不止一个?
- angular - Angular/RxJS 取消订阅先前的请求
- vb.net - VB.NET 中的 EF Core、LINQ 运算符“=”
- jenkins - 禁用 Jenkins 项目/作业有什么好处吗?
- javascript - How do i render a react component passed in as a props with additional props?
- php - 尝试正确调用 Alt 和标题标签
- python - 如何在 Django 项目中构建模板库?
- erlang - How to send body params in elixir using hackney
- c99 - why segmentation fault error in recursive function