从load_model()加载模型时在Keras中获取错误

时间:2018-07-11 15:26:06

标签: python keras mnist

我是Keras的初学者,我正在为MNIST编写一个简单的程序,但是当我尝试加载模型时出现此错误:

ValueError: You are trying to load a weight file containing 2 layers into a model with 0 layers.

这是我的代码:

import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import np_utils

#fixing random number seed
np.random.seed(7)

(X_train, Y_train),(X_test, Y_test) = mnist.load_data("D:\MY CODE PROJECT\CNN\datasets\mnist.npz")
num_pixel   =  X_train.shape[1] * X_train.shape[2]

#converting image to vector
X_train = X_train.reshape(X_train.shape[0],num_pixel).astype('float32')
X_test  = X_test.reshape(X_test.shape[0],num_pixel).astype('float32')

# Normalizing Input from 0-255 to 0-1
X_train = X_train/255
X_test  = X_test/255

#As output is multiclass so change output labels to 'ONE-HOT' ecodings Form
Y_train = np_utils.to_categorical(Y_train)
Y_test  = np_utils.to_categorical(Y_test)

#defining simple Neural Network with one hidden layer
num_classes = Y_test.shape[1]
#creating model
model = Sequential()
model.add(Dense(num_pixel,activation = 'relu',kernel_initializer='normal'))
model.add(Dense(num_classes, kernel_initializer='normal',activation='softmax'))
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
#Fitting the model
model.fit(X_train,Y_train,batch_size=200,epochs=10,verbose=2,validation_data=(X_test,Y_test))
scores = model.evaluate(X_test,Y_test,verbose=0)
#Printing Error
print("baseline Error: %f" %(100-scores[1]*100))

model.save('mnist_nn_keras.h5')
del model

model = load_model('mnist_nn_keras.h5')

任何人都可以解释代码中的错误吗?我正在使用Keras 2.2.0版。

1 个答案:

答案 0 :(得分:0)

您需要在添加图层实例的同时向模型添加input_shape。阅读有关添加功能的文档,它显然是在讨论错误详细信息。 请参见下面的屏幕截图。

enter image description here