Tensorflow / Keras教程保存/加载模型不起作用

时间:2018-10-15 15:28:18

标签: python tensorflow keras

我无法使用Tensorflow 1.11.0按照教程保存简单的keras顺序模型。我能够将模型配置转换为json字符串,并且能够保存权重,但不能完全保存模型。

错误来自Model.save中的第一行代码,该代码检查self._is_graph_network是否为True。我觉得我缺少一些基本的东西,但是我无法弄清楚。我相信我的代码类似于此处的教程代码:“保存整个模型”部分的Keras Save and Restore

Python 3.6.6 (default, Jun 28 2018, 05:43:53)
[GCC 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> import tensorflow.keras as tk
>>> mnist = tk.datasets.mnist
>>> (xtrain, ytrain), (xtest, ytest) = mnist.load_data()
>>> xtrain, xtest = xtrain/255.0, xtest/255.0
>>> model = tk.models.Sequential([tk.layers.Flatten(), tk.layers.Dense(64, activation=tf.nn.relu), \
tk.layers.Dense(10, activation=tf.nn.softmax)])
>>> model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
>>> model.fit(xtrain, ytrain, epochs=5)
Epoch 1/5
60000/60000 [==============================] - 2s 39us/step - loss: 0.3086 - acc: 0.9126
...
Epoch 5/5
60000/60000 [==============================] - 2s 37us/step - loss: 0.0715 - acc: 0.9787
<tensorflow.python.keras.callbacks.History object at 0x129819470>
>>> model.evaluate(xtest, ytest)
10000/10000 [==============================] - 0s 17us/step
[0.09259423367818817, 0.9711]
>>> model.save('m0x.h5')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mmelton/Library/Python/3.6/lib/python/site-packages/tensorflow/python/keras/engine/n\
etwork.py", line 1358, in save
    raise NotImplementedError
NotImplementedError
>>> model._is_graph_network
False
>>> model.save_weights('w0.h5', save_format='h5')
>>>

>>> tf.__version__
'1.11.0'
>>> tk.__version__
'2.1.6-tf'
>>>

我想念什么?

1 个答案:

答案 0 :(得分:1)

model = tk.models.Sequential([
    tk.layers.Flatten(), 
    tk.layers.Dense(64, activation=tf.nn.relu), 
    tk.layers.Dense(10, activation=tf.nn.softmax)
])

您的网络没有输入-Flatten(input_shape=(784,))。另外,将Flatten()作为第一层有点有趣,但是如果需要的话,可以选择