tflite 学习——生成.tflite 模型与验证

用Resnet 模型进行验证

Step 1 导入resnet 50模型 

import numpy as np
import tensorflow as tf



physical_devices = tf.config.list_physical_devices('GPU')
for device in physical_devices: # 使用GPU 
    tf.config.experimental.set_memory_growth(device, True)

model = tf.keras.applications.resnet50.ResNet50(weights='imagenet') # 导入resnet 模型 
img = tf.keras.utils.load_img('123.jpg', target_size=[224, 224,3])  # 载入图片并给出size 

x = tf.keras.preprocessing.image.img_to_array(img)  # 处理输入图片尺寸 
x = np.expand_dims(x, axis=0)
x = tf.keras.applications.resnet50.preprocess_input(x)


preds = model.predict(x)  # 预测结果 
# 将结果解码为元组列表 (class, description, probability)
# (一个列表代表批次中的一个样本)
print('Predicted:', tf.keras.applications.resnet50.decode_predictions(preds, top=3)[0])








结果: Predicted: [('n03887697', 'paper_towel', 0.71528304), ('n15075141', 'toilet_tissue', 0.16052581), ('n02948072', 'candle', 0.03291733)]

Step 2 存储Resnet 模型为 Savemodel的格式  两种方法

(1)低级API 

存储 tf.saved_model.save (model, path)

这种形式保存以后文件夹是这样的

加载 tf.saved_model.load(path_to_dir)

具体代码如下 

load_model = tf.saved_model.load('resnet50_low_level_save/') # 加载模型
labeling = load_model(x)   # 
imagenet_labels = np.array(open('ImageNetLabels.txt').read().splitlines())  # ImageNetLabels.txt 文件中包含1000个被识别的物体名字列表 和 一个backgroud 所以下面的物体标号是+1 
decoded = imagenet_labels[np.argsort(labeling)[0, ::-1][:3] + 1]
print(decoded)

(2)高级API 

存储  tf.keras.models.save_model(model, path)

这种形式保存以后文件夹是这样的 多了一个keras_metadata.pb的文件 

加载  tf.keras.models.save_model(path_to_dir)

具体代码如下 

tf.keras.models.save_model(model, 'resnet50_high_level_save/')
load_model = tf.keras.models.load_model('resnet50_high_level_save/') # 加载模型
preds = load_model.predict(x)
decoded = imagenet_labels[np.argsort(preds)[0, ::-1][:3] + 1]

这种方法好处在于可以继续使用keras 的方法

Step 3 利用 Savedmodel 生成.tflite模型 

(1) 低级API 

convert = tf.lite.TFLiteConverter.from_saved_model('resnet50_low_level_save')
tflite_model = convert.convert()

tflite_model_file = pathlib.Path('resnet50_low_level.tflite')
tflite_model_file.write_bytes(tflite_model)

(2) 高级API 

convert = tf.lite.TFLiteConverter.from_saved_model('resnet50_high_level_save')
tflite_model = convert.convert()

tflite_model_file = pathlib.Path('resnet50_high_level.tflite')
tflite_model_file.write_bytes(tflite_model)

Step4 .tflite 模型结果验证

(1)低级API 输入图片的处理利用tensorflow 处理 

import numpy as np
import tensorflow as tf

interpreter = tf.lite.Interpreter(model_path="resnet50_low_level.tflite")
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
interpreter.allocate_tensors()
imagenet_labels = np.array(open('ImageNetLabels.txt').read().splitlines())


################################### 输入矩阵处理方式 1 ###################################
img_path = '123.jpg'
print(np.shape(img_path))
img = tf.keras.preprocessing.image.load_img(img_path, target_size=(224, 224, 3))   # 输入矩阵处理方式 1
x = tf.keras.preprocessing.image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = tf.keras.applications.resnet50.preprocess_input(x)


print(np.shape(x))

interpreter.set_tensor(input_details[0]['index'], x)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])

decoded = imagenet_labels[np.argsort(output_data)[0, ::-1][:3] + 1]
print(output_data[:,[np.argsort(output_data)[0, ::-1][:3]]])
print("Result before saving:\n", decoded)

结果 : 

