如何在 cplex-python 中设置间隙公差?
How to set gap tolerance in cplex-python?
我想设置一个间隙值 (GAP),以便在当前间隙低于 GAP 时优化过程停止。我已阅读 cplex-python
文档并发现:
Model.parameters.mip.tolerances.absmipgap(GAP)
但我收到下一个警告:
Model.parameters.mip.tolerances.mipgap(float(0.1))
TypeError: 'NumParameter' object is not callable
有什么想法吗?请帮我。提前致谢。
让我根据您的问题调整我的巴士示例:
from docplex.mp.model import Model
mdl = Model(name='buses')
# gap tolerance
mdl.parameters.mip.tolerances.mipgap=0.001;
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40*500 + nbbus30*400)
mdl.solve()
for v in mdl.iter_integer_vars():
print(v," = ",v.solution_value)
print("gap tolerance = ",mdl.parameters.mip.tolerances.mipgap.get())
给出:
nbBus40 = 6.0
nbBus30 = 2.0
gap tolerance = 0.001
你的错误是把参数当作函数来调用。更改参数的正确方法是分配给它:
Model.parameters.mip.tolerances.absmipgap = GAP
还要确保您不使用 Model
class 而是 class:
的一个实例
mdl = Model()
mdl.parameters.mip.tolerances.absmipgap = GAP
另请注意,有两个间隙参数:绝对和相对。相对间隙是最常用的。您可以找到 here 和
here(相对公差的参数称为mipgap
)。
根据您遇到的错误,我认为您可能正在使用 CPLEX Python API 而不是 docplex(如其他答案)。要解决您的问题,请考虑以下示例:
import cplex
Model = cplex.Cplex()
# This will raise a TypeError
#Model.parameters.mip.tolerances.mipgap(float(0.1))
# This is the correct way to set the parameter
Model.parameters.mip.tolerances.mipgap.set(float(0.1))
# Write the parameter file to check that it looks as you expect
Model.parameters.write_file("test.prm")
您需要使用set()
方法。您可以通过使用 write_file 方法将参数文件写入磁盘并查看它来确保参数已按预期更改。
我想设置一个间隙值 (GAP),以便在当前间隙低于 GAP 时优化过程停止。我已阅读 cplex-python
文档并发现:
Model.parameters.mip.tolerances.absmipgap(GAP)
但我收到下一个警告:
Model.parameters.mip.tolerances.mipgap(float(0.1))
TypeError: 'NumParameter' object is not callable
有什么想法吗?请帮我。提前致谢。
让我根据您的问题调整我的巴士示例:
from docplex.mp.model import Model
mdl = Model(name='buses')
# gap tolerance
mdl.parameters.mip.tolerances.mipgap=0.001;
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40*500 + nbbus30*400)
mdl.solve()
for v in mdl.iter_integer_vars():
print(v," = ",v.solution_value)
print("gap tolerance = ",mdl.parameters.mip.tolerances.mipgap.get())
给出:
nbBus40 = 6.0
nbBus30 = 2.0
gap tolerance = 0.001
你的错误是把参数当作函数来调用。更改参数的正确方法是分配给它:
Model.parameters.mip.tolerances.absmipgap = GAP
还要确保您不使用 Model
class 而是 class:
mdl = Model()
mdl.parameters.mip.tolerances.absmipgap = GAP
另请注意,有两个间隙参数:绝对和相对。相对间隙是最常用的。您可以找到 here 和
here(相对公差的参数称为mipgap
)。
根据您遇到的错误,我认为您可能正在使用 CPLEX Python API 而不是 docplex(如其他答案)。要解决您的问题,请考虑以下示例:
import cplex
Model = cplex.Cplex()
# This will raise a TypeError
#Model.parameters.mip.tolerances.mipgap(float(0.1))
# This is the correct way to set the parameter
Model.parameters.mip.tolerances.mipgap.set(float(0.1))
# Write the parameter file to check that it looks as you expect
Model.parameters.write_file("test.prm")
您需要使用set()
方法。您可以通过使用 write_file 方法将参数文件写入磁盘并查看它来确保参数已按预期更改。