【问题标题】:How to convert just a h5 file to a tflite file?如何仅将 h5 文件转换为 tflite 文件?
【发布时间】:2020-12-15 06:50:19
【问题描述】:

我正在尝试在 Android 上运行车牌检测。所以首先我找到了这个教程:https://medium.com/@quangnhatnguyenle/detect-and-recognize-vehicles-license-plate-with-machine-learning-and-python-part-1-detection-795fda47e922 顺便说一句真的很棒。

在教程中,我们可以找到wpod-net.h5,所以我尝试使用以下方法将其转换为 TensorFlow lite:

import tensorflow as tf

model = tf.keras.models.load_model('wpod-net.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.post_training_quantize = True
tflite_model = converter.convert()
open("wpod-net.tflite", "wb").write(tflite_model)

但是当我运行它时,我有这个错误:

  File "converter.py", line 3, in <module>
    model = tf.keras.models.load_model('License_character_recognition.h5')
  File "/home/.local/lib/python3.8/site-packages/tensorflow/python/keras/saving/save.py", line 184, in load_model
    return hdf5_format.load_model_from_hdf5(filepath, custom_objects,
  File "/home/.local/lib/python3.8/site-packages/tensorflow/python/keras/saving/hdf5_format.py", line 175, in load_model_from_hdf5
    raise ValueError('No model found in config file.')
ValueError: No model found in config file.

我也尝试使用 API tflite_convert --keras_model_file=License_character_recognition.h5 --output_file=test.tflite,但它给了我同样的错误。

这是否意味着如果我自己不训练模型,我就无法将其转换为 tflite ?或者还有其他方法可以转换 .h5 吗?

【问题讨论】:

  • 您确定 H5 文件包含模型广告而不仅仅是其权重吗?如果是第二个,您首先需要自己构建模型(与教程中构建的方式相同),然后调用model.load_weights('path_to_your_file.h5')
  • 感谢您的快速回答。我怎么知道文件是否包含模型?
  • 好吧,load_model 失败了,所以我猜它不包含模型。您还可以在教程的代码中搜索该文件的创建位置,并查看他们在那里使用的函数
  • 好的,如果我们只有正确的权重,就不可能转换? wpod-net 来自这里:sergiomsilva.com/pubs/alpr-unconstrained

标签: python keras tensorflow-lite


【解决方案1】:

TensorFlow Lite 模型包含权重和模型代码本身。您需要加载 Keras 模型(带权重),然后您才能转换为 tflite 模型。

获取作者repo 的副本,并执行get-networks.sh。车牌检测器只需要data/lp-detector/wpod-net_update1.h5,这样您就可以提前停止下载。

深入研究一下代码,您可以在 keras utils 找到准备好的负载模型函数。

得到模型对象后,可以将其转换成tflite。

Python3、TF2.4 测试:

import sys, os
import tensorflow as tf
import traceback

from os.path                    import splitext, basename

print(tf.__version__)

mod_path = "data/lp-detector/wpod-net_update1.h5"

def load_model(path,custom_objects={},verbose=0):
    #from tf.keras.models import model_from_json

    path = splitext(path)[0]
    with open('%s.json' % path,'r') as json_file:
        model_json = json_file.read()
    model = tf.keras.models.model_from_json(model_json, custom_objects=custom_objects)
    model.load_weights('%s.h5' % path)
    if verbose: print('Loaded from %s' % path)
    return model

keras_mod = load_model(mod_path)

converter = tf.lite.TFLiteConverter.from_keras_model(keras_mod)
tflite_model = converter.convert()

# Save the TF Lite model.
with tf.io.gfile.GFile('model.tflite', 'wb') as f:
    f.write(tflite_model)

祝你好运!

【讨论】:

  • 非常感谢它也对我有用。我现在明白为什么它以前不起作用了。
猜你喜欢
  • 2019-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-22
  • 2020-10-10
  • 2020-06-09
  • 1970-01-01
  • 2020-04-20
相关资源
最近更新 更多