【问题标题】:AttributeError: 'Sequential' object has no attribute 'output_names'AttributeError:“顺序”对象没有属性“输出名称”
【发布时间】:2019-03-10 20:56:09
【问题描述】:

下面的代码有问题 以下行的 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(最近一次调用最后一次):文件 "C:/Users/TanveerIslam/PycharmProjects/DeepLearningPractice/1.py", 第 32 行,在 new_model = load_model('124446.model', custom_objects=None, compile=True) 文件 "C:\Users\TanveerIslam\PycharmProjects\DeepLearningPractice\venv\lib\site-packages\tensorflow\python\keras\engine\saving.py", 第 262 行,在 load_model sample_weight_mode=sample_weight_mode) 文件 "C:\Users\TanveerIslam\PycharmProjects\DeepLearningPractice\venv\lib\site-packages\tensorflow\python\training\checkpointable\base.py", 第 426 行,在 _method_wrapper 中 方法(自我,*args,**kwargs)文件“C:\Users\TanveerIslam\PycharmProjects\DeepLearningPractice\venv\lib\site-packages\tensorflow\python\keras\engine\training.py”, 第 525 行,在编译中 指标,self.output_names)

AttributeError: 'Sequential' 对象没有属性 'output_names'

那么任何人都可以给我蚂蚁解决方案。

注意:我使用 pycharm 作为 IDE。

【问题讨论】:

  • 代码运行正常。我不知道是什么问题。也许尝试指定保存/加载文件的某个位置。
  • 感谢您的回复。但我也使用了文件(模型)的真实路径。但显示相同的错误“AttributeError:'Sequential'对象没有属性'output_names'”并且我使用了pycharm IDE

标签: python tensorflow machine-learning keras deep-learning


【解决方案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()

【讨论】:

  • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
【解决方案2】:

正如@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')

选项2:

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')

选项 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.Saving & Loading Keras Models
2.https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model

【讨论】:

    【解决方案3】:

    我可以通过在 load_model()

    中设置 compile=False 来加载模型

    【讨论】:

      【解决方案4】:

      如果这是在 Windows 上运行,那么问题是当前 Windows 不支持 toco - https://github.com/tensorflow/tensorflow/issues/20975

      【讨论】:

        猜你喜欢
        • 2019-05-24
        • 2022-01-04
        • 2021-10-23
        • 2020-01-29
        • 2020-01-03
        • 2021-10-28
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        相关资源
        最近更新 更多