gpt4 book ai didi

r - 在 R 中使用线性(或非线性?)约束优化值

转载 作者:行者123 更新时间:2023-12-03 16:24:14 27 4
gpt4 key购买 nike

考虑到不同的限制条件,我正在努力挑选最好的梦幻足球队。我的目标是挑选能够最大化他们的投影总和的玩家

约束是:

1) 团队必须包括:

-1 四分卫

-2 RB

-2 WR

-1 TE

2) 玩家的风险不得超过 6

3) 玩家的费用总和不得超过300。

我该怎么做? R 中优化这些约束的最佳包/功能是什么?给定这些约束,最大化投影点的函数调用会是什么样子?仅供引用,我将搜索 100-300 名玩家。

提前致谢!这是一个小的示例数据集:

name <- c("Aaron Rodgers","Tom Brady","Arian Foster","Ray Rice","LeSean McCoy","Calvin Johnson","Larry Fitzgerald","Wes Welker","Rob Gronkowski","Jimmy Graham")

pos <- c("QB","QB","RB","RB","RB","WR","WR","WR","TE","TE")

pts <- c(167, 136, 195, 174, 144, 135, 89, 81, 114, 111)

risk <- c(2.9, 3.4, 0.7, 1.1, 3.5, 5.0, 6.7, 4.7, 3.7, 8.8)

cost <- c(60, 47, 63, 62, 40, 60, 50, 35, 40, 40)

mydata <- data.frame(name, pos, pts, risk, cost)

最佳答案

你的约束和目标是线性的,但你的变量是二元的:每个球员是否应该被选中。所以你的问题比线性规划(LP)更普遍,它是混合整数规划(MIP)。在 CRAN 的 Optimization Task View ,查找他们的 MIP 部分。

CPLEX 是您可能无法访问的商业求解器,但 GLPK 是免费的。如果我是你,我可能会使用高级接口(interface) Rglpk .

这需要你把你的问题用矩阵的形式表达出来,我建议你看看文档和例子。


编辑:这是一个实现:

# We are going to solve:
# maximize f'x subject to A*x <dir> b
# where:
# x is the variable to solve for: a vector of 0 or 1:
# 1 when the player is selected, 0 otherwise,
# f is your objective vector,
# A is a matrix, b a vector, and <dir> a vector of "<=", "==", or ">=",
# defining your linear constraints.

# number of variables
num.players <- length(name)
# objective:
f <- pts
# the variable are booleans
var.types <- rep("B", num.players)
# the constraints
A <- rbind(as.numeric(pos == "QB"), # num QB
as.numeric(pos == "RB"), # num RB
as.numeric(pos == "WR"), # num WR
as.numeric(pos == "TE"), # num TE
diag(risk), # player's risk
cost) # total cost

dir <- c("==",
"==",
"==",
"==",
rep("<=", num.players),
"<=")

b <- c(1,
2,
2,
1,
rep(6, num.players),
300)

library(Rglpk)
sol <- Rglpk_solve_LP(obj = f, mat = A, dir = dir, rhs = b,
types = var.types, max = TRUE)
sol
# $optimum
# [1] 836 ### <- the optimal total points

# $solution
# [1] 1 0 1 0 1 1 0 1 1 0 ### <- a `1` for the selected players

# $status
# [1] 0 ### <- an optimal solution has been found

# your dream team
name[sol$solution == 1]
# [1] "Aaron Rodgers" "Arian Foster" "LeSean McCoy"
# [4] "Calvin Johnson" "Wes Welker" "Rob Gronkowski

关于r - 在 R 中使用线性(或非线性?)约束优化值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15147398/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com