sklearnトレーニングモデル、モデルファイル(テキスト、PKL)、モデルファイル変換(pkl2onnx)とモデルの可視化保存

1.環境

IDE:Jupyterラボ、達成するためにPython2カーネルを使用して

モデルの可視化:GraphVizをは、jupyterで直接使用することができます。Netronウィンドウのバージョン

変換モデル:onnx / onnx-生態系容器中

2.コード

モデルを作成し、訓練します

import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import pandas as pd


from sklearn.datasets import load_iris
from sklearn import tree

iris = load_iris()

# 训练模型
clf =  tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
with open("iris.dot", 'w') as f:
    f = tree.export_graphviz(clf, out_file=f)


from IPython.display import Image  
import pydotplus

dot_data = tree.export_graphviz(clf, out_file=None, 
                         feature_names=iris.feature_names,  
                         class_names=iris.target_names,  
                         filled=True, rounded=True,  
                         special_characters=True)


graph = pydotplus.graph_from_dot_data(dot_data)

# 模型可视化
Image(graph.create_png())


 

PDFとして画像を保存します

#设置环境变量,解决调用graph时“InvocationException: GraphViz's executables not found”的错误。

import os
os.environ["PATH"] += os.pathsep + 'D:/Anaconda2/Library/bin/graphviz/' 

dot_data = tree.export_graphviz(clf, out_file=None)
graph = pydotplus.graph_from_dot_data(dot_data) 
graph.write_pdf("iris.pdf")

使用モデルPKLの保存形式JOBLIB、およびPKL予測モデルのファイル形式を読み取ります

from sklearn.externals import joblib
joblib.dump(clf, "DecisionTreeClassifier.pkl")

f1=joblib.load('DecisionTreeClassifier.pkl')

f1.score(iris.data, iris.target)


ピクルスのテキスト形式を使用してモデルを保存し、モデルファイルに保存ピクルスによって予測された読み取り値

import pickle
s=pickle.dumps(clf)
f=open('DecisionTreeClassifier.txt','w')
f.write(s)
f.close()

f2=open('DecisionTreeClassifier.txt','r')
s2=f2.read()
clf2=pickle.loads(s2)
clf2.score(iris.data, iris.target)

モデルフォーマット変換

コードonnx / onnx・エコシステムコンテナを実行します。

onnxためPKLモデルファイル形式を変換しますDecisionTreeClassifier.pkl ----> model.onnx

from sklearn.externals import joblib
from skl2onnx import convert_sklearn
from skl2onnx.common.data_types import *
import onnxmltools

# Update the input name and path for your sklearn model
input_skl_model = 'DecisionTreeClassifier.pkl'

# input data type for your sklearn model
input_data_type = [('float_input', FloatTensorType([1, 4]))]

# Change this path to the output name and path for the ONNX model
output_onnx_model = 'model.onnx'

# Load your sklearn model
skl_model = joblib.load(input_skl_model)

# Convert the sklearn model into ONNX
onnx_model = onnxmltools.convert_sklearn(skl_model, initial_types=input_data_type)

# Save as protobuf
onnxmltools.utils.save_model(onnx_model, output_onnx_model)

3. NetronビューPKLモデルとモデルonnx

ビューモデルPKLフォーマット

 

ビューモデルonnxフォーマット

 

公開された227元の記事 ウォン称賛94 ビュー540 000 +

おすすめ

転載: blog.csdn.net/wiborgite/article/details/95778182