与前面的结果基本一样,所以证明一切正确。

 (2)低级API 输入图片的处理利用Opencv 处理 

import numpy as np
import tensorflow as tf
import cv2
interpreter = tf.lite.Interpreter(model_path="resnet50_low_level.tflite")
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
interpreter.allocate_tensors()
imagenet_labels = np.array(open('ImageNetLabels.txt').read().splitlines())


################################### 输入矩阵处理方式 2 利用Opencv ###################################
img = cv2.imread("123.jpg")
new_img = cv2.resize(img, (224, 224))
new_img = new_img.astype(dtype=np.float32)
# new_img = tf.cast(new_img , dtype=np.float32)
x = np.expand_dims(new_img, axis=0)

print(np.shape(x))

interpreter.set_tensor(input_details[0]['index'], x)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])

decoded = imagenet_labels[np.argsort(output_data)[0, ::-1][:3] + 1]
print(output_data[:,[np.argsort(output_data)[0, ::-1][:3]]])
print("Result before saving:\n", decoded)

 从结果看,Opencv 处理的图片,识别效果更好。

(3)高级API 输入图片的处理利用tensorflow 处理 

只需要把低级API保存的模型,改成高级的。

 

结论保存结果的形式,对于tflite的结果无影响。

(4)高级API 输入图片的处理利用tensorflow 处理 

只需要把低级API保存的模型,改成高级的。

 

### TensorFlow模型转换为TensorFlow Lite的方法教程 将TensorFlow模型转换为TensorFlow LiteTFLite)是一个常见的需求,尤其是在需要在移动设备或嵌入式系统上部署机器学习模型时。以下是关于这一过程的具体方法和注意事项。 #### 1. 使用`tf.lite.TFLiteConverter`进行模型转换 TensorFlow提供了专门用于模型转换的工具——`TFLiteConverter`类。该工具可以根据不同的输入源执行转换操作[^3]。对于Keras模型文件(`.h5`),可以按照以下方式进行处理: ```python import tensorflow as tf # 加载Keras模型 model = tf.keras.models.load_model('path_to_your_model.h5') # 创建TFLite转换器实例 converter = tf.lite.TFLiteConverter.from_keras_model(model) # 执行转换 tflite_model = converter.convert() # 将转换后的模型保存到本地 with open('converted_model.tflite', 'wb') as f: f.write(tflite_model) ``` 上述代码展示了如何加载一个已有的Keras模型并将其转换为TFLite格式。 --- #### 2. 自定义激活函数的支持 如果模型中包含了自定义层或激活函数,则需要通过`CustomObjectScope`来注册这些对象以便于成功完成转换。例如,在实现ReLU6激活函数的情况下,可以通过如下方式解决兼容性问题: ```python from tensorflow.python.keras import backend as K from tensorflow.python.keras.utils import CustomObjectScope def relu6(x): return K.relu(x, max_value=6) # 注册自定义激活函数 with CustomObjectScope({'relu6': relu6}): # 加载带有自定义激活函数的Keras模型 model = tf.keras.models.load_model('custom_model.h5') # 进行TFLite转换 converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert() # 存储转换后的模型 with open('custom_converted_model.tflite', 'wb') as f: f.write(tflite_model) ``` 这段代码说明了当模型依赖特定功能(如ReLU6)时应采取的操作步骤[^2]。 --- #### 3. 验证转换后的模型性能 为了确保转换过程中不会丢失精度或者引入错误行为,建议验证原始TensorFlow模型生成TFLite版本之间的预测一致性。这通常涉及以下几个方面: - **数据准备**:选取一组测试样本。 - **推理比较**:分别利用两种形式的模型计算输出并向量间差异评估其相似度水平。 --- #### 4. 参考Google官方语音命令识别案例 除了基本流程外,还可以参照由谷歌提供的实际应用范例进一步加深理解。比如下面链接中的项目就演示了一个完整的端到端解决方案,其中包括训练音频分类网络以及最终导出轻量化版供安卓客户端调用等功能模块[^4]: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/speech_commands --- #### 总结 综上所述,无论是标准架构还是特殊定制化场景下都可以借助内置API轻松达成目标;此同时也要注意某些特殊情况下的额外配置工作以保障整个迁移链条顺畅无误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值