如何在pyomo中保存(pickle)模型实例

时间:2018-06-13 09:53:01

标签: python pyomo

我想创建一个模型实例,然后保存它,以便我可以在以后加载和解决(与解决相比,初始化需要很长时间)。 当我尝试这个时它给了我以下错误。

<button (click)="testService.getDataService()">Button</button>

AttributeError的: 不能腌制当地对象'Euphemia。 init .. obj_expression

目标函数是:

with open('model.pickle', 'w') as f:
    pickle.dump(instance, f)

有人知道如何保存具体模型吗?

2 个答案:

答案 0 :(得分:0)

解决方案是cloudpickle模块,普通的泡菜具有酸洗功能问题。一个例子:

import cloudpickle

with open('test.pkl', mode='wb') as file:
   cloudpickle.dump(instance, file)


with open('test.pkl', mode='rb') as file:
   instance = cloudpickle.load(file)

答案 1 :(得分:0)

使用DerivativeVar时,似乎泡菜(还有泡菜)将无法工作。

from pyomo.environ import *
from pyomo.dae import *
import pickle
import dill
model = ConcreteModel()
model.x = ContinuousSet(initialize=(0., 1.))
model.y = Var(model.x, initialize=1.)
with open('model1.pickle', 'wb') as f:
    pickle.dump(model, f)

model.dydx = DerivativeVar(model.y, wrt=model.x)
with open('model2.pickle', 'wb') as f:
    try:
        pickle.dump(model, f)
    except TypeError:
        dill.dump(model, f)

莳萝似乎可以代替弱引用:Pickling weakref in Python