ValueError:您尝试将包含14层的权重文件加载到具有3层的模型中

时间:2019-01-18 12:05:48

标签: python tensorflow keras valueerror pre-trained-model

(我找不到先前提出的问题的解决方案。) 我使用VGG16来测试我的数据。我的班级号是2,我用this page冻结了转换层并训练了顶层。这是代码:

from keras.applications import VGG16
model = VGG16(include_top=False,classes=2,input_shape(224,224,3),weights='imagenet')

然后我创建了top_model,它将成为我的Vgg16的顶级模型:

top_model=Sequential()
top_model.add(Flatten(input_shape=model.output_shape[1:]))
top_model.add(Dense(4096,activation='relu'))
top_model.add(Dense(4096,activation='relu'))
top_model.add(Dense(2,activation='softmax'))
model= Model(inputs=model.input, output=top_model(model.output))

然后我冻结了一些图层并编译了模型:

for layer in model.layers[:19]:
 layer.trainable=False

model.compile(loss='binary_crossentropy',optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),
           metrics=['accuracy'])

经过一些数据扩充过程,我训练了模型并保存了权重:

model.fit_generator(trainGenerator,samples_per_epoch=numTraining//batchSize,
                  epochs=numEpoch,
                  validation_data=valGenerator,
                  validation_steps=numValid//batchSize)

model.save_weights('top3_weights.h5') 

此后,保存了权重,并更改了代码的第二部分,以便能够使用数据测试整个模型:

model = VGG16(include_top=False,classes=2,input_shape=(224,224,3),weights='imagenet')

top_model=Sequential()
top_model.add(Flatten(input_shape=model.output_shape[1:]))
top_model.add(Dense(4096,activation='relu'))
top_model.add(Dense(4096,activation='relu'))
top_model.add(Dense(2,activation='softmax'))
top_model.load_weights(r'C:\\Users\\Umit Kilic\\Komodomyfiles\\umit\\top3_weights.h5') #(this line is added)
model= Model(inputs=model.input, output=top_model(model.output)) 

最后,当我尝试用代码总结模型时:

print(model.summary())

我得到了错误和输出:

Using TensorFlow backend.
Traceback (most recent call last):
  File "C:\Users\Umit Kilic\Komodomyfiles\umit\test_vgg16.py", line 38, in <module>
    top_model.load_weights(r'C:\\Users\\Umit Kilic\\Komodomyfiles\\umit\\top3_weights.h5')
  File "C:\Users\Umit Kilic\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\engine\network.py", line 1166, in load_weights
f, self.layers, reshape=reshape)
  File "C:\Users\Umit Kilic\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\engine\saving.py", line 1030, in load_weights_from_hdf5_group
str(len(filtered_layers)) + ' layers.')
ValueError: You are trying to load a weight file containing 14 layers into a model with 3 layers.

有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

model包含完整模型,即VGG加top_model的堆叠模型。保存权重时,它有14层。您也无法在top_model中加载它,因为VGG权重也在其中,但是您可以在新的model中加载。

model = VGG16(include_top=False,classes=2,input_shape=(224,224,3),weights='imagenet')
top_model=Sequential()
top_model.add(Flatten(input_shape=model.output_shape[1:])) 
top_model.add(Dense(4096,activation='relu'))
top_model.add(Dense(4096,activation='relu'))
top_model.add(Dense(2,activation='softmax'))
model= Model(inputs=model.input, output=top_model(model.output))

model.load_weights(r'C:\\Users\\Umit Kilic\\Komodomyfiles\\umit\\top3_weights.h5') #(this line is added)