TensorFlow Lite开发系列之python接口解析(一)

简介: 环境: tensorflow2.x, 一定要使用linux系统,后期转换模型windows会出现bug

API解析


微信图片_20230203192252.png


常用的就这4个类,常用方法介绍:


# model_path:TF-Lite Flatbuffer文件的路径
# model_content:模型的内容
tf.lite.Interpreter(
    model_path=None, model_content=None, experimental_delegates=None
)


allocate_tensors()   # 加载所有的tensor


get_input_details()  # 获取模型输入详细信息


get_output_details()  # 获取模型输出详细信息


 # 获取输入张量的值(获取副本),该值可以从get_output_details中的“索引”字段中获得
get_tensor( 
    tensor_index
)


get_tensor_details()   # 返回值:包含张量信息的字典列表


invoke()  # 进行推理, 在调用它之前,请确保设置输入大小,分配张量和填充值


# tensor_index:要设置的张量的张量索引。该值可以从get_input_details中的“索引”字段中获得
# value:要设置的张量值
set_tensor(
    tensor_index, value
)


# Converting a SavedModel to a TensorFlow Lite model.
converter = lite.TFLiteConverter.from_saved_model(saved_model_dir)
tflite_model = converter.convert()
# Converting a tf.Keras model to a TensorFlow Lite model.
converter = lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Converting ConcreteFunctions to a TensorFlow Lite model.
converter = lite.TFLiteConverter.from_concrete_functions([func])
tflite_model = converter.convert()


tf.lite.Optimize 
类变量
  DEFAULT
  OPTIMIZE_FOR_LATENCY
  OPTIMIZE_FOR_SIZE


完整例子:


1. 训练一个模型用于后面转换TFLite模型与推理


import tensorflow as tf
from tensorflow import keras
# 读取数据
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = tf.expand_dims(x_train, 3)
y_train = keras.utils.to_categorical(y_train, num_classes=10)
datasets = tf.data.Dataset.from_tensor_slices((x_train, y_train))
datasets = datasets.repeat(1).batch(10)
# 定义模型
img = keras.Input(shape=[28, 28, 1])
x = keras.layers.Conv2D(filters=64, kernel_size=4, strides=1, padding='SAME', activation='relu')(img)
x = keras.layers.AveragePooling2D(pool_size=2, strides=2, padding='SAME')(x)
x = keras.layers.BatchNormalization()(x)
x = keras.layers.Dropout(0.15)(x)
x = keras.layers.Flatten()(x)
x = keras.layers.Dense(512, activation='relu')(x)
y_pred = keras.layers.Dense(10, activation='softmax')(x)
model = keras.Model(inputs=img, outputs=y_pred)
model.compile(optimizer=keras.optimizers.Adam(0.01),
              loss=keras.losses.categorical_crossentropy,
              metrics=['AUC', 'accuracy'])
model.fit(datasets, epochs=1)
model.save('./model.h5')


2. 转换模型


import tensorflow as tf
from tensorflow import keras
model = tf.keras.models.load_model("./model.h5")
model.summary()
converter = tf.lite.TFLiteConverter.from_keras_model(model)  # 生成转化器
tflite_model = converter.convert()  # 进行转换
open('./converted_model.tflite', 'wb').write(tflite_model)  # 写入


3. 推理


