keras加载模型错误,试图将包含17层的权重文件加载到0层的模型中 [英] keras load model error trying to load a weight file containing 17 layers into a model with 0 layers

查看:111
本文介绍了keras加载模型错误,试图将包含17层的权重文件加载到0层的模型中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在与keras一起开发vgg16模型. 我用一些图层微调了vgg模型. 拟合模型(训练)后,我将模型保存为model.save('name.h5'). 可以毫无问题地保存它. 但是,当我尝试使用load_model函数重新加载模型时,它显示错误:

I am currently working on vgg16 model with keras. I fine tune vgg model with some of my layer. After fitting my model (training), I save my model with model.save('name.h5'). It can be saved without problem. However, when I try to reload the model with load_model function, it shows the error:

您正在尝试将包含17层的权重文件加载到模型中 有0层

You are trying to load a weight file containing 17 layers into a model with 0 layers

有人以前遇到过这个问题吗? 我的keras版本是2.2.

Did anyone meet this problem before? My keras verion is 2.2.

这是我的代码的一部分...

Here is part of my code ...

from keras.models import load_model
vgg_model = VGG16(weights='imagenet',include_top=False,input_shape=(224,224,3))    
global model_2
model_2 = Sequential()
for layer in vgg_model.layers:
    model_2.add(layer)
for layer in model_2.layers:
    layer.trainable= False
model_2.add(Flatten())
model_2.add(Dense(128, activation='relu'))
model_2.add(Dropout(0.5))
model_2.add(Dense(2, activation='softmax'))
model_2.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model_2.fit(x=X_train,y=y_train,batch_size=32,epochs=30,verbose=2)
model_2.save('name.h5')
del model_2
model_2 = load_model('name.h5')

实际上,我不会先删除模型,然后立即删除load_model, 只是为了显示我的问题.

Actually I do not delete the model and then load_model immediately, just for showing my problem.

推荐答案

我花了6个小时寻找解决方案. 最后,我尝试使用VGG16作为模型,并使用我自己训练的h5砝码,太棒了!

I spent 6 hours looking around for a solution.. to apply me trained model. finally i tried VGG16 as model and using h5 weights i´ve trained on my own and Great!

weights_model='C:/Anaconda/weightsnew2.h5'  # my already trained weights .h5
vgg=applications.vgg16.VGG16()
cnn=Sequential()
for capa in vgg.layers:
   cnn.add(capa)
cnn.layers.pop()
for layer in cnn.layers:
   layer.trainable=False
cnn.add(Dense(2,activation='softmax'))  

cnn.load_weights(weights_model)

def predict(file):
   x = load_img(file, target_size=(longitud, altura)) 
   x = img_to_array(x)                            
   x = np.expand_dims(x, axis=0)
   array = cnn.predict(x)     
   result = array[0]
   respuesta = np.argmax(result) 
   if respuesta == 0:
      print("Gato")
   elif respuesta == 1:
      print("Perro")

这篇关于keras加载模型错误,试图将包含17层的权重文件加载到0层的模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