【问题标题】:Converting Keras Model Weights and Architecture to TensorFlow Lite Model将 Keras 模型权重和架构转换为 TensorFlow Lite 模型
【发布时间】:2019-12-16 09:45:56
【问题描述】:

我有 Keras 模型,模型权重存储在 model.h5 中,模型架构存储在 model.json 中,我的目标是将构成 Keras 模型的这两个文件转换为 tensorflow Lite 模型,我尝试了几种方法,但是它似乎不起作用。

当我使用带有以下代码的 Tensoflow 1.15.0 时,我得到“NameError: name 'lite' is not defined”,当我降级到 Tensoflow 1.15.0 时,我得到 "AttributeError: type object 'TFLiteConverter' 没有属性 'from_keras_model'"

谁能帮忙提前谢谢!

#from tensorflow.contrib import lite 
import tensorflow as tf

from tensorflow.contrib import lite

from keras.models import model_from_json
# Model reconstruction from JSON file
with open('drive/My Drive/Colab Notebooks/model.json', 'r') as f:
    model = model_from_json(f.read())

# Load weights into the new model
model.load_weights('drive/My Drive/Colab Notebooks/model.h5')

# Converting a tf.Keras model to a TensorFlow Lite model.
converter = lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    我对这个问题有以下解决方案:

    将 tensorflow 更新到我目前使用的是 2.1.0-rc0

    然后代替

    model = model_from_json(f.read())
    

    使用

    model = tf.keras.models.model_from_json(f.read())
    

    整个代码是:

    import tensorflow as tf
    
    with open('../input/melanoma-cancer-h5-model/model.json', 'r') as f:
        model = tf.keras.models.model_from_json(f.read())
    
    # Load weights into the new model
    model.load_weights('../input/melanoma-cancer-h5-model/model.h5')
    
    # Convert the model.
    converter = tf.lite.TFLiteConverter.from_keras_model(model)
    tflite_model = converter.convert()
    open("model.tflite","wb").write(tflite_model)
    

    【讨论】:

    • 谢谢!我已经找了一个小时了。
    猜你喜欢
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2019-04-14
    • 1970-01-01
    相关资源
    最近更新 更多