我正在尝试保存优化的高斯过程模型以用于不同的脚本。我目前的想法是利用 GPy 的内置 to_dict
和 from_dict
函数将模型信息存储在 json 文件中。类似的东西:
import GPy
import numpy as np
import json
X = np.random.uniform(-3.,3.,(20,1))
Y = np.sin(X) + np.random.randn(20,1)*0.05
kernel = GPy.kern.RBF(input_dim=1, variance=1., lengthscale=1.)
m = GPy.models.GPRegression(X, Y, kernel)
m.optimize(messages=True)
m.optimize_restarts(num_restarts = 10)
jt = json.dumps(m.to_dict(save_data=False), indent=4)
with open("j-test.json", 'w') as file:
file.write(jt)
此步骤没有问题,但是当我尝试使用加载模型信息时遇到问题:
with open("j-test.json", 'r') as file:
d = json.load(file) # d is a dictionary
m2 = GPy.models.GPClassification.from_dict(d, data=None)
这给了我一个断言错误,因为“数据不是无”,它是——或者至少我是这么认为的。
我对 GPy 和使用 jsons 真的很陌生,所以我真的不确定我哪里误入歧途了。我试着查看文档,但文档有点含糊,我找不到它的使用示例。 有没有我错过的步骤/概念?另外,这是存储和重新加载我的模型的最佳方式吗?对此的任何帮助将不胜感激!谢谢!
最佳答案
模块 pickle 是你的 friend !
import pickle
with open('save.pkl', 'wb') as file:
pickle.dump(m, file)
您可以在以后的脚本中调用它:
with open('save.pkl', 'rb') as file:
loaded_model = pickle.load(file)
关于python - 如何保存/加载优化的 GPy 回归模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64557786/