【发布时间】:2019-06-12 16:50:47
【问题描述】:
(我无法通过之前提出的问题找到解决方案。) 我使用 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.
有什么帮助吗?
【问题讨论】:
标签: python tensorflow keras valueerror pre-trained-model