• sklearn模型的保存和加载


    sklearn模型的保存和加载API

    • from sklearn.externals import joblib
      • 保存:joblib.dump(estimator, 'test.pkl')
      • 加载:estimator = joblib.load('test.pkl')

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

    from sklearn.datasets import load_boston
    from sklearn.model_selection import train_test_split
    from sklearn.preprocessing import StandardScaler
    from sklearn.linear_model import LinearRegression, SGDRegressor, Ridge, RidgeCV
    from sklearn.metrics import mean_squared_error
    from sklearn.externals import joblib
    
    
    def dump_load_demo():
        """
        模型保存和加载
        :return: None
        """
        # 1.获取数据
        boston = load_boston()
    
        # 2.数据基本处理
        # 2.1 数据集划分
        x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=22, test_size=0.2)
    
        # 3.特征工程 --标准化
        transfer = StandardScaler()
        x_train = transfer.fit_transform(x_train)
        x_test = transfer.fit_transform(x_test)
        #
        # # 4.机器学习(线性回归)
        # # 4.1 模型训练
        # estimator = Ridge()
        #
        # estimator.fit(x_train, y_train)
        # print("这个模型的偏置是:
    ", estimator.intercept_)
        #
        # # 4.2 模型保存
        # joblib.dump(estimator, "../../data/test.pkl")
    
        # 4.3 模型加载
        estimator = joblib.load("../../data/test.pkl")
    
        # 5.模型评估
        # 5.1 预测值和准确率
        y_pre = estimator.predict(x_test)
        print("预测值是:
    ", y_pre)
    
        score = estimator.score(x_test, y_test)
        print("准确率是:
    ", score)
    
        # 5.2 均方误差
        ret = mean_squared_error(y_test, y_pre)
        print("均方误差是:
    ", ret)
    
    
    if __name__ == '__main__':
        dump_load_demo()
    
    
  • 相关阅读:
    Apache Maven ToolChains的使用
    小师妹学JavaIO之:文件读取那些事
    JDK9的新特性:JPMS模块化
    JDK9的新特性:String压缩和字符编码
    小师妹学JavaIO之:File copy和File filter
    JDK10的新特性:var和匿名类
    Flutter 完美的验证码输入框
    Flutter 不可错过的学习资源
    《Flutter 动画系列》组合动画
    【强烈推荐】适合Flutter初学者的完整项目
  • 原文地址:https://www.cnblogs.com/yeyueweiliang/p/14342320.html
Copyright © 2020-2023  润新知