C++?ncnn模型驗(yàn)證精度實(shí)現(xiàn)代碼
驗(yàn)證ncnn模型的精度
1、進(jìn)行pth模型的驗(yàn)證
得到ncnn模型的順序?yàn)椋?pth–>.onnx–>ncnn
.pth的精度驗(yàn)證如下:
如進(jìn)行的是二分類:
model = init_model(model, data_cfg, device=device, mode='eval')
###.pth轉(zhuǎn).onnx模型
# #---
# input_names = ["x"]
# output_names = ["y"]
# inp = torch.randn(1, 3, 256, 128) ##錯(cuò)誤示例
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的兩個(gè)值。
2、轉(zhuǎn)為onnx后的精度驗(yàn)證
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精度驗(yàn)證
首先保證mean、norm輸出的值與onnx保持一致,因?yàn)閛nnx直接輸入值0.5,ncnn模型經(jīng)過mean、norm計(jì)算后的結(jié)果與0.5一致就行。
然后就是ncnn模型的計(jì)算輸出
- 查看輸出結(jié)果是否是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計(jì)算后,得到的結(jié)果進(jìn)行查看,值為0.5則正確轉(zhuǎn)換。得到的結(jié)果送入下面的代碼進(jìn)行輸出。
ncnn結(jié)果為mat,因此采用該方法進(jìn)行遍歷查看。
```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給到模型進(jìn)行推理得到結(jié)果。
4、結(jié)果確認(rèn)
一般情況下,pth模型與onnx模型結(jié)果相差不大,ncnn會(huì)有點(diǎn)點(diǎn)損失,千分位上的損失,這樣精度基本上是一致的。
若不一致,看哪一步結(jié)果相差太大,如果是ncnn這一步相差太大,檢查是否是值輸入有問題,或者是輸入的(h,w)弄反了。
到此這篇關(guān)于C++ ncnn模型驗(yàn)證精度實(shí)現(xiàn)代碼的文章就介紹到這了,更多相關(guān)C++ ncnn驗(yàn)證精度內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++實(shí)現(xiàn)校園運(yùn)動(dòng)會(huì)報(bào)名系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)校園運(yùn)動(dòng)會(huì)報(bào)名系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-10-10
C++實(shí)現(xiàn)雷霆戰(zhàn)機(jī)可視化小游戲
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)雷霆戰(zhàn)機(jī)可視化小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-11-11
win10+VS2017+Cuda10.0環(huán)境配置詳解
這篇文章主要介紹了win10+VS2017+Cuda10.0環(huán)境配置詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08

