如何在GridSearchCV中保存最佳估计器?

Lan*_*orr 3 python save gridsearchcv

当面对大型数据集时,我需要花一天的时间GridSearchCV()来训练具有最佳参数的 SVM。如何保存最佳估计器,以便下次启动计算机时可以直接使用这个经过训练的估计器?

Sim*_*awe 9

默认情况下,GridSearchCV不公开或存储最佳模型实例,它仅返回导致最高分数的参数集。如果您想要最好的预测器,则必须指定refit=True,或者如果您使用多个指标refit=name-of-your-decider-metric这将使用完整的数据集和找到的最佳参数运行最终的训练步骤。为了找到最佳参数,GridSearchCV显然不会使用整个数据集进行训练,因为它们必须拆分保留验证集。

现在,当您这样做时,您可以通过属性获取模型best_estimator_。有了这个,您可以使用 joblib 选择该模型并在第二天重新加载它以进行预测。在伪代码和真实代码的混合中,其内容如下:

from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
from joblib import dump, load

svc = SVC() # Probably not what you are using, but just as an example
gcv = GridSearchCV(svc, parameters, refit=True) 
gcv.fit(X, y)
estimator = gcv.best_estimator_
dump(estimator, "your-model.joblib")
# Somewhere else
estimator = load("your-model.joblib")
Run Code Online (Sandbox Code Playgroud)