简体   繁体   中英

Getting error in Keras while loading the model from load_model()

I am a beginner in Keras and I am writing a simple program for MNIST but when I tried to load the model I am getting this error:

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

This is my code:

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

Can anyone explain what's wrong in the code? I am using Keras version 2.2.0.

you need to add input_shape to your model while adding layer instance. read the documentation for add function it's clearly talking about error details. Please see below screenshot.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM