# ESP_TinyML **Repository Path**: yang-shao1/esp_-tiny-ml ## Basic Information - **Project Name**: ESP_TinyML - **Description**: No description available - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2024-07-17 - **Last Updated**: 2025-04-23 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # TinyML ESP Tensorflow Lite Micro ## 介绍 - 这部分主要就是通过生成sinx的数据集,来拟合一条sinx的曲线,然后将这个曲线的点作为模型的输入,来训练一个Tensorflow Lite Micro模型。 ## 首先是模型训练部分 ### 数据集 - 随机生成1000个sinx数据点 得到x 、y的值,打乱数据集顺序 - 取0-600 部分位训练集 - 取600-800 部分位测试集 - 取800-1000 部分位验证集 ### 构建模型 - 4层线性全连接层 - 激活函数使用relu - 损失函数使用均方误差 - 优化器使用rmsprop ### 训练模型 2000次迭代,学习率0.001,batch_size=16 #### 训练后未量化结果对比 ![img.png](img.png) #### 训练后量化结果对比 int8位量化 ![img_1.png](img_1.png) # 大坑!!! - 做int8量化的时候,需要把模型的输入跟输出设置成int8!!!!,否则在部署端做做量化跟反量化的时候会出现问题。 - 会取不到量化的参数 比例因数跟0点偏移量 会默认为0 ,导致整个模型的量化输入不对,量化输出也不对。 - 现象:x y 都会输入输出一个定值 ```python # 翻译:将模型转换为TensorFlow Lite格式,并进行8位的量化,这是量化成8位的过程,可以减少模型大小并提高性能。 # 保证输入跟输出都是int8,因为量化后的模型大小会减小。 converter = tf.lite.TFLiteConverter.from_keras_model(model_1) converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8] converter.inference_input_type = tf.int8 # 如果需要量化 那么这里需要设置为int8 converter.inference_output_type = tf.int8 # 如果需要量化 那么这里需要设置为int8 # 定义一个生成器来提供测试数据x的值,作为代表性数据集,并告诉转换器使用它 def representative_dataset_gen(): for value in x_test: yield [np.array([[value]], dtype=np.float32)] # 这dtepe=np.float32是为了保证输入的数据类型为float32 converter.representative_dataset = representative_dataset_gen tflite_model_quantized = converter.convert() # 转换模型 tflite_model = converter.convert() # 翻译:将量化后的模型保存到磁盘 open("sine_model_quantized_generated.tflite", "wb").write(tflite_model) ```` # ESP端模型推理部分代码 - 可以进行int的量化跟反量化推理,也可以对模型不量化,直接进行float类型的推理 ```C++ // Quantize the input from floating-point to integer int8_t x_quantized = x / input->params.scale + input->params.zero_point; // Place the quantized input in the model's input tensor input->data.int8[0] = x_quantized; // Run inference, and report any error // 翻译:运行推理,并报告任何错误 TfLiteStatus invoke_status = interpreter->Invoke(); if (invoke_status != kTfLiteOk) { TF_LITE_REPORT_ERROR(error_reporter, "Invoke failed on x: %f\n", static_cast(x)); return; } // Obtain the output from model's output tensor // float y = output->data.f[0]; // Obtain the quantized output from model's output tensor int8_t y_quantized = output->data.int8[0]; // Dequantize the output from integer to floating-point float y = (y_quantized - output->params.zero_point) * output->params.scale; ````