gpt4 book ai didi

python - 使用 PuLP 代码时出现 "int object is not callable"错误

转载 作者:行者123 更新时间:2023-12-01 13:52:26 25 4
gpt4 key购买 nike

我正在学习 PuLP 库的工作原理,它是一个线性规划求解器。我正在使用的代码是在这里找到的:LINK .它解决了以下优化问题(在本例中,使用二进制变量 x_{ij}):

enter image description here

这是教程中的代码:

import random
import pulp as plp

#Creating random constants for the model's input
n = 10
m = 5
set_I = range(1, n+1)
set_J = range(1, m+1)
c = {(i,j): random.normalvariate(0,1) for i in set_I for j in set_J}
a = {(i,j): random.normalvariate(0,5) for i in set_I for j in set_J}
l = {(i,j): random.randint(0,10) for i in set_I for j in set_J}
u = {(i,j): random.randint(10,20) for i in set_I for j in set_J}
b = {j: random.randint(0,30) for j in set_J}

opt_model = plp.LpProblem(name="Binary Model")


# if x is Binary
x_vars = {(i,j):
plp.LpVariable(cat=plp.LpBinary, name="x_{0}_{1}".format(i,j))
for i in set_I for j in set_J}


# Less than equal constraints
constraints = {j : opt_model.addConstraint(
plp.LpConstraint(
e=m(a[i,j] * x_vars[i,j] for i in set_I),
sense=plp.plp.LpConstraintLE,
rhs=b[j],
name="constraint_{0}".format(j)))
for j in set_J}

objective = plp.lpSum(x_vars[i,j] * c[i,j]
for i in set_I
for j in set_J)

# for minimization
opt_model.sense = plp.LpMinimize
opt_model.setObjective(objective)

我收到以下我不理解的错误:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-08e33a7305cc> in <module>
28 rhs=b[j],
29 name="constraint_{0}"))
---> 30 for j in set_J}
31
32 objective = plp.lpSum(x_vars[i,j] * c[i,j]

<ipython-input-20-08e33a7305cc> in <dictcomp>(.0)
28 rhs=b[j],
29 name="constraint_{0}"))
---> 30 for j in set_J}
31
32 objective = plp.lpSum(x_vars[i,j] * c[i,j]

TypeError: 'int' object is not callable

最佳答案

您的代码包含以下作为 plp.LpConstraint 的参数:

e=m(a[i,j] * x_vars[i,j] for i in set_I)

m 被定义为一个 int,但作为一个函数被调用。它应该是:

e=plp.lpSum(a[i,j] * x_vars[i,j] for i in set_I)

这是错误的原因,似乎只是您指南中的错字。同一表达式中的另一个拼写错误是 plp.plp.LpConstraintLE 应该只是 plp.LpConstraintLE

一旦你清除了这两个错误,你就应该解除阻塞,继续 opt_model.solve() 将解决模型。


您可能会发现以下代码更具可读性,可以用来解决 pulp 中的这个问题,例如使用像 LpVariable.dicts 这样的 pulp 特性。我一直喜欢 pulp 的一点是模型创建代码实际上非常可读。

import pulp

### Create n, m, set_I, set_J, c, a, l, u, and b as before

# Model
opt_mod = pulp.LpProblem(name="Binary_model", sense=pulp.LpMinimize)

# Variables from a dictionary
x_vars = pulp.LpVariable.dicts("x", c.keys(), cat=pulp.LpBinary)

# Constraints
for j in set_J:
opt_mod += pulp.lpSum(a[i,j] * x_vars[i,j] for i in set_I) <= b[j]

# Objective
opt_mod += pulp.lpSum(c[i,j] * x_vars[i,j] for i,j in c)

# Solve
opt_mod.solve()

# Which variables are set?
print([x for x in x_vars if x_vars[x].varValue > 0.999])

关于python - 使用 PuLP 代码时出现 "int object is not callable"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59674360/

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