嘉楠K510开发板的AI应用5——模型验证和格式转换
[复制链接]
嘉楠K510开发板的AI应用5——模型验证和格式转换
在前一篇(https://bbs.eeworld.com.cn/thread-1228112-1-1.html)已经基于自建模型训练了一个分类模型“model_ex-019_acc-0.744914_loss-0.569983”,
model_ex-019_acc-0.744914_loss-0.569983.h5
(17.44 MB, 下载次数: 0)
从名字就可以看到,它精度不太高。这次我们来试试如何使用这个模型。
一、在电脑上测试模型效果
首先我们知道这个模型是用于分类的,可以将图片分成3类:dinosaur、flower、hotdog。
use_h5_model.py
(928 Bytes, 下载次数: 0)
从网上随机取用几张图片(确保不要踩到训练集),我们试试效果:
[[9.9788362e-01 1.5169366e-38 2.1163719e-03]]
dinosaur:99.78836178779602%
hotdog:0.21163718774914742%
flower:1.516936556327676e-36%
[[1.0000000e+00 3.9236673e-16 0.0000000e+00]]
dinosaur:100.0%
flower:3.9236673111275487e-14%
hotdog:0.0%
[[3.668387e-21 1.000000e+00 0.000000e+00]]
flower:100.0%
dinosaur:3.6683868813399893e-19%
hotdog:0.0%
[[1.0000000e+00 7.0039135e-21 0.0000000e+00]]
dinosaur:100.0%
flower:7.003913537690513e-19%
hotdog:0.0%
[[0.0000000e+00 2.2953879e-23 1.0000000e+00]]
hotdog:100.0%
flower:2.295387861194658e-21%
dinosaur:0.0%
[[0. 1. 0.]]
flower:100.0%
hotdog:0.0%
dinosaur:0.0%
[[0.0000000e+00 3.7185172e-28 1.0000000e+00]]
hotdog:100.0%
flower:3.718517166109849e-26%
dinosaur:0.0%
[[0.0000000e+00 3.4181737e-31 1.0000000e+00]]
hotdog:100.0%
flower:3.4181737082787074e-29%
dinosaur:0.0%
[[0.00111238 0.9988876 0. ]]
flower:99.88875985145569%
dinosaur:0.11123800650238991%
hotdog:0.0%
[[2.6787177e-06 9.9999738e-01 0.0000000e+00]]
flower:99.99973773956299%
dinosaur:0.00026787176921061473%
hotdog:0.0%
[[0.00721908 0.992781 0. ]]
flower:99.27809834480286%
dinosaur:0.7219081744551659%
hotdog:0.0%
[[2.2203972e-06 9.9999774e-01 0.0000000e+00]]
flower:99.99977350234985%
dinosaur:0.00022203971639100928%
hotdog:0.0%
可以看到命中率是非常高的,而且无论是否分类成功,首选分类都是接近100%,感觉还是有点overfitting了。
二、从H5格式转换为tflite模式
嘉楠K510只支持kmodel格式,而kmodel格式似乎只能从tflite模式转换而成。所以需要两级转换,先将H5模型转换为tflite模型,再从tflite模型转换为kmodel模型。
TensorFlow的v1版本很容易实现转换,所以在python中调用v1兼容模式即可。四行代码完成模型转换:
import tensorflow as tf
converter=tf.compat.v1.lite.TFLiteConverter.from_keras_model_file("model_ex-019_acc-0.744914_loss-0.569983.h5")
tflite_model=converter.convert()
open("converted_model.tflite","wb").write(tflite_model)
原始模型“model_ex-019_acc-0.744914_loss-0.569983.h5”大概有17.4Mb,转换后的模型“converted_model.tflite”只有5.79Mb。
继续在电脑上验证“converted_model.tflite”模型,可以看到效果和上一节完全一致。
使用tflite.py
(1.59 KB, 下载次数: 0)
三、将tflite模型转换为kmodel格式
这个需要ncc工具实现,目前最新版本是1.8,虽然已经根据例程写了代码,但执行错误,
File "C:\K510test\tcn.py", line 30, in main
compiler = nncase.Compiler(compile_options)
于是还是用较早的版本ncc 0.2进行转换的(号称是k210的,不确定k510能否使用),比较小,只有一个ncc的可执行文件。
ncc.exe
(12.35 MB, 下载次数: 1)
命令行:
ncc.exe compile converted_model.tflite file.kmodel -i tflite -o kmodel --dataset data
这里为什么要带上dataset我不太明白,而且我尝试过修改数据集中的图片数量不同,但生成的文件大小还是相同的5.47Mb(md5效验值不同,说明每次生成的文件有区别)。
|