python – pickle与PuLP玩得不好
作者:互联网
我正在使用Python 2.7并使用PuLP库来设置问题.一旦定义了变量,目标和约束,我就会挑选我的LpProblem对象以发送给其他地方的Solver.在解开我的问题时,我注意到所有变量都是重复的:
import pulp
import pickle
prob = pulp.LpProblem('test problem', pulp.LpMaximize)
x = pulp.LpVariable('x', 0, 10)
y = pulp.LpVariable('y', 3, 6)
prob += x + y
prob += x <= 5
print prob
print pickle.loads(pickle.dumps(prob))
第一个打印声明输出:
>>> print prob
test problem:
MAXIMIZE
1*x + 1*y + 0
SUBJECT TO
_C1: x <= 5
VARIABLES
x <= 10 Continuous
3 <= y <= 6 Continuous
而第二次打印:
>>> print pickle.loads(pickle.dumps(prob))
test problem:
MAXIMIZE
1*x + 1*y + 0
SUBJECT TO
_C1: x <= 5
VARIABLES
x <= 10 Continuous
x <= 10 Continuous
3 <= y <= 6 Continuous
3 <= y <= 6 Continuous
如您所见,目标和约束都很好,但所有变量都是重复的.导致此行为的原因是什么,以及如何防止这种情况发生?
解决方法:
所以我还没弄清楚为什么会发生这种情况,但我确实有办法解决陷入同样情况的人:
def UnpicklePulpProblem(pickled_problem):
wrong_result = pickle.loads(pickled_problem)
result = pulp.LpProblem(wrong_result.name, wrong_result.sense)
result += wrong_result.objective
for i in wrong_result.constraints: result += wrong_result.constraints[i], i
return result
以这种方式添加目标和约束可确保变量仅在问题中定义一次,因为您基本上是从头开始以这种方式重建问题.
标签:python,pickle,linear-programming,pulp 来源: https://codeday.me/bug/20190708/1405431.html