How to predict fast? 修改onnx model支持batch模式

 在onnxruntime中如何可以支持“batching”模式使模型前向运行更快呢:

For example, if your model has graph input (taking image case) of 
shape [1, 3, 224, 224] 
- it can only take one 3 channel image of height and width 224. 
But if it has graph inputlike this - ["some_string", 3, 224, 224]
- it can handle "batched" input of any size.

上述意思是修改onnx模型input的第一个维度为None即可适应batch输入,此外,需要对应修改output的第一个维度为None

import onnx
mp = onnx.load_model('aa.onnx')
mp.graph.input[0].type.tensor_type.shape.dim[0].dim_param = 'None'
onnx.save(mp, 'aa_batch.onnx')
[C++] after session_ load aa_batch.onnx.
auto output_tensors = session_->Run(Ort::RunOptions{ nullptr }, input_node_names.data(), &input_tensor, 1, output_node_names.data(), 1);
It runs very fast! 

eg:

import onnx
from onnx import helper, checker
from onnx import TensorProto,GraphProto
import onnx.utils
from onnx.tools import update_model_dims
import re
import argparse
import numpy as np

onnx_path='./resnet50-v1-7.onnx'
model = onnx.load(onnx_path)                         
                                                      
dim_proto0 = model.graph.input[0].type.tensor_type.shape.dim[0]
dim_proto0.dim_param = 'None'
dim_proto_o1 = model.graph.output[0].type.tensor_type.shape.dim[0]
dim_proto_o1.dim_param = 'None'
onnx.checker.check_model(model)
onnx.save(model, 'dynamic_input_resnet_batch_50.onnx')

参考链接:https://github.com/microsoft/onnxruntime/issues/2118
                  OnnxRunTime的部署流程_hjxu2016的博客-CSDN博客_c++ onnx 部署

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
To apply CNN-BiLSTM-Attention to predict one feature based on other features, you can follow these steps in Python: 1. Data Preparation: Collect the historical data of the target feature and other features, and split them into training and testing sets. You can use libraries like pandas and numpy for data manipulation. 2. Feature Engineering: Extract relevant features from the data, and normalize them to reduce the effect of outliers. You can use sklearn.preprocessing for feature scaling. 3. Model Building: Build a CNN-BiLSTM-Attention model using libraries like Keras or PyTorch. The model should take the other features as input and predict the target feature for the next 12 hours (6 am to 18 pm). 4. Model Training: Train the model on the training set, and validate it on the testing set. You can use libraries like TensorFlow or PyTorch for model training. 5. Model Evaluation: Evaluate the model performance using metrics like Mean Squared Error (MSE) or Root Mean Squared Error (RMSE). You can use libraries like sklearn.metrics for evaluation. Here is some sample code to get started with: ``` # Data Preparation import pandas as pd import numpy as np # Load data data = pd.read_csv('data.csv') # Split data into training and testing sets train_data = data[:-24] test_data = data[-24:] # Feature Engineering from sklearn.preprocessing import MinMaxScaler # Extract relevant features train_features = train_data[['feature1', 'feature2', 'feature3']].values train_target = train_data['target'].values test_features = test_data[['feature1', 'feature2', 'feature3']].values test_target = test_data['target'].values # Normalize features scaler = MinMaxScaler() train_features = scaler.fit_transform(train_features) test_features = scaler.transform(test_features) # Model Building from keras.models import Sequential from keras.layers import Dense, Conv1D, MaxPooling1D, LSTM, Bidirectional, Attention # Build model model = Sequential() model.add(Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(train_features.shape[1], 1))) model.add(MaxPooling1D(pool_size=2)) model.add(Bidirectional(LSTM(64, return_sequences=True))) model.add(Attention()) model.add(Dense(1)) # Model Training model.compile(optimizer='adam', loss='mse') model.fit(train_features.reshape(train_features.shape[0], train_features.shape[1], 1), train_target, epochs=50, batch_size=32) # Model Evaluation from sklearn.metrics import mean_squared_error # Test model test_pred = model.predict(test_features.reshape(test_features.shape[0], test_features.shape[1], 1)) test_mse = mean_squared_error(test_target, test_pred) print('Test MSE:', test_mse) ``` Note that this is just a sample code, and you may need to modify it based on your specific use case.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值