【问题标题】:Keras Model AttributeError: 'str' object has no attribute 'call'Keras Model AttributeError:“str”对象没有属性“call”
【发布时间】:2020-07-11 23:29:01
【问题描述】:

我正在尝试使用以下代码将我的 Keras hdf5 文件转换为 TensorFlow Lite 文件:

import tensorflow as tf

# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model("/content/best_model_11class.hdf5")
tflite_model = converter.convert()

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

我在from_keras_model 行收到此错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-14-26467c686751> in <module>()
      2 
      3 # Convert the model.
----> 4 converter = tf.lite.TFLiteConverter.from_keras_model("/content/best_model_11class.hdf5")
      5 tflite_model = converter.convert()
      6 

/usr/local/lib/python3.6/dist-packages/tensorflow/lite/python/lite.py in from_keras_model(cls, model)
    426     # to None.
    427     # Once we have better support for dynamic shapes, we can remove this.
--> 428     if not isinstance(model.call, _def_function.Function):
    429       # Pass `keep_original_batch_size=True` will ensure that we get an input
    430       # signature including the batch dimension specified by the user.

AttributeError: 'str' object has no attribute 'call'

我该如何解决这个问题?顺便说一句,我正在使用 Google Colab。

【问题讨论】:

    标签: python-3.x keras tensorflow2.0 tf.keras tensorflow-lite


    【解决方案1】:

    我不确定 Colab 上的东西是如何工作的,但是查看 tf.lite.TFLiteConverter.from_keras_model 的文档我可以看到它需要一个 Keras 模型实例作为参数,但你给它一个字符串。也许你需要先load the Keras model

    类似:

    keras_model = tf.keras.models.load_model("/content/best_model_11class.hdf5")
    converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
    

    【讨论】:

    • 当我现在运行它时,我得到ValueError: None is only supported in the 1st dimension. Tensor 'input_1' has invalid shape '[None, None, None, 3]'.tfmodel = converter.convert()
    【解决方案2】:
    import tensorflow as tf
    model=tf.keras.models.load_model(""/content/best_model_11class.hdf5"")
    converter = tf.lite.TFLiteConverter.from_keras_model(model)
    converter.experimental_new_converter = True
    tflite_model = converter.convert()
    open("converted_model.tflite", "wb").write(tflite_model) 
    

    这符合https://github.com/tensorflow/tensorflow/issues/32693

    【讨论】:

      【解决方案3】:

      当您不小心尝试仅加载已保存模型的权重而不是完全加载模型时,也会出现此错误。

      例如,使用ModelCheckpoint()save_weights_only = True 时可能会发生这种情况,此时只保存权重而不保存其他模型元数据,因此会出现同样的错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-10
        • 2021-10-04
        • 2019-12-02
        • 2021-09-25
        • 2014-03-04
        相关资源
        最近更新 更多