python保存和加载机器学习模型
程序员文章站
2022-07-13 09:00:54
...
一:使用pickle实现
# Save Model Using Pickle
import pandas
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
import pickle
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = pandas.read_csv(url, names=names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
test_size = 0.33
seed = 7
X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size, random_state=seed)
# Fit the model on 33%
model = LogisticRegression()
model.fit(X_train, Y_train)
# save the model to disk
filename = 'finalized_model.sav'
pickle.dump(model, open(filename, 'wb'))#保存模型
# some time later...
# load the model from disk
loaded_model = pickle.load(open(filename, 'rb'))#加载保存的模型
result = loaded_model.score(X_test, Y_test)
print(result)
二:使用Joblib实现
# Save Model Using joblib
import pandas
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
from sklearn.externals import joblib
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = pandas.read_csv(url, names=names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
test_size = 0.33
seed = 7
X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size, random_state=seed)
# Fit the model on 33%
model = LogisticRegression()
model.fit(X_train, Y_train)
# save the model to disk
filename = 'finalized_model.sav'
joblib.dump(model, filename)
# some time later...
# load the model from disk
loaded_model = joblib.load(filename)
result = loaded_model.score(X_test, Y_test)
print(result)
上一篇: 一文搞定泛型知识
推荐阅读
-
Tensorflow加载预训练模型和保存模型的实例
-
MacOS配置Anaconda3(Miniconda3)下Python3.6、Python3.7和Python2.7环境和基础机器学习、神经网络相关包详解(版本号对应)
-
tensorflow三种模型的加载和保存的方法(.ckpt,.pb,SavedModel)
-
python机器学习朴素贝叶斯算法及模型的选择和调优详解
-
【机器学习基础】Python数据预处理:彻底理解标准化和归一化
-
机器学习——SVM之python实现数据样本标准化和归一化
-
Python3入门机器学习之11.4随机森林和Extra-Trees
-
python保存加载机器学习模型实例
-
机器学习—保存模型、加载模型—Joblib
-
python保存和加载机器学习模型