目錄
一、初步認(rèn)識ONNX
二、pkl轉(zhuǎn)ONNX+可視化模型
三、ONNX Runtime運(yùn)行時
3.1 相關(guān)介紹(了解此運(yùn)行時):
3.2 VS、c++部署onnxruntime
3.3 頭文件引用的一些問題
四、問題匯總:
1. 類沒有成員
2. 版本兼容問題
3. 3.“GetInputName“: 不是 “Ort::Session“ 的成員
官網(wǎng):ONNX Runtime | Home
GitHub - microsoft/onnxruntime
一、初步認(rèn)識ONNX
一圖看懂ONNX模型格式
ONNX學(xué)習(xí)筆記
Onnx模型介紹_HelloWorldQAQ。的博客-CSDN博客
ONNX(Open Neural Network Exchange)是一個開放的深度學(xué)習(xí)模型交換格式,它的目標(biāo)是提供一個標(biāo)準(zhǔn)化的橋梁,使得不同深度學(xué)習(xí)框架之間能夠更輕松地共享和部署模型。
ONNX 的主要特點(diǎn)和目標(biāo)包括:
- 開放性: ONNX 是一個開放標(biāo)準(zhǔn),由微軟、Facebook和其他合作伙伴共同推動。它的目標(biāo)是促進(jìn)深度學(xué)習(xí)生態(tài)系統(tǒng)的互操作性。
- 跨平臺: ONNX 支持在不同的深度學(xué)習(xí)框架之間交換模型。目前,它支持諸如PyTorch、TensorFlow、MXNet等流行的深度學(xué)習(xí)框架。
- 靈活性: ONNX 支持多種深度學(xué)習(xí)模型的表示,包括卷積神經(jīng)網(wǎng)絡(luò)(CNN)、循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)和其他常見的神經(jīng)網(wǎng)絡(luò)架構(gòu)。
- 部署: ONNX 不僅僅是一個模型表示格式,還提供了一些工具和庫,使得用戶能夠在不同的硬件和軟件環(huán)境中有效地部署模型。
一些學(xué)習(xí)資料:[推理部署]?????? 全網(wǎng)最詳細(xì) ONNXRuntime C++/Java/Python 資料!
二、pkl轉(zhuǎn)ONNX+可視化模型
python onnx版本:1.15.0
import joblib
import onnxmltools
from onnxmltools.convert.common.data_types import FloatTensorType
import netron
from sklearn.model_selection import train_test_split # 如果使用 scikit-learn 0.23 以上版本,請改用 sklearn.model_selection 而不是 sklearn.externals
# 加載.pkl模型
model = joblib.load('LinearRegressor.pkl')
# 定義輸入特征的類型和形狀
num_features = 1 # 你的特征數(shù)量
initial_type = [('float_input', FloatTensorType([None, num_features]))]
# 導(dǎo)出ONNX模型
onnx_model = onnxmltools.convert.convert_sklearn(model, initial_types=initial_type)
# 保存ONNX模型為文件
onnxmltools.utils.save_model(onnx_model, 'do_LinearRegressor.onnx')
# 指定你的 ONNX 模型路徑
onnx_model_path = 'do_LinearRegressor.onnx'
# 啟動 Netron 服務(wù)并在瀏覽器中打開可視化界面
netron.start(onnx_model_path)
三、ONNX Runtime運(yùn)行時
3.1 相關(guān)介紹(了解此運(yùn)行時):
想深入了解可以看一下,如果想快速實(shí)踐可以簡單看一下或者跳過
模型部署之 ONNX ONNXRuntime
推理模型部署(一):ONNX runtime 實(shí)踐
Everything You Want to Know About ONNX
MicroSoft onnx and onnx runtim
3.2 VS、c++部署onnxruntime
c++ onnxruntime版本:1.15.1
網(wǎng)址:Releases · microsoft/onnxruntime · GitHub
下載onnxruntime-win-x64-1.15.1.zip
將壓縮包解壓得到include與lib文件夾,添加到環(huán)境變量中,然后將lib中的dll放入release與debug中
#include <iostream>
#include <assert.h>
#include <onnxruntime_cxx_api.h>
#include <onnxruntime_c_api.h>
int main() {
const wchar_t* model_path = L"do_LinearRegressor.onnx";
try {
Ort::Env env(ORT_LOGGING_LEVEL_WARNING, "ONNX_C_API");
std::wcout << L"Attempting to load model from: " << model_path << std::endl;
Ort::SessionOptions session_options;
Ort::Session session(env, model_path, session_options);
std::wcout << L"Model loaded successfully." << std::endl;
Ort::AllocatorWithDefaultOptions allocator;
// 獲取輸入節(jié)點(diǎn)信息
size_t num_input_nodes = session.GetInputCount();
size_t num_output_nodes = session.GetOutputCount();
// 定義輸入和輸出節(jié)點(diǎn)的名稱向量
std::vector<const char*> input_node_names;
std::vector<const char*> output_node_names;
// 獲取輸入節(jié)點(diǎn)信息并填充到向量中
for (size_t i = 0; i < num_input_nodes; i++) {
Ort::AllocatedStringPtr in_name = session.GetInputNameAllocated(i, allocator);
const char* in_name_cstr = in_name.get(); // 獲取字符串指針
std::cout << "Input Name: " << in_name_cstr << std::endl;
input_node_names.push_back(in_name_cstr);
}
// 獲取輸出節(jié)點(diǎn)信息并填充到向量中
for (size_t i = 0; i < num_output_nodes; i++) {
Ort::AllocatedStringPtr out_name = session.GetOutputNameAllocated(i, allocator);
const char* out_name_cstr = out_name.get(); // 獲取字符串指針
std::cout << "Output Name: " << out_name_cstr << std::endl;
output_node_names.push_back(out_name_cstr);
}
// 設(shè)置輸入數(shù)據(jù)的維度,這里以單條數(shù)據(jù)為例
std::vector<int64_t> input_node_dims = { 1, 1 };
size_t input_tensor_size = 1 * 1;
// 構(gòu)造輸入數(shù)據(jù)
std::vector<float> input_tensor_values(input_tensor_size);
for (unsigned int i = 0; i < input_tensor_size; i++)
{
input_tensor_values[i] = 30000;
std::cout << input_tensor_values[i] << std::endl;
}
// create input tensor object from data values
auto memory_info = Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault);
Ort::Value input_tensor = Ort::Value::CreateTensor<float>(
memory_info,
input_tensor_values.data(),
input_tensor_size,
input_node_dims.data(),
input_node_dims.size()
);
assert(input_tensor.IsTensor());
std::vector<Ort::Value> ort_inputs;
ort_inputs.push_back(std::move(input_tensor));
// score model & input tensor, get back output tensor
auto output_tensors = session.Run(
Ort::RunOptions{ nullptr },
input_node_names.data(),
ort_inputs.data(),
ort_inputs.size(),
output_node_names.data(),
1
);
// Get pointer to output tensor float values
float* floatarr = output_tensors[0].GetTensorMutableData<float>();
std::cout << "推理結(jié)果:" << *floatarr << std::endl;
}
catch (const Ort::Exception& e) {
// 處理 Ort::Exception 異常
std::cerr << "Caught Ort::Exception: " << std::string(e.what()) << std::endl;
// 在異常描述信息中查找錯誤代碼
size_t pos = std::string(e.what()).find("ErrorCode: ");
if (pos != std::string::npos) {
std::string error_code_str = std::string(e.what()).substr(pos + 12); // 12 是 "ErrorCode: " 的長度
int error_code = std::stoi(error_code_str);
std::cerr << "Error Code: " << error_code << std::endl;
}
// 可選:進(jìn)行其他異常處理或返回錯誤碼
return -1;
}
return 0;
}
可以參照這個:VS2019 快速配置Onnxruntime環(huán)境_onnxruntime_cxx_api.h_小wu學(xué)cv的博客-CSDN博客
c++通過onnxruntime調(diào)用sklearn_c++調(diào)用sklearn模型_歐拉歐拉木大的博客-CSDN博客
3.3 頭文件引用的一些問題
網(wǎng)上有很多頭文件就不是
#include <onnxruntime_c_api.h>
這樣的而是這樣的
#include <onnxruntime/core/providers/providers.h>
所以他下的是一個完整的資源,什么設(shè)備環(huán)境都有的包括各種docs文檔,不是一個針對性的庫,比如說x64,win,gpu的版本的庫。我們用的時候主要還是要用到3.2中下載的include文件夾中的.h文件,providers.h是一個集合庫,包含了很多.h文件的整合文件,并不是核心庫。
那他們這些文件都在這里:
Releases · microsoft/onnxruntime · GitHub
然后我們可以根據(jù)官網(wǎng)的說明編譯出自己想要的庫,自定義性質(zhì)比較強(qiáng)。一個簡單的例子:
onnxruntime (C++/CUDA) 編譯安裝及部署_initcxxruntime_白色小靴的博客-CSDN博客
四、問題匯總:
1. 類沒有成員
換個寫法,1.15.1版本好像不這么寫了,除非你換回舊版本
2. 版本兼容問題
c++onnxruntime加載onnx模型的時候發(fā)現(xiàn)加載的模型是未知版本,說明這個c++onnxruntime不認(rèn)識,那么就需要知道生成oonx模型的庫版本和推理部署的onnxruntime版本是否兼容
比如我的onnx文件是py生成的onnx版本是1.15.0,那么我的c++中的onnxruntime就需要下載部署1.15.0,如果你的c++中的onnxruntime是1.8.0,運(yùn)行時onnxruntime不認(rèn)識太新的onnx文件
3. 3.“GetInputName“: 不是 “Ort::Session“ 的成員
不要用GetInputName,因?yàn)橐褩売茫羔槻话踩某蒅etInputNameAllocated
不要用GetOutputName,因?yàn)橐褩売?,指針不安全,改成GetOutputNameAllocated文章來源:http://www.zghlxwxcb.cn/news/detail-845614.html
“GetInputName“: 不是 “Ort::Session“ 的成員-CSDN博客文章來源地址http://www.zghlxwxcb.cn/news/detail-845614.html
到了這里,關(guān)于VS c++ onnxruntime 環(huán)境配置、onnx教程、部署推理模型、sklearn pkl模型轉(zhuǎn)onnx、問題匯總的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!