TensorFlow Lite 是一组工具,可帮助开发者在移动设备、嵌入式设备和 loT 设备上运行模型,以便实现设备端机器学习。
更多请见Tensorflow Lite官网:
https://tensorflow.google.cn/lite/guide?hl=zh-cn
在python中训练模型
具体案例参见这里:
https://github.com/tensorflow/tflite-micro/blob/main/tensorflow/lite/micro/examples/hello_world/train/train_hello_world_model.ipynb
2023年4月11日更新:github tflite example进行了重构,上面链接已失效
将tf模型转化为tflite模型
We'll use the TensorFlow Lite Converter to convert the model into a special, space-efficient format for use on memory-constrained devices.
将模型保存为字节形式
make -f tensorflow/lite/micro/tools/make/Makefile <project_name>_bin
编写C/C++程序将模型导入到设备中,进行运行推断
使用 ESP-IDF
官方首选推荐,有详细的教程说明:
https://github.com/espressif/tflite-micro-esp-examples
使用 PlatformIO
更加适合我们项目的方式
一个简单的神经网络,属于监督学习。
先生成1000组x和对应的y=sin(x),然后对y适当加入噪声,对神经网络进行训练。
训练好后输入x神经网络会输出对应预测的sin(x).
xxx.h not found,编译失败
xxx.h not found的解决方法通常都在platfromio.ini里
此处是对 lib_deps 与 build_flags进行添加依赖项
添加了一个TensorLite sensor,使用串口进行数据读写
下面是一些测试: 输入数据为 0, /2, , 3/2, 2
Running inference on inputted data...
Input: 0.00
Output: 0.01
Running inference on inputted data...
Input: 1.57
Output: 0.94
Running inference on inputted data...
Input: 3.14
Output: -0.04
Running inference on inputted data...
Input: 4.71
Output: -1.00
Running inference on inputted data...
Input: 6.28
Output: -0.05
可以看到神经网络的训练结果是比较好的,预测的sin值有些许误差,在可接受范围内。
本文章使用limfx的vscode插件快速发布