模型的保存和加载
1.sklearn模型的保存和加载API
- from sklearn.externals import joblib
- 保存:joblib.dump(estimator, ‘test.pkl’)
- 加载:estimator = joblib.load(‘test.pkl’)
2.线性回归的模型保存加载案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| def load_dump_demo(): """ 模型保存和加载 :return: """ data = load_boston()
x_train, x_test, y_train, y_test = train_test_split(data.data, data.target, random_state=22)
transfer = StandardScaler() x_train = transfer.fit_transform(x_train) x_test = transfer.fit_transform(x_test)
estimator = joblib.load("./data/test.pkl")
y_predict = estimator.predict(x_test) print("预测值为:\n", y_predict) print("模型中的系数为:\n", estimator.coef_) print("模型中的偏置为:\n", estimator.intercept_)
error = mean_squared_error(y_test, y_predict) print("误差为:\n", error)
|
3.tips
如果你在学习过程中,发现使用上面方法报如下错误:
1
| ImportError: cannot import name 'joblib' from 'sklearn.externals' (/Library/Python/3.7/site-packages/sklearn/externals/__init__.py)
|
这是因为scikit-learn版本在0.21之后,无法使用from sklearn.externals import joblib
进行导入,你安装的scikit-learn版本有可能是最新版本。如果需要保存模块,可以使用:
1 2 3 4 5
| pip install joblib
import joblib
|
安装joblib,然后使用joblib.load
进行加载;使用joblib.dump
进行保存
参考:https://scikit-learn.org/stable/modules/model_persistence.html