首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在约束和二元变量中使用函数的约束优化

在约束和二元变量中使用函数的约束优化
EN

Stack Overflow用户
提问于 2019-09-09 16:15:23
回答 1查看 223关注 0票数 0

我正在寻找一种方法来解决-在R中-形式的约束优化问题

代码语言:javascript
复制
min sum(x)

s.t. f(x) < k

其中x是长度为n的二元变量(0或1),f(x)是依赖于整个x变量的函数,k是整数常量。因此,f( x )不是对x的每个值(例如sqrt(x))的n个约束的集合,而是基于二元变量x的整个值集所满足的约束。

我尝试使用具有以下语法的ompr R包

代码语言:javascript
复制
v < 1:10
result <- MILPModel() %>%
add_variable(x[i], i = 1:v, type = "binary") %>%
set_objective(sum_expr(x[i], i = 1:v), sense = "min") %>%
add_constraint(f(x) <= 60) %>%
solve_model(with_ROI(solver = "glpk"))

但是它不起作用,因为我相信这个包不接受全局f(x)约束。

EN

回答 1

Stack Overflow用户

发布于 2019-09-09 19:16:07

这是一个使用rgenoud包的解决方案。

代码语言:javascript
复制
library(rgenoud)

g <- function(x){
  c(
    ifelse(sd(x) > 0.2, 0, 1), # set the constraint (here sd(x)>0.2) in this way
    sum(x) # the objective function (to minimize/maximize)
  )
}

solution <- genoud(
  g, lexical = 2,
  nvars = 30, 
  starting.values = rep(0, 30), 
  Domains = cbind(rep(0,30), rep(1,30)),
  data.type.int = TRUE)

solution$par # the values of x
## [1] 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
sd(solution$par) # is the constraint satisfied ?
## [1] 0.2537081
solution$value
## [1] 0 2 ; 0 is the value of ifelse(sd(x)>0.2,0,1) and 2 is the value of sum(x)

要理解lexical参数,请参阅?genoud中的Notes部分。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57850149

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档