将 TensorFlow Keras python 模型转换为 Android .tflite 模型
Convert TensorFlow Keras python model to Android .tflite model
我正在使用 TensorFlow
和 Keras
进行图像识别项目,我想将其应用到我的 Android 项目中。我是 Tensorflow 的新手...
我想找到图像与包含 +2000 张图像的文件夹之间最接近的匹配项。图片的背景和大小都相似,如下所示:
现在我有以下 Python 代码可以正常工作。
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input
from tensorflow.keras.models import Model
import numpy as np
from PIL import Image
base_model = VGG16(weights='imagenet')
model = Model(inputs=base_model.input, outputs=base_model.get_layer('fc1').output)
def extract(img):
img = img.resize((224, 224)) # Resize the image
img = img.convert('RGB') # Convert the image color space
x = image.img_to_array(img) # Reformat the image
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
feature = model.predict(x)[0] # Extract Features
return feature / np.linalg.norm(feature)
# Iterate through images and extract Features
images = ["img1.png","img2.png","img3.png","img4.png","img5.png"...+2000 more]
all_features = np.zeros(shape=(len(images),4096))
for i in range(len(images)):
feature = extract(img=Image.open(images[i]))
all_features[i] = np.array(feature)
# Match image
query = extract(img=Image.open("image_to_match.png")) # Extract its features
dists = np.linalg.norm(all_features - query, axis=1) # Calculate the similarity (distance) between images
ids = np.argsort(dists)[:5] # Extract 5 images that have lowest distance
现在我有点不知道从这里去哪里了。据我了解,我需要创建一个包含所有提取图像特征的 .h5 文件和一个包含模型的 .tflite 文件。
回答后更新
我可以转换模型:
# Convert the model.
base_model = VGG16(weights='imagenet')
model = Model(inputs=base_model.input, outputs=base_model.get_layer('fc1').output)
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
但是我怎样才能将提取的特征应用到我的 Android 项目中呢?此外,模型的文件大小为 +400 MB,因此 Android 不允许导入它。
希望你能帮助我,谢谢。
# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
请查看下图,以便更好地理解转换过程。 TensorFlow Lite 转换器采用 tensorflow/keras 模型并生成 tensoflow lite (.tflite) 模型。即使有一个转换模型的命令行方式 (https://www.tensorflow.org/lite/convert/index#cmdline),你也被推荐使用 Python API 来做同样的事情,因为它允许添加元数据(如果需要的话)并对模型应用优化。以下步骤可让您将 keras 模型转换为 tflite。
# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
很多时候当你处理更大的模型时,你的模型尺寸会比允许的尺寸大很多,并且可能无法达到你想要的效果。所以你已经应用优化来使模型工作。这是使用 tf.lite.Optimize 完成的。它允许您在 tensorflow 允许大量手动控制之前优化模型的速度、存储等,您可以在使用 tf.lite.Optimize.OPTIMIZE_FOR_LATENCY 或 [=54= 时指定需要优化的内容].OPTIMIZE_FOR_SIZE 如今,这两种优化都是默认设置。现在转换代码变成这样了
# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT] #optimization
tflite_quant_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_quant_model)
这是动态范围量化。完成此步骤后检查模型的尺寸。
如果您想进一步量化模型,例如将所有 float32 转换为 float16,这会将模型大小减小到大约。尺寸为原始尺寸的一半,您可以指定目标规格。那么您的代码将如下所示。 (理解这会影响模型精度)
# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT] #optimization
converter.target_spec.supported_types = [tf.float16] #target spec
tflite_fp16_model = converter.convert()
tflite_model_fp16_file = tflite_models_dir/"model_quant_f16.tflite"
tflite_model_fp16_file.write_bytes(tflite_fp16_model)
还有其他类型的 post 训练量化,您可以在此页面中找到。
https://www.tensorflow.org/lite/performance/post_training_quantization
所有这些都是post训练量化,你也可以在这之前量化模型。同样参考这个link,你也可以通过搜索找到很多教程https://www.tensorflow.org/api_docs/python/tf/quantization/
在此之后,您将必须 运行 这些 tflite 模型以使用 python 测试它们。
步骤如下
- 将模型加载到解释器上。
- 使用示例图像测试模型
- 评估模型
您可以在此页面上找到详细示例
https://www.tensorflow.org/lite/performance/post_training_float16_quant
根据所需的精度和您要使用的边缘设备类型,还有许多其他类型的量化。有关如何将它们应用到您的模型的详细信息,请参阅下面的 link。
https://www.tensorflow.org/lite/performance/model_optimization.
量化后检查你的模型大小,这应该将模型大小减小到所需的值,如果不重复操作会降低精度。
您有 2 个选择:
-
import tensorflow as tf
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_quant_model = converter.convert()
-
TensorFlow Lite 使您能够通过使用选择性构建 (Mobilenet) 来减少模型二进制文件的大小。它说:
Selective builds skip unused operations in your model set and produce
a compact library with just the runtime and the op kernels required
for the model to run on your mobile device.
我正在使用 TensorFlow
和 Keras
进行图像识别项目,我想将其应用到我的 Android 项目中。我是 Tensorflow 的新手...
我想找到图像与包含 +2000 张图像的文件夹之间最接近的匹配项。图片的背景和大小都相似,如下所示:
现在我有以下 Python 代码可以正常工作。
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input
from tensorflow.keras.models import Model
import numpy as np
from PIL import Image
base_model = VGG16(weights='imagenet')
model = Model(inputs=base_model.input, outputs=base_model.get_layer('fc1').output)
def extract(img):
img = img.resize((224, 224)) # Resize the image
img = img.convert('RGB') # Convert the image color space
x = image.img_to_array(img) # Reformat the image
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
feature = model.predict(x)[0] # Extract Features
return feature / np.linalg.norm(feature)
# Iterate through images and extract Features
images = ["img1.png","img2.png","img3.png","img4.png","img5.png"...+2000 more]
all_features = np.zeros(shape=(len(images),4096))
for i in range(len(images)):
feature = extract(img=Image.open(images[i]))
all_features[i] = np.array(feature)
# Match image
query = extract(img=Image.open("image_to_match.png")) # Extract its features
dists = np.linalg.norm(all_features - query, axis=1) # Calculate the similarity (distance) between images
ids = np.argsort(dists)[:5] # Extract 5 images that have lowest distance
现在我有点不知道从这里去哪里了。据我了解,我需要创建一个包含所有提取图像特征的 .h5 文件和一个包含模型的 .tflite 文件。
回答后更新
我可以转换模型:
# Convert the model.
base_model = VGG16(weights='imagenet')
model = Model(inputs=base_model.input, outputs=base_model.get_layer('fc1').output)
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
但是我怎样才能将提取的特征应用到我的 Android 项目中呢?此外,模型的文件大小为 +400 MB,因此 Android 不允许导入它。
希望你能帮助我,谢谢。
# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
请查看下图,以便更好地理解转换过程。 TensorFlow Lite 转换器采用 tensorflow/keras 模型并生成 tensoflow lite (.tflite) 模型。即使有一个转换模型的命令行方式 (https://www.tensorflow.org/lite/convert/index#cmdline),你也被推荐使用 Python API 来做同样的事情,因为它允许添加元数据(如果需要的话)并对模型应用优化。以下步骤可让您将 keras 模型转换为 tflite。
# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
很多时候当你处理更大的模型时,你的模型尺寸会比允许的尺寸大很多,并且可能无法达到你想要的效果。所以你已经应用优化来使模型工作。这是使用 tf.lite.Optimize 完成的。它允许您在 tensorflow 允许大量手动控制之前优化模型的速度、存储等,您可以在使用 tf.lite.Optimize.OPTIMIZE_FOR_LATENCY 或 [=54= 时指定需要优化的内容].OPTIMIZE_FOR_SIZE 如今,这两种优化都是默认设置。现在转换代码变成这样了
# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT] #optimization
tflite_quant_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_quant_model)
这是动态范围量化。完成此步骤后检查模型的尺寸。
如果您想进一步量化模型,例如将所有 float32 转换为 float16,这会将模型大小减小到大约。尺寸为原始尺寸的一半,您可以指定目标规格。那么您的代码将如下所示。 (理解这会影响模型精度)
# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT] #optimization
converter.target_spec.supported_types = [tf.float16] #target spec
tflite_fp16_model = converter.convert()
tflite_model_fp16_file = tflite_models_dir/"model_quant_f16.tflite"
tflite_model_fp16_file.write_bytes(tflite_fp16_model)
还有其他类型的 post 训练量化,您可以在此页面中找到。
https://www.tensorflow.org/lite/performance/post_training_quantization
所有这些都是post训练量化,你也可以在这之前量化模型。同样参考这个link,你也可以通过搜索找到很多教程https://www.tensorflow.org/api_docs/python/tf/quantization/
在此之后,您将必须 运行 这些 tflite 模型以使用 python 测试它们。
步骤如下
- 将模型加载到解释器上。
- 使用示例图像测试模型
- 评估模型
您可以在此页面上找到详细示例 https://www.tensorflow.org/lite/performance/post_training_float16_quant
根据所需的精度和您要使用的边缘设备类型,还有许多其他类型的量化。有关如何将它们应用到您的模型的详细信息,请参阅下面的 link。
https://www.tensorflow.org/lite/performance/model_optimization.
量化后检查你的模型大小,这应该将模型大小减小到所需的值,如果不重复操作会降低精度。
您有 2 个选择:
-
import tensorflow as tf converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir) converter.optimizations = [tf.lite.Optimize.DEFAULT] tflite_quant_model = converter.convert()
TensorFlow Lite 使您能够通过使用选择性构建 (Mobilenet) 来减少模型二进制文件的大小。它说:
Selective builds skip unused operations in your model set and produce a compact library with just the runtime and the op kernels required for the model to run on your mobile device.