import tensorflow as tf
from tensorflow import keras
import numpy as np
interpreter = tf.lite.Interpreter(model_path='./converted_model.tflite')  # 读入并生成interpreter
interpreter.allocate_tensors()  # 加载所有的张量
input_details = interpreter.get_input_details()  # 获取输入的信息
output_details = interpreter.get_output_details()  # 获取输出的信息
# 指定随机数进行预测
input_shape = input_details[0]['shape']
input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
# 指定输入数据
interpreter.set_tensor(input_details[0]['index'], input_data)
# 调用模型进行推理
interpreter.invoke()
# 根据tensor索引取出推理的结果
tflite_result = interpreter.get_tensor(output_details[0]['index'])
目录
相关文章
|
1天前
|
JSON API 数据安全/隐私保护
python小知识-数据验证和解析神器pydantic
Pydantic是一个Python库,用于数据验证和设置管理,基于类型提示提供数据模型验证。它可以用于用户输入验证、JSON序列化和解析,以及API交互中的数据校验。安装Pydantic可使用`pip install -U pydantic`或`conda install pydantic -c conda-forge`。通过定义BaseModel子类并使用Field进行约束,可以创建数据模型并进行验证。例如,定义User模型验证用户名、邮箱和年龄。Pydantic还支持自定义验证器,允许在字段赋值时执行特定逻辑,如密码强度检查和哈希处理。5月更文挑战第19天
12 1
|
1天前
|
API Python
Python实现大麦网抢票的四大关键技术点解析
随着互联网的普及和发展,线上购票已经成为人们生活中不可或缺的一部分。然而,在抢购热门演出门票时,往往会遇到抢票难、抢票快的问题,有时候一秒钟的延迟就意味着与心仪的演出擦肩而过。为了解决这个问题,技术爱好者们开始探索利用Python多线程技术来提高抢票效率。本文将介绍Python实现大麦网抢票的四大关键技术点,帮助读者了解抢票脚本的核心原理,并通过示例代码详细说明实现过程。
|
1天前
|
Python
Python之Math库解析
Python之Math库解析
7 0
Python之Math库解析
|
1天前
|
IDE 开发工具 Python
python中SyntaxError: unexpected EOF while parsing(语法错误:解析时遇到意外的文件结束)
【5月更文挑战第14天】python中SyntaxError: unexpected EOF while parsing(语法错误:解析时遇到意外的文件结束)
19 6
|
2天前
|
人工智能 文字识别 自然语言处理
准确高效的TextIn文档解析:一项开发痛点的解决方案
企业在构建知识库问答系统时面临挑战,尤其是处理扫描文档和手写内容。传统OCR工具和开源方法在准确性和速度上不足。专业长文档解析成为关键,其中TextIn平台的文档解析服务脱颖而出。该服务能快速将PDF转为Markdown,提高处理速度和准确性,尤其适合处理复杂布局的长文档。通过实际测试,TextIn能有效增强LLM问答系统的性能,解决无法正确解析的问题。目前TextIn处于内测阶段,提供每周7000页的免费试用额度,开发者可通过其官网或“合研社”公众号了解更多信息和获取接口文档。
|
2天前
|
缓存 负载均衡 网络协议
使用Go语言开发高性能服务的深度解析
【5月更文挑战第21天】本文深入探讨了使用Go语言开发高性能服务的技巧,强调了Go的并发性能、内存管理和网络编程优势。关键点包括:1) 利用goroutine和channel进行并发处理,通过goroutine池优化资源;2) 注意内存管理,减少不必要的分配和释放,使用pprof分析;3) 使用非阻塞I/O和连接池提升网络性能,结合HTTP/2和负载均衡技术;4) 通过性能分析、代码优化、缓存和压缩等手段进一步提升服务性能。掌握这些技术能帮助开发者构建更高效稳定的服务。
|
3天前
|
Python
2024年最全用Python写了一个电子考勤系统_用python写一个宿舍考勤系统,2024年最新1307页阿里Python面试全套真题解析在互联网火了
2024年最全用Python写了一个电子考勤系统_用python写一个宿舍考勤系统,2024年最新1307页阿里Python面试全套真题解析在互联网火了
|
3天前
|
机器学习/深度学习 人工智能 算法
食物识别系统Python+深度学习人工智能+TensorFlow+卷积神经网络算法模型
食物识别系统采用TensorFlow的ResNet50模型,训练了包含11类食物的数据集,生成高精度H5模型。系统整合Django框架,提供网页平台,用户可上传图片进行食物识别。效果图片展示成功识别各类食物。[查看演示视频、代码及安装指南](https://www.yuque.com/ziwu/yygu3z/yhd6a7vai4o9iuys?singleDoc#)。项目利用深度学习的卷积神经网络(CNN),其局部感受野和权重共享机制适于图像识别,广泛应用于医疗图像分析等领域。示例代码展示了一个使用TensorFlow训练的简单CNN模型,用于MNIST手写数字识别。
18 3
|
5天前
|
存储 Java 程序员
【Python 的内存管理机制专栏】深入解析 Python 的内存管理机制:从变量到垃圾回收
【5月更文挑战第18天】Python内存管理关乎程序性能与稳定性,包括变量存储和垃圾回收。变量存储时,如`x = 10`,`x`指向内存中值的引用。垃圾回收通过引用计数自动回收无引用对象,防止内存泄漏。了解此机制可优化内存使用,避免循环引用等问题,提升程序效率和稳定性。深入学习内存管理对成为优秀Python程序员至关重要。
【Python 的内存管理机制专栏】深入解析 Python 的内存管理机制:从变量到垃圾回收
|
JSON 网络安全 对象存储
python接口自动化(六)--发送get请求接口(详解)
如果想用python做接口测试,我们首先有不得不了解和学习的模块。它就是第三方模块:Requests。 虽然Python内置的urllib模块,用于访问网络资源。但是,它用起来比较麻烦,而且,缺少很多实用的高级功能。更好的方案是使用 requests。
377 1
python接口自动化(六)--发送get请求接口(详解)