justnoxx
justnoxx

Reputation: 165

Export Keras model to SavedModel format

I have issues with saving a sequential model produced by Keras to SavedModel format.

As been said in https://www.tensorflow.org/guide/keras/save_and_serialize#export_to_savedmodel , to save the Keras model to the format that could be used by TensorFlow, I need to use model.save() and provide save_format='tf', but what I have is:

Traceback (most recent call last):
  File "load_file2.py", line 14, in <module>
    classifier.save('/tmp/keras-model.pb', save_format='tf')

My code example is:

import pandas as pd
import tensorflow as tf;
import keras;
from keras import Sequential
from keras.layers import Dense
import json;
import numpy as np;

classifier = Sequential()
classifier.add(Dense(4, activation='relu', kernel_initializer='random_normal', input_dim=4))
classifier.add(Dense(1, activation='sigmoid', kernel_initializer='random_normal'))
classifier.compile(optimizer ='adam',loss='binary_crossentropy', metrics = ['accuracy'])

classifier.save('/tmp/keras-model.pb', save_format='tf')

My python is 3.6.10.

My tensorflow is 1.14 and 2.0 (I tested on both, my result is the same).

My keras is 2.3.1.

What is wrong there or what should I change to make my model saved and then used by tensorflow?

Or, maybe, there is another way of saving models from Keras with TensorFlow2 as backend?

Thanks.

Upvotes: 2

Views: 2480

Answers (1)

sreagm
sreagm

Reputation: 378

I ran your code. With tensorflow 1.15 I got type error saying save_format is not a known parameter. With tensorflow 2 I got the suggesstion to use tf.keras instead of native keras. So, I tried tf.keras instead of keras. This time the code ran with no error. Also, I don't see a fit method before saving the model.

With TF2.0:

import pandas as pd
import tensorflow as tf;
##Change.
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
import json;
import numpy as np;

classifier = Sequential()
classifier.add(Dense(4, activation='relu', kernel_initializer='random_normal', input_dim=4))
classifier.add(Dense(1, activation='sigmoid', kernel_initializer='random_normal'))
classifier.compile(optimizer ='adam',loss='binary_crossentropy', metrics = ['accuracy'])

classifier.save('/tmp/keras-model.pb', save_format='tf')

Result:

INFO:tensorflow:Assets written to: /tmp/keras-model.pb/assets

Upvotes: 3

Related Questions