简体   繁体   English

将 Keras 模型权重和架构转换为 TensorFlow Lite 模型

[英]Converting Keras Model Weights and Architecture to TensorFlow Lite Model

I have Keras Model in terms of Model Weights stored in model.h5 and Model Architecture stored in model.json , my aim is to covert these two files that makes up Keras model to tensorflow Lite Model, I have tried several ways but it does not seem to work.我在 model.h5 中存储了模型权重方面的 Keras 模型,在 model.json 中存储了模型架构,我的目标是将构成 Keras 模型的这两个文件转换为 tensorflow Lite 模型,我尝试了几种方法,但没有似乎工作。

When I use Tensoflow 1.15.0 with the following code I get "NameError: name 'lite' is not defined" and when I downgrade to Tensoflow 1.15.0 I get "AttributeError: type object 'TFLiteConverter' has no attribute 'from_keras_model'"当我使用 Tensoflow 1.15.0 和以下代码时,我得到“NameError: name 'lite' is not defined”,当我降级到 Tensoflow 1.15.0 时,我得到“AttributeError: type object 'TFLiteConverter' has no attribute 'from_keras_model'”

can anybody help Thanks in advance!任何人都可以帮助提前谢谢!

#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()

I have the following solution to this problem:我对这个问题有以下解决方案:

update tensorflow to what I am currently using is 2.1.0-rc0将 tensorflow 更新为我目前使用的是 2.1.0-rc0

then instead of然后代替

model = model_from_json(f.read())

Use

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

the whole code would be :整个代码将是:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM