[ESP32]:TFLite Micro推理CIFAR10模型

2024-04-27 23:04

本文主要是介绍[ESP32]:TFLite Micro推理CIFAR10模型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

[ESP32]:TFLite Micro推理CIFAR10模型

模型训练

数据集处理

from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential, load_model, Model
from keras.layers import Input, Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D, GlobalAveragePooling2D
import pandas as pd
import matplotlib.pyplot as plt
import time, pickle
from keras.utils import to_categorical
from keras import layers
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping(x_train, y_train), (x_test, y_test) = cifar10.load_data()y_train = y_train.reshape(y_train.shape[0])
y_test = y_test.reshape(y_test.shape[0])print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'training samples')
print(x_test.shape[0], 'validation samples')x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)

模型搭建

def build_model():model = tf.keras.Sequential()model.add(layers.Conv2D(32, kernel_size=(4,4), strides=1,activation='relu', input_shape=(32, 32, 3)))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Conv2D(32, kernel_size=(4,4), strides=1,activation='relu'))model.add(layers.MaxPooling2D((2, 2)))model.add(layers.Flatten())model.add(layers.Dense(256, activation='relu'))model.add(layers.Dense(10, activation='softmax'))print(model.summary())return modelmodel=build_model()

tflite模型转换


converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
open("cifar10.tflite", "wb").write(tflite_model)

ESP32推理

本文采用的是2DCNN,添加所需的op算子即可

static tflite::MicroMutableOpResolver<5> resolver;
// 这里需要添加我们模型使用的层
if (resolver.AddReshape() != kTfLiteOk)
{ESP_LOGI(TAG, "Add reshape failed");return;
}if (resolver.AddConv2D() != kTfLiteOk)
{ESP_LOGI(TAG, "Add reshape failed");return;
}if (resolver.AddMaxPool2D() != kTfLiteOk)
{ESP_LOGI(TAG, "Add reshape failed");return;
}if (resolver.AddFullyConnected() != kTfLiteOk)
{ESP_LOGI(TAG, "Add reshape failed");return;
}if (resolver.AddSoftmax() != kTfLiteOk)
{ESP_LOGI(TAG, "Add reshape failed");return;
}

推理方案1:PC端JPG图片转换为数组

每一个像素点都有RGB三个数值,依次排开即可,以下为python的一段实例

from PIL import Image
import numpy as npdef image_to_c_array(image_path):# 读取图片image = Image.open(image_path)print(image.size)# 转换为numpy数组image_array = np.array(image)# 归一化# normalized_image_array = image_array / 255.0print(image_array.size)x_array_flatten = image_array.flatten()print(len(x_array_flatten))c_array_string = "{" + ", ".join(str(pixel) for pixel in x_array_flatten) + "}"with open("image_array.h", "w") as f:f.write("#ifndef IMAGE_ARRAY_H\n")f.write("#define IMAGE_ARRAY_H\n\n")f.write("const float image_array[] = %s;\n" % c_array_string)f.write("#endif\n")# 调用函数生成.h文件
image_to_c_array("0042.jpg")

在这里插入图片描述

这样,我们可以直接将这个数组作为模型的输入去推理,记得归一化,除以255。

推理方案2:esp_jpeg解码jpg

size_t pic_buf_size = 32 * 32 * sizeof(uint32_t);uint8_t *pic_buf = (uint8_t *)heap_caps_malloc(pic_buf_size + 1, MALLOC_CAP_SPIRAM); // create out image bufferesp_jpeg_image_cfg_t jpeg_cfg = {.indata = (uint8_t *)file_buf,.indata_size = filesize,.outbuf = (uint8_t *)pic_buf,.outbuf_size = pic_buf_size,.out_format = JPEG_IMAGE_FORMAT_RGB888,.out_scale = JPEG_IMAGE_SCALE_0,};// // decode jpgesp_jpeg_image_output_t outimage;esp_jpeg_decode(&jpeg_cfg, &outimage);ESP_LOGI(TAG, "%s size: %d x %d", filename, outimage.width, outimage.height);

和上面python版本的一样,解码出来的pic_buf存放的也是每一个的像素,类似于这样

pic_buf[]= {像素0的R,像素0的G,像素0的B,像素1的R....}

所以在输入网络的时候,pic_buf的长度一定是图像宽图像高3,其中3为RGB,包括解码的时候选择RGB888

推理端的代码,记得归一化。

void cifar10_model_predict(const uint8_t *pic, int size)
{for (int i = 0; i < size; i++){input->data.f[i] = pic[i] / 255.0f;}TfLiteStatus invoke_status = interpreter->Invoke();if (invoke_status != kTfLiteOk){MicroPrintf("Invoke failed on");return;}for (int i = 0; i < 10; i++){printf("%.2f ", output->data.f[i]);}printf("\n");
}
LiteOk){MicroPrintf("Invoke failed on");return;}for (int i = 0; i < 10; i++){printf("%.2f ", output->data.f[i]);}printf("\n");
}

可以看到推理结果还是挺不错的。
在这里插入图片描述

这篇关于[ESP32]:TFLite Micro推理CIFAR10模型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/941734

相关文章

0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型的操作流程

《0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeekR1模型的操作流程》DeepSeekR1模型凭借其强大的自然语言处理能力,在未来具有广阔的应用前景,有望在多个领域发... 目录0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型,3步搞定一个应

Deepseek R1模型本地化部署+API接口调用详细教程(释放AI生产力)

《DeepseekR1模型本地化部署+API接口调用详细教程(释放AI生产力)》本文介绍了本地部署DeepSeekR1模型和通过API调用将其集成到VSCode中的过程,作者详细步骤展示了如何下载和... 目录前言一、deepseek R1模型与chatGPT o1系列模型对比二、本地部署步骤1.安装oll

Spring AI Alibaba接入大模型时的依赖问题小结

《SpringAIAlibaba接入大模型时的依赖问题小结》文章介绍了如何在pom.xml文件中配置SpringAIAlibaba依赖,并提供了一个示例pom.xml文件,同时,建议将Maven仓... 目录(一)pom.XML文件:(二)application.yml配置文件(一)pom.xml文件:首

如何在本地部署 DeepSeek Janus Pro 文生图大模型

《如何在本地部署DeepSeekJanusPro文生图大模型》DeepSeekJanusPro模型在本地成功部署,支持图片理解和文生图功能,通过Gradio界面进行交互,展示了其强大的多模态处... 目录什么是 Janus Pro1. 安装 conda2. 创建 python 虚拟环境3. 克隆 janus

本地私有化部署DeepSeek模型的详细教程

《本地私有化部署DeepSeek模型的详细教程》DeepSeek模型是一种强大的语言模型,本地私有化部署可以让用户在自己的环境中安全、高效地使用该模型,避免数据传输到外部带来的安全风险,同时也能根据自... 目录一、引言二、环境准备(一)硬件要求(二)软件要求(三)创建虚拟环境三、安装依赖库四、获取 Dee

DeepSeek模型本地部署的详细教程

《DeepSeek模型本地部署的详细教程》DeepSeek作为一款开源且性能强大的大语言模型,提供了灵活的本地部署方案,让用户能够在本地环境中高效运行模型,同时保护数据隐私,在本地成功部署DeepSe... 目录一、环境准备(一)硬件需求(二)软件依赖二、安装Ollama三、下载并部署DeepSeek模型选

Golang的CSP模型简介(最新推荐)

《Golang的CSP模型简介(最新推荐)》Golang采用了CSP(CommunicatingSequentialProcesses,通信顺序进程)并发模型,通过goroutine和channe... 目录前言一、介绍1. 什么是 CSP 模型2. Goroutine3. Channel4. Channe

Python基于火山引擎豆包大模型搭建QQ机器人详细教程(2024年最新)

《Python基于火山引擎豆包大模型搭建QQ机器人详细教程(2024年最新)》:本文主要介绍Python基于火山引擎豆包大模型搭建QQ机器人详细的相关资料,包括开通模型、配置APIKEY鉴权和SD... 目录豆包大模型概述开通模型付费安装 SDK 环境配置 API KEY 鉴权Ark 模型接口Prompt

大模型研发全揭秘:客服工单数据标注的完整攻略

在人工智能(AI)领域,数据标注是模型训练过程中至关重要的一步。无论你是新手还是有经验的从业者,掌握数据标注的技术细节和常见问题的解决方案都能为你的AI项目增添不少价值。在电信运营商的客服系统中,工单数据是客户问题和解决方案的重要记录。通过对这些工单数据进行有效标注,不仅能够帮助提升客服自动化系统的智能化水平,还能优化客户服务流程,提高客户满意度。本文将详细介绍如何在电信运营商客服工单的背景下进行

Andrej Karpathy最新采访:认知核心模型10亿参数就够了,AI会打破教育不公的僵局

夕小瑶科技说 原创  作者 | 海野 AI圈子的红人,AI大神Andrej Karpathy,曾是OpenAI联合创始人之一,特斯拉AI总监。上一次的动态是官宣创办一家名为 Eureka Labs 的人工智能+教育公司 ,宣布将长期致力于AI原生教育。 近日,Andrej Karpathy接受了No Priors(投资博客)的采访,与硅谷知名投资人 Sara Guo 和 Elad G