介绍两种保存训练好的模型方法
joblib
import 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
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)
joblib .dump(model1, 'model1.pkl')
print("模型保存成功")
pre = joblib .load('model1.pkl')
Y_pred = pre.predict(X_train)
plot.scatter(X_train, Y_train, color='green')
plot.plot(X_train, Y_pred, color='red')
plot.show()
结果:
pickle
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
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)
f = open('model2.pkl', 'wb')
pickle.dump(model2, f)
f.close()
print("模型保存成功")
f = open('model2.pkl', 'rb')
pre = pickle.load(f)
f.close()
Y_pred = pre.predict(X_train)
plot.scatter(X_train, Y_train, color='green')
plot.plot(X_train, Y_pred, color='red')
plot.show()
结果:
|