Tensorflow——keras model.save() raise NotImplementedError

Reason For the Error:

I was getting the same error and tried the above answers but got errors. But I find a solution to the problem that I will share below:

Check whether you passed input_shape at the time of defining the input layer of the model if not you will get an error at the time of saving and loading the model.

How to define input_shape?

Lets consider the one example If you use minst dataset:

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

It consists of images of handwritten digits 0-9 of size 28 x 28 resolution each. For this, we can define input shape as (28,28) without mentioning batch size as follows:

model.add(tf.keras.layers.Flatten(input_shape=(28,28)))

In this way, you can give input shape by looking at your input training dataset.

Save your trained model:

Now after training and testing the model we can save our model. Following code worked for me it did not change the accuracy as well after reloading the model:

by using save_model()

import tensorflow as tf    
tf.keras.models.save_model(
    model,
    "your_trained_model.model",
    overwrite=True,
    include_optimizer=True
) 

by using .save()

your_trained_model.save('your_trained_model.model')

del model  # deletes the existing model

Now load the model which we saved :

model2 = tf.keras.models.load_model("your_trained_model.model")

For more details refer to this link: Keras input explanation: input_shape, units, batch_size, dim, etc


You forgot the input_shape argument in the definition of the first layer, which makes the model undefined, and saving undefined models has not been implemented yet, which triggers the error.

model.add(tf.keras.layers.Flatten(input_shape = (my, input, shape)))

Just add the input_shape to the first layer and it should work fine.


For those who still have not solved the problem even did as Matias suggested, you can consider using tf.keras.models.save_model() and load_model(). In my case, it worked.


tf.keras.models.save_model

Works here (tensorflow 1.12.0) (even when the input_shape is unspecified)

Tags:

Python

Keras