Tensorflow - keras model.save()引发NotImplementedError

Eva*_*Gao 10 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)
Run Code Online (Sandbox Code Playgroud)

当我试图保存模型时

model.save('epic_num_reader.model')
Run Code Online (Sandbox Code Playgroud)

我得到一个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.
Run Code Online (Sandbox Code Playgroud)

那么如何保存代码中定义的模型呢?

Mat*_*gro 12

您忘记了input_shape第一层定义中的参数,这使得模型未定义,并且尚未实现保存未定义模型,这会触发错误.

model.add(tf.keras.layers.Flatten(input_shape = (my, input, shape)))
Run Code Online (Sandbox Code Playgroud)

只需添加input_shape到第一层,它应该工作正常.

  • @Matias.非常感谢你的回复.我试过`model.add(tf.keras.layers.Flatten(input_shape = x_train [0] .shape))`,然后就可以了. (3认同)