我的优化需要几个小时才能在高性能服务器上解决。我想将解决方案保存到磁盘,然后在我的笔记本电脑上将它们重新加载到模型实例中。这将使我能够在 python 命令行中以交互方式探索结果,并开发或测试新编写的导出代码。 pyomo 库有很多函数可以将数据转储到磁盘,但没有提供将数据加载回不同运行时环境的明确解决方案。
我理想的解决方案是在加载解决方案后对实例进行 pickle,以便它封装输入、解决方案和整个运行时状态。不幸的是,该实例附加了不可 pickle 的方法,pyomo 团队还没有编写自定义 pickle 函数。 2015 forum thread 中建议的解决方法是腌制结果对象。结果对象在 v5.1.1 中默认没有加载解决方案,但是 another post解释了如何解决这个问题。
我设法拼凑出一个适用于 pyomo v5.1.1 的解决方案,但想知道是否有更好的方法。
保存
# ...Define abstract model
# ...Load data from input directory and create model instance
# Solve, get a results object that only contains execution metadata
results = opt.solve(instance)
# Load solution data into results object
instance.solutions.store_to(results)
# Archive results: solution & execution metadata
pickle.dump(results, open("results.pickle", "wb"))
重新加载
...将代码、输入目录和 results.pickle 文件从服务器同步到我的笔记本电脑。
# ...Define abstract model
# ...Load data from input directory and create model instance
# Load results from pickle: metadata & solution
results = pickle.load(open("results.pickle", "wb"))
# Load solution data into instance object
instance.solutions.load_from(results)
最佳答案
如 this question 中所述,一个解决方案是使用 cloudpickle
来 pickle 实例:
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 - 如何保存 Pyomo 解决方案并重新加载到单独的运行时环境中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47212921/