简体   繁体   中英

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.

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'"

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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