C++?ncnn模型驗證精度實現(xiàn)代碼
驗證ncnn模型的精度
1、進行pth模型的驗證
得到ncnn模型的順序為:.pth–>.onnx–>ncnn
.pth的精度驗證如下:
如進行的是二分類:
model = init_model(model, data_cfg, device=device, mode='eval')
###.pth轉.onnx模型
# #---
# input_names = ["x"]
# output_names = ["y"]
# inp = torch.randn(1, 3, 256, 128) ##錯誤示例
inp = np.full((1, 3, 160, 320), 0.5).astype(np.float) #(160,320) = (h,w)
inp = torch.FloatTensor(inp)
out = model(inp)
print(out)
沒有經(jīng)過softmax層,out輸出為±1的兩個值。
2、轉為onnx后的精度驗證
sess = onnxruntime.InferenceSession("G:\\pycharm_pytorch171\\pytorch_classification\\main\\sim.onnx", providers=["CUDAExecutionProvider"]) # use gpu
input_name = sess.get_inputs()[0].name
print("input_name: ", input_name)
output_name = sess.get_outputs()[0].name
print("output_name: ", output_name)
# test_images = torch.rand([1, 3, 256, 128])
test_images = np.full((1, 3, 160, 320), 0.5).astype(np.float) #(160,320) = (h,w)
test_images = torch.FloatTensor(test_images)
print("test_image", test_images)
prediction = sess.run([output_name], {input_name: test_images.numpy()})
print(prediction)
3、ncnn精度驗證
首先保證mean、norm輸出的值與onnx保持一致,因為onnx直接輸入值0.5,ncnn模型經(jīng)過mean、norm計算后的結果與0.5一致就行。
然后就是ncnn模型的計算輸出
- 查看輸出結果是否是0.5,首先得將輸入值1給到img
```cpp
constexpr int w = 320;
constexpr int h = 160;
float cbuf[h][w];
cv::Mat img(h, w, CV_8UC3,(float *)cbuf);
//BYTE* iPtr = new BYTE[128 * 256 * 3];
BYTE* iPtr = new BYTE[h * w * 3];
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
for (int k = 0; k < 3; k++)
{
//iPtr[i * 256 * 3 + j * 3 + k] = img.at<cv::Vec3f>(i, j)[k];
img.at<cv::Vec3b>(i, j)[k] = 1;
}
}
}
```
- 經(jīng)過上面的賦值,通過了mean、norm計算后,得到的結果進行查看,值為0.5則正確轉換。得到的結果送入下面的代碼進行輸出。
ncnn結果為mat,因此采用該方法進行遍歷查看。
```cpp
//輸出ncnn mat
void ncnn_mat_print(const ncnn::Mat& m)
{
for (int q = 0; q < m.c; q++)
{
const float* ptr = m.channel(q);
for (int y = 0; y < m.h; y++)
{
for (int x = 0; x < m.w; x++)
{
printf("%f ", ptr[x]);
}
ptr += m.w;
printf("\n");
}
printf("------------------------\n");
}
}
```
將mat給到模型進行推理得到結果。
4、結果確認
一般情況下,pth模型與onnx模型結果相差不大,ncnn會有點點損失,千分位上的損失,這樣精度基本上是一致的。
若不一致,看哪一步結果相差太大,如果是ncnn這一步相差太大,檢查是否是值輸入有問題,或者是輸入的(h,w)弄反了。
到此這篇關于C++ ncnn模型驗證精度實現(xiàn)代碼的文章就介紹到這了,更多相關C++ ncnn驗證精度內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
將正小數(shù)轉化為2-9進制小數(shù)的實現(xiàn)方法
本篇文章對正小數(shù)轉化為2-9進制小數(shù)的實現(xiàn)方法進行了介紹,需要的朋友參考下2013-05-05
C++11中l(wèi)onglong超長整型和nullptr初始化空指針
本文介紹?C++11?標準中新添加的?long?long?超長整型和?nullptr?初始化空指針,在?C++11?標準下,相比?NULL?和?0,使用?nullptr?初始化空指針可以令我們編寫的程序更加健壯,本文結合示例代碼給大家詳細講解,需要的朋友跟隨小編一起看看吧2022-12-12
深入剖析設計模式中的組合模式應用及在C++中的實現(xiàn)
這篇文章主要介紹了設計模式中的組合模式應用及在C++中的實現(xiàn),組合模式可以清晰地反映出遞歸構建樹狀的組合結構,需要的朋友可以參考下2016-03-03

