為了怕自己忘記,趕緊發一下文章,這是一篇關於如何將訓練好的scikit-learn模型進行保存以及再次呼叫,代碼中的範例只是簡單的5個數字的加法。
有兩個方法可以保存scikit-learn模型,分別是joblib和pickle,這邊演示的是joblib。
# Save Model Using joblib
import numpy as np
import joblib
from sklearn.linear_model import LinearRegression
model = LinearRegression(fit_intercept=False)
X_train = np.random.rand(1000, 5)*100
y_train = np.sum(X_train, axis=1)
model.fit(X_train, y_train)
joblib.dump(model, 'LR_model')
# load the model from disk
import numpy as np
import joblib
loaded_model = joblib.load('LR_model')
result = loaded_model.predict(np.array([[1, 2, 3, 4, 5]]))
print(result)
Save and Load Machine Learning Models in Python with scikit-learn