属性错误:'Sequential'对象没有属性'output_names'。

7

我遇到了以下代码的一些问题,在下面这行代码中:

new_model = load_model('124446.model', custom_objects=None, compile=True)

以下是完整代码:

import tensorflow as tf
from tensorflow.keras.models import load_model

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)


tf.keras.models.save_model(model,'124446.model')


val_loss, val_acc = model.evaluate(x_test,y_test)
print(val_loss, val_acc)


new_model = load_model('124446.model', custom_objects=None, compile=True)


prediction = new_model.predict([x_test])
print(prediction)

错误信息如下:
Traceback (most recent call last): File "C:/Users/TanveerIslam/PycharmProjects/DeepLearningPractice/1.py", line 32, in new_model = load_model('124446.model', custom_objects=None, compile=True) File "C:\Users\TanveerIslam\PycharmProjects\DeepLearningPractice\venv\lib\site-packages\tensorflow\python\keras\engine\saving.py", line 262, in load_model sample_weight_mode=sample_weight_mode) File "C:\Users\TanveerIslam\PycharmProjects\DeepLearningPractice\venv\lib\site-packages\tensorflow\python\training\checkpointable\base.py", line 426, in _method_wrapper method(self, *args, **kwargs) File "C:\Users\TanveerIslam\PycharmProjects\DeepLearningPractice\venv\lib\site-packages\tensorflow\python\keras\engine\training.py", line 525, in compile metrics, self.output_names AttributeError: 'Sequential' object has no attribute 'output_names'
请问有没有任何解决办法?
注:我使用的是PyCharm集成开发环境。

代码运行良好。我不知道哪里出了问题。也许尝试指定一个特定的位置来保存/加载文件。 - George
感谢您的回复。我已经使用了文件(模型)的真实路径。但是仍然出现相同的错误“AttributeError:'Sequential'对象没有属性'output_names'”,并且我使用的是PyCharm IDE。 - Tanveer Islam
4个回答

5

如@Shinva所说,将load_model函数的“compile”属性设置为“False”。 然后在加载模型之后,单独编译它。

from tensorflow.keras.models import save_model, load_model
save_model(model,'124446.model')

然后,要重新加载模型,请执行以下操作:

saved_model = load_model('124446.model', compile=False)
saved_model.compile(optimizer='adam',
          loss='sparse_categorical_crossentropy',
          metrics=['accuracy'])
saved_model.predict([x_test])

更新: 由于某些未知原因,我开始遇到与问题陈述相同的错误。在尝试寻找不同解决方案后,似乎直接使用“keras”库而不是“tensorflow.keras”可以正常工作。

我的设置是在“Windows 10”上,使用python:'3.6.7',tensorflow:'1.11.0'和keras:'2.2.4'

据我所知,有三种不同的方法可以保存和恢复您的模型;前提是您已经直接使用keras制作了您的模型。

选项1:

import json
from keras.models import model_from_json, load_model

# Save Weights + Architecture
model.save_weights('model_weights.h5')
with open('model_architecture.json', 'w') as f:
    f.write(model.to_json())

# Load Weights + Architecture
with open('model_architecture.json', 'r') as f:
    new_model = model_from_json(f.read())
new_model.load_weights('model_weights.h5')

Option2:

from keras.models import save_model, load_model

# Creates a HDF5 file 'my_model.h5' 
save_model(model, 'my_model.h5') # model, [path + "/"] name of model

# Deletes the existing model
del model  

# Returns a compiled model identical to the previous one
new_model = load_model('my_model.h5')

Option 3

# using model's methods
model.save("my_model.h5")

# deletes the existing model
del model

# load the saved model back
new_model = load_model('my_model.h5')

选项1要求在使用之前需要先编译 new_model。

选项2和3的语法几乎相同。

使用的代码来源:
1. 保存和加载Keras模型
2. https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model


2

通过在load_model()中设置compile=False,我成功地加载了模型。


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

new_model = tf.keras.models.load_model('epic_num_reader.model', custom_objects=None, compile=False)

predictions = new_model.predict(x_test)
print(predictions)

import numpy as np

print(np.argmax(predictions[0]))
plt.imshow(x_test[0],cmap=plt.cm.binary)
plt.show()

4
尽管这段代码可能解决了问题,但如果您能够解释它是如何解决问题的,为什么这样做可以提高您的帖子质量并可能获得更多的赞。请记住,您在回答问题时是为未来的读者而不仅仅是为当前提问的人。请[编辑]您的答案以添加说明,并指出适用的限制和假设。 - Suraj Rao

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接