AttributeError:“顺序”对象没有属性“ output_names”

时间:2018-10-05 10:58:44

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

以下代码有问题 以下行 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)

错误是:

  

回溯(最近通话最近):文件   “ C:/用户/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”,   在load_model中的第262行       sample_weight_mode = sample_weight_mode)文件“ C:\ Users \ TanveerIslam \ PycharmProjects \ DeepLearningPractice \ venv \ lib \ site-packages \ tensorflow \ python \ training \ checkpointable \ base.py”,   _method_wrapper中的第426行       方法(自身,* args,** kwargs)文件“ C:\ Users \ TanveerIslam \ PycharmProjects \ DeepLearningPractice \ venv \ lib \ site-packages \ tensorflow \ python \ keras \ engine \ training.py”,   525行,正在编译       指标,self.output_names)

     

AttributeError:“顺序”对象没有属性“ output_names”

任何人都可以给我提供解决方案。

注意:我使用pycharm作为IDE。

4 个答案:

答案 0 :(得分:1)

我可以通过在 load_model()

中设置 compile = False 来加载模型

答案 1 :(得分:0)

如果此程序在Windows上运行,则问题在于Windows当前不支持toco-https://github.com/tensorflow/tensorflow/issues/20975

答案 2 :(得分:0)

正如@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要求编译才能使用。

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

使用的代码:
 1. Saving & Loading Keras Models
 2. https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model

答案 3 :(得分:0)

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