【问题标题】:Issue in converting Keras H5 model tflite转换 Keras H5 模型 tflite 的问题
【发布时间】:2021-12-09 17:54:23
【问题描述】:
converter = tf.lite.TFLiteConverter.from_keras_model( './signet.h5')
tflite_model = converter.convert()
with open('model.tflite', 'wb') as f:
  f.write(tflite_model)

AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_2464/3288577076.py in <module>
      1 converter = tf.lite.TFLiteConverter.from_keras_model( './signet.h5')
----> 2 tflite_model = converter.convert()
      3 # Save the model.
      4 with open('model.tflite', 'wb') as f:
      5   f.write(tflite_model)

~\anaconda3\envs\tensorflow\lib\site-packages\tensorflow\lite\python\lite.py in convert(self)
    795     # to None.
    796     # Once we have better support for dynamic shapes, we can remove this.
--> 797     if not isinstance(self._keras_model.call, _def_function.Function):
    798       # Pass `keep_original_batch_size=True` will ensure that we get an input
    799       # signature including the batch dimension specified by the user.

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

我正在尝试将 h5 keras 模型转换为 tflite 以用于反应本机应用程序,但显示此错误。 我在论坛上尝试了一些解决方案,其中一个在 github 上,但没有奏效。 有没有办法将我的 h5 模型转换为 tflite。

【问题讨论】:

    标签: python tensorflow keras deep-learning tensorflow-lite


    【解决方案1】:

    您应该将实际的 Keras 模型对象传递给转换器的 `from_keras_model 方法 :-)。见例子:

    import tensorflow as tf
    
    # Create a model using high-level tf.keras.* APIs
    model = tf.keras.models.Sequential([
        tf.keras.layers.Dense(units=1, input_shape=[1]),
        tf.keras.layers.Dense(units=16, activation='relu'),
        tf.keras.layers.Dense(units=1)
    ])
    model.compile(optimizer='sgd', loss='mean_squared_error') # compile the model
    model.fit(x=[-1, 0, 1], y=[-3, -1, 1], epochs=5) # train the model
    # (to generate a SavedModel) tf.saved_model.save(model, "saved_model_keras_dir")
    
    # 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)
    

    所以你首先需要从 H5 文件中加载。

    【讨论】:

      猜你喜欢
      • 2020-09-10
      • 2019-06-10
      • 2020-10-10
      • 1970-01-01
      • 2019-04-14
      • 2019-08-04
      • 2019-09-05
      • 2022-06-30
      • 1970-01-01
      相关资源
      最近更新 更多