方式一:保存为python支持的pickle格式
import picklefrom sklearn.svm import SVCfrom sklearn import datasets# 定义分类器svm = SVC()# 加载iris数据集iris = datasets.load_iris()# 读取特征X = iris.data# 读取分类标签y = iris.target# 训练模型svm.fit(X, y)# 保存成python支持的文件格式pickle, 在当前目录下可以看到svm.picklewith open('D:/Model/svm.pickle', 'wb') as fw: pickle.dump(svm, fw)# 调用svm.picklewith open('D:/Model/svm.pickle', 'rb') as fr: new_svm = pickle.load(fr) print (new_svm.predict(X[0:1])) # 预测新的数据
方式二:保存为sklearn自带的文件pkl格式
from sklearn.externals import joblibfrom sklearn.svm import SVCfrom sklearn import datasets# 定义分类器svm = SVC()# 加载iris数据集iris = datasets.load_iris()# 读取特征X = iris.data# 读取分类标签y = iris.target# 训练模型svm.fit(X, y)# 保存成sklearn自带的文件格式joblib.dump(svm, 'D:/Model/svm.pkl')# 调用svm.pklnew_svm = joblib.load('D:/Model/svm.pkl')print(new_svm.predict(X[0:1])) # 预测新的数据
方式三:保存为java支持的pmml格式
pip install sklearn2pmml
# 保存为java支持的格式from sklearn2pmml import PMMLPipeline, sklearn2pmmlfrom sklearn.ensemble import RandomForestClassifierfrom sklearn import datasets# 加载iris数据集iris = datasets.load_iris()# 读取特征X = iris.data# 读取分类标签y = iris.targetrf = PMMLPipeline([ ("classifier", RandomForestClassifier())])# 训练模型rf.fit(X, y)# 保存成java支持的文件格式pmml, 在当前目录下可以看到svm.pmmlsklearn2pmml(rf, 'D:/Model/rf.pmml')
java调用:
可参考https://blog.csdn.net/hellozhxy/article/details/82142700
python调用:
pip install pypmml
from pypmml import Modelmodel = Model.fromFile(path)y_predict = model.predict(X_test)