【问题标题】:Converting saved_model to TFLite model using TF 2.0使用 TF 2.0 将 saved_model 转换为 TFLite 模型
【发布时间】:2020-04-27 23:36:37
【问题描述】:

目前我正在将自定义对象检测模型(使用 SSD 和初始网络训练)转换为量化的 TFLite 模型。我可以使用以下代码 sn-p(使用 Tensorflow 1.4)将自定义对象检测模型从冻结图转换为量化的 TFLite 模型:

converter = tf.lite.TFLiteConverter.from_frozen_graph(args["model"],input_shapes = {'normalized_input_image_tensor':[1,300,300,3]},
input_arrays = ['normalized_input_image_tensor'],output_arrays = ['TFLite_Detection_PostProcess','TFLite_Detection_PostProcess:1',
'TFLite_Detection_PostProcess:2','TFLite_Detection_PostProcess:3'])

converter.allow_custom_ops=True
converter.post_training_quantize=True 
tflite_model = converter.convert()
open(args["output"], "wb").write(tflite_model)

但是tf.lite.TFLiteConverter.from_frozen_graph 类方法不适用于 Tensorflow 2.0 (refer this link)。所以我尝试使用tf.lite.TFLiteConverter.from_saved_model 类方法转换模型。代码sn-p如下所示:

converter = tf.lite.TFLiteConverter.from_saved_model("/content/") # Path to saved_model directory
converter.optimizations =  [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()

上面的代码sn -p抛出如下错误:

ValueError: None is only supported in the 1st dimension. Tensor 'image_tensor' has invalid shape '[None, None, None, 3]'.

我尝试将input_shapes 作为参数传递

converter = tf.lite.TFLiteConverter.from_saved_model("/content/",input_shapes={"image_tensor" : [1,300,300,3]})

但它会引发以下错误:

TypeError: from_saved_model() got an unexpected keyword argument 'input_shapes'

我错过了什么吗?请随时纠正我!

【问题讨论】:

  • TFLiteConverter.from_saved_model 没有参数input_shapes。关键是您是否使用 tensorflow2 创建了您的 saved_model ?
  • 嗨,我已经使用 tensorflow 1.4 创建了模型。我在github上提出了这个问题:github.com/tensorflow/tensorflow/issues/35736
  • 我是否必须将tensorflow1模型转换为tensorflow2模型,然后再转换为tflite模型?
  • 我认为如果你用 tensorflow2 重新加载模型,你可以改变 input_shape 签名——虽然我还没有测试过
  • @edkeveked 我得到了解决方案并添加了参考。谢谢!

标签: python tensorflow tensorflow2.0 tensorflow-lite


【解决方案1】:

我使用tf.compat.v1.lite.TFLiteConverter.from_frozen_graph 得到了解决方案。这个compat.v1 将TF1.x 的功能带入TF2.x。 以下是完整代码:

converter = tf.compat.v1.lite.TFLiteConverter.from_frozen_graph("/content/tflite_graph.pb",input_shapes = {'normalized_input_image_tensor':[1,300,300,3]},
    input_arrays = ['normalized_input_image_tensor'],output_arrays = ['TFLite_Detection_PostProcess','TFLite_Detection_PostProcess:1',
    'TFLite_Detection_PostProcess:2','TFLite_Detection_PostProcess:3'])

converter.allow_custom_ops=True

# Convert the model to quantized TFLite model.
converter.optimizations =  [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()


# Write a model using the following line
open("/content/uno_mobilenetV2.tflite", "wb").write(tflite_model)

【讨论】:

    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多