1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

がちもとさんAdvent Calendar 2022

Day 21

PyCaretのモデルをONNXに変換すーる(回帰分析、Mac)

Last updated at Posted at 2022-12-20

はじめに

PyCaretで作成したモデルをONNXに変換しまーす

開発環境

  • MacBookPro 2018
  • Python 3.8

導入

1.anaconda環境作成

conda create -n py38 python=3.8

2.ライブラリのインストール

pip install pycaret
pip install skl2onnx
pip install onnxruntime==1.10.0
pip install numpy==1.20.3
brew install libomp

3.insurance.csvを回帰分析し、モデルをonnxに変換します

※簡単にage,bmi,children,chargesのみにしています
image.png

pycaret2onnx.py
from pycaret.regression import *
import pandas as pd
from skl2onnx import to_onnx

df = pd.read_csv("insurance.csv")
s = setup(df, target = 'charges')

best = compare_models()
# save_model(best, 'insurance') # insurance.pkl

X_sample = get_config('X_train')[:1]
print(X_sample)

onnx_model = to_onnx(best, X_sample.to_numpy(), target_opset={'':15, 'ai.onnx.ml':2})

with open("insurance.onnx", "wb") as f:
    f.write(onnx_model.SerializeToString())

4.変換したONNXを用いて、Pythonで推論します

predict.py
import onnxruntime as rt
import numpy as np

session = rt.InferenceSession("insurance.onnx")

print(session.get_inputs()[0].name) # X
print(session.get_outputs()[0].name) # variable

# age, bmi, children_0, children_1, children_2, children_3, children_4, children_5
inputs = np.array([[19.0,27.9,1.0,0.0,0.0,0.0,0.0,0.0]],dtype=np.float32)
outputs = session.run(["variable"],{"X": inputs})[0]
print(outputs[0][0])

5.C#で推論します

using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;

Console.WriteLine(Directory.GetCurrentDirectory());
var session = new InferenceSession("../../../insurance.onnx");

Tensor<float> input = new DenseTensor<float>(new[] { 1, 8 });
input[0, 0] = 19.0f;
input[0, 1] = 27.9f;
input[0, 2] = 1.0f;
input[0, 3] = 0.0f;
input[0, 4] = 0.0f;
input[0, 5] = 0.0f;
input[0, 6] = 0.0f;
input[0, 7] = 0.0f;

var inputs = new List<NamedOnnxValue>() {
    NamedOnnxValue.CreateFromTensor<float>("X",input)
};

var results = session.Run(inputs);
Console.WriteLine(results.First().AsTensor<float>()[0]);

image.png

参考文献

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?