Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow——keras model.save() raise NotImplementedError

Tags:

python

keras

import tensorflow as tf 

mnist = tf.keras.datasets.mnist 

(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = tf.keras.utils.normalize(x_train, axis=1)
x_test = tf.keras.utils.normalize(x_test, axis=1)

model = tf.keras.models.Sequential()

model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128,activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(128,activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10,activation=tf.nn.softmax))

model.compile(optimizer ='adam',
            loss='sparse_categorical_crossentropy',
             metrics=['accuracy'])
model.fit(x_train, y_train, epochs=3)

When I tried to save the model

model.save('epic_num_reader.model')

I get a NotImplementedError:

NotImplementedError                       Traceback (most recent call last)
<ipython-input-4-99efa4bdc06e> in <module>()
      1 
----> 2 model.save('epic_num_reader.model')

NotImplementedError: Currently `save` requires model to be a graph network. Consider using `save_weights`, in order to save the weights of the model.

So how can I save the model defined in the code?

like image 601
Evan-Gao Avatar asked Sep 28 '18 10:09

Evan-Gao


2 Answers

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.

like image 178
Frederick Hong Avatar answered Sep 28 '22 06:09

Frederick Hong


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.

like image 25
Dr. Snoopy Avatar answered Sep 28 '22 05:09

Dr. Snoopy