介绍两种保存训练好的模型方法
joblibimport joblib
joblib.dump(model, ‘model1.pkl’) #保存模型,后缀为 .pkl
pre = joblib.load(‘model1.pkl’) #加载模型
代码实现:
from matplotlib import pyplot as plot import numpy as np from sklearn import linear_model import joblib #创建数据集生成50到60,shape=(20,1)的随机二维数组 X_train = np.random.randint(50,60,size=(20,1)) Y_train = np.random.randint(50,60,size=(20,1)) # 建立线性模型 model1 = linear_model.LinearRegression() model1.fit(X_train, Y_train) # 保存 model joblib .dump(model1, 'model1.pkl') print("模型保存成功") # 加载 model pre = joblib .load('model1.pkl') Y_pred = pre.predict(X_train) #使用predict预测 # 可视化 # 1.训练集数据 plot.scatter(X_train, Y_train, color='green') # 2.线性预测数据 plot.plot(X_train, Y_pred, color='red') plot.show()
结果:
import pickle
f = open(‘model2.pkl’, ‘wb’) # 保存模型,后缀为 .pkl
pickle.dump(model2, f)
f.close()
f = open(’.model2.pkl’, ‘rb’) # 加载模型
pre = pickle.load(f)
f.close()
代码示例:
from matplotlib import pyplot as plot import numpy as np from sklearn import linear_model import pickle #创建数据集生成50到60,shape=(20,1)的随机二维数组 X_train = np.random.randint(50,60,size=(20,1)) Y_train = np.random.randint(50,60,size=(20,1)) # 建立线性模型 model2 = linear_model.LinearRegression() model2.fit(X_train, Y_train) # 保存 model f = open('model2.pkl', 'wb') pickle.dump(model2, f) f.close() print("模型保存成功") # 加载 model f = open('model2.pkl', 'rb') pre = pickle.load(f) f.close() Y_pred = pre.predict(X_train) # 可视化 # 1.训练集数据 plot.scatter(X_train, Y_train, color='green') # 2.测试数据 plot.plot(X_train, Y_pred, color='red') plot.show()
结果:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)