I encountered the following issue when trying to export a Keras model as a TensorFlow Estimator with the purpose of serving the model. Since the same problem also popped up in an answer to this question, I will illustrate what happens on a toy example and provide my workaround solution for documentation purposes. This behaviour occurs with Tensorflow 1.12.0 and Keras 2.2.4. This happens with actual Keras as well as with tf.keras
.
The problem occurs when trying to export an Estimator that was created from a Keras model with tf.keras.estimator.model_to_estimator
. Upon calling estimator.export_savedmodel
, either a NotFoundError
or a ValueError
is thrown.
The below code reproduces this for a toy example.
Create a Keras model and save it:
import keras
model = keras.Sequential()
model.add(keras.layers.Dense(units=1,
activation='sigmoid',
input_shape=(10, )))
model.compile(loss='binary_crossentropy', optimizer='sgd')
model.save('./model.h5')
Next, convert the model to an estimator with tf.keras.estimator.model_to_estimator
, add an input receiver function and export it in the Savedmodel
format with estimator.export_savedmodel
:
# Convert keras model to TF estimator
tf_files_path = './tf'
estimator =
tf.keras.estimator.model_to_estimator(keras_model=model,
model_dir=tf_files_path)
def serving_input_receiver_fn():
return tf.estimator.export.build_raw_serving_input_receiver_fn(
{model.input_names[0]: tf.placeholder(tf.float32, shape=[None, 10])})
# Export the estimator
export_path = './export'
estimator.export_savedmodel(
export_path,
serving_input_receiver_fn=serving_input_receiver_fn())
This will throw:
ValueError: Couldn't find trained model at ./tf.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…