人工智能基础(十六)模型的保存与加载

模型的保存与加载

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():
    boston = load_boston()
    x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=22, test_size=0.2)
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.fit_transform(x_test)
    estimator = Ridge()
    estimator.fit(x_train, y_train)
    print("这个模型的偏置是:\n", estimator.intercept_)
    joblib.dump(estimator, "./data/test.pkl")
    #estimator = joblib.load("./data/test.pkl")
    y_pre = estimator.predict(x_test)
    print("预测值是:\n", y_pre)
    score = estimator.score(x_test, y_test)
    print("准确率是:\n", score)
    ret = mean_squared_error(y_test, y_pre)
    print("均方误差是:\n", ret)
if __name__ == '__main__':
    dump_load_demo()

注意:
1、保存文件,后缀名是.pki
2、加载模型是需要通过一个变量进行承接

上一篇:机器学习-朴素贝叶斯算法


下一篇:《机器学习Python实现_10_13_集成学习_xgboost_分类的简单实现》