以下是我用于生成器的代码。它是从Saving and loading multiple objects in pickle file?修改的。该文件是使用joblib.dump创建的,并且包含(到目前为止)单个机器学习模型。
import pickle
from sklearn.externals import joblib
filename = 'ML_models.pkl'
def load(filename):
with open(filename, "rb") as f:
while True:
try:
yield joblib.load(f)
except EOFError:
break
接下来,我按如下方式测试发生器:
models = load(filename)
for model in models:
print model
不幸的是,这会重复打印模型,直到我中断内核。 发出EOF信号的正确方法是什么?
答案 0 :(得分:1)
根据documentation,joblib.load
会返回完整的对象。
def load(filename):
with open(filename, "rb") as f:
return joblib.load(f)