python - 如何通过 scikit-learn 保存训练好的模型?

标签 python python-3.x scikit-learn save pre-trained-model

我正在尝试重新创建经过训练的模型的预测,但我不知道如何保存模型。 例如,我想保存经过训练的高斯处理回归模型,并在训练模型后重新创建预测。 我用来训练模型的包是 scikit-learn。

kernel = DotProduct() + WhiteKernel()
gpr = GaussianProcessRegressor(kernel=kernel,random_state=0)
gpr.fit(X,y)

最佳答案

您可以使用:

<强>1。 pickle

from sklearn import svm
from sklearn import datasets

iris = datasets.load_iris()
X, y = iris.data, iris.target

clf = svm.SVC()
clf.fit(X, y)  

##########################
# SAVE-LOAD using pickle #
##########################
import pickle

# save
with open('model.pkl','wb') as f:
    pickle.dump(clf,f)

# load
with open('model.pkl', 'rb') as f:
    clf2 = pickle.load(f)

clf2.predict(X[0:1])

<强>2。 joblib

来自scikit-learn documentation :

In the specific case of scikit-learn, it may be better to use joblib’s replacement of pickle (dump & load), which is more efficient on objects that carry large numpy arrays internally as is often the case for fitted scikit-learn estimators, but can only pickle to the disk and not to a string:

from sklearn import svm
from sklearn import datasets

iris = datasets.load_iris()
X, y = iris.data, iris.target

clf = svm.SVC()
clf.fit(X, y)  

##########################
# SAVE-LOAD using joblib #
##########################
import joblib

# save
joblib.dump(clf, "model.pkl") 

# load
clf2 = joblib.load("model.pkl")

clf2.predict(X[0:1])

关于python - 如何通过 scikit-learn 保存训练好的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56107259/

相关文章:

python-3.x - 在 AWS lambda 中使用/tmp 目录有多安全?

python - 使用sklearn进行线性回归时遇到的数值错误

scikit-learn - 在训练之前或作为基于像素的分类的后处理执行的图形切割

python networkx eigenvector_centrality 和 eigenvector_centrality_numpy 都不适用于此 gml

python - 编写视频而不会丢失数据或比特率 - opencv(python)

python-3.x - 将 '000111010010111' 拆分为 ['000' ,'111' ,'0' , 1',' 0 0',' 1',' 0x9'104] 15

python-3.x - gcp firestore上的python超时流方法

python - GridSearchCV 是否执行交叉验证?

python - Flask - 蓝图 - 在第一次请求之前?

python - 如何在 Choregraphe Log Viewer 上查看我的服务日志?