如何在 pyomo 中保存(pickle)模型实例 [英] How to save (pickle) a model instance in pyomo

查看:93
本文介绍了如何在 pyomo 中保存(pickle)模型实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a model instance and then save it so I can load and solve at a later time (the initialization takes quite long compared to the solving). When I tried this it gave me the following error.

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

属性错误:无法pickle本地对象'Euphemia.init..obj_expression

AttributeError: Can't pickle local object 'Euphemia.init..obj_expression

目标函数是这样的:

    def obj_expression(model):
        curve = sum(model.x[area, hour, Type, index] * model.Q[area, hour, Type, index] * 
                    ( model.P1[area, hour, Type, index] + model.P0[area, hour, Type, index] ) / 2  
                        for (area, hour, Type, index) in model.Curve )
        bids = sum(model.y[area, index] * model.PB[area, index] * 
                       sum( model.QB[area, index, hour] for (hour) in model.Hours ) 
                               for (area, index) in model.Bids  )
        return curve + bids
    self.model.OBJ = pe.Objective(rule = obj_expression, sense = pe.maximize)

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

does anybody know how to save a concrete model?

推荐答案

解决方案是cloudpickle模块,普通pickle有问题pickle功能.一个例子:

The solution is the cloudpickle module, regular pickle has problems pickling functions. An example:

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)

这篇关于如何在 pyomo 中保存(pickle)模型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