一、概述
1.1 模型的保存
当模型完成训练之后,可以得到参数,例如线性回归得到权重与偏置等。可以将这些参数保存起来,方便下次调用。
一般与Pipeline联合使用,先用Pipline操作,在保存Pipline训练好的模型。
如果不使用Pipeline,则需要将每个训练都保存起来,太过麻烦。
1.2 模型的加载
将保存的模型,再次加载,训练的各种参数可以直接使用。
二、 代码
from sklearn.preprocessing import StandardScaler from sklearn.linear_model import Ridge from sklearn.model_selection import train_test_split from sklearn.datasets import load_boston from sklearn.pipeline import Pipeline from sklearn.preprocessing import PolynomialFeatures import joblib import warnings warnings.filterwarnings("ignore") X,y = load_boston(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1) pipe_lr = Pipeline([ ('pf', PolynomialFeatures(degree=3,include_bias=False,interaction_only=False)), ('sc', StandardScaler()), ('clf', Ridge(alpha=0.8))]) # fit依次对前n-1的学习器执行fit和transform方法,并且对最后一个学习器执行fit方法 pipe_lr.fit(X_train, y_train) # score依次对前n-1的学习器执行transform方法,并且对最后一个学习器执行score方法 print(f'Train score: {pipe_lr.score(X_train, y_train):.2%},Test score: {pipe_lr.score(X_test, y_test):.2%},') clf = pipe_lr.named_steps['clf'] print(f'前3个权重:{clf.coef_[:5]}') # 模型保存(sklearn框架保存后缀建议采用pkl) joblib.dump(value=pipe_lr, filename='../data/pipe_lr.pkl') # 模拟在其它页面加载模型 pipe_lr_l=joblib.load(filename='../data/pipe_lr.pkl') # 调用之前的训练参数 clf_l = pipe_lr_l.named_steps['clf'] print(f'前3个权重:{clf_l.coef_[:5]}') #结果与前面训练的结果相同 X, y = load_boston(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1) # 可以返现训练结果与前面的训练结果也相同 print(f'Train score: {pipe_lr_l.score(X_train, y_train):.2%},Test score: {pipe_lr_l.score(X_test, y_test):.2%},')
标签:score,模型,pipe,test,train,lr,joblib,import,加载 From: https://www.cnblogs.com/qianslup/p/16974868.html