1 sklearn模型的保存和加载API

  • from sklearn.externals import joblib

    • 保存:joblib.dump(estimator, ‘test.pkl’)
    • 加载:estimator = joblib.load(‘test.pkl’)

      2 线性回归的模型保存加载案例

      1. def load_dump_demo():
      2. """
      3. 线性回归:岭回归
      4. :return:
      5. """
      6. # 1.获取数据
      7. data = load_boston()
      8. # 2.数据集划分
      9. x_train, x_test, y_train, y_test = train_test_split(data.data, data.target, random_state=22)
      10. # 3.特征工程-标准化
      11. transfer = StandardScaler()
      12. x_train = transfer.fit_transform(x_train)
      13. x_test = transfer.fit_transform(x_test)
      14. # 4.机器学习-线性回归(岭回归)
      15. # # 4.1 模型训练
      16. # estimator = Ridge(alpha=1)
      17. # estimator.fit(x_train, y_train)
      18. #
      19. # # 4.2 模型保存
      20. # joblib.dump(estimator, "./data/test.pkl")
      21. # 4.3 模型加载
      22. estimator = joblib.load("./data/test.pkl")
      23. # 5.模型评估
      24. # 5.1 获取系数等值
      25. y_predict = estimator.predict(x_test)
      26. print("预测值为:\n", y_predict)
      27. print("模型中的系数为:\n", estimator.coef_)
      28. print("模型中的偏置为:\n", estimator.intercept_)
      29. # 5.2 评价
      30. # 均方误差
      31. error = mean_squared_error(y_test, y_predict)
      32. print("误差为:\n", error)