首页 文章

使用VGG16微调模型后无法加载重量

提问于
浏览
0

我从VGG16加载了权重并添加到我的顺序模型中 . 我想通过冻结顶层(微调)来训练VGG16的较低重量 .

一切都很好:我能够 Build 模型并预测新图像 . 但现在我想加载模型,我无法做到 .

这是我尝试过的代码如下:

model1 = applications.VGG16(weights='imagenet', 
include_top=False,input_shape=(img_width,img_height,3))

train_datagen = ImageDataGenerator(rescale=1./255,
                                   rotation_range=40,
                                   width_shift_range=0.2,
                                   height_shift_range=0.2,
                                   shear_range=0.2,
                                   zoom_range=0.2,
                                   horizontal_flip=True,
                                   fill_mode='nearest')

test_datagen = ImageDataGenerator(rescale=1./255)


 train_generator = train_datagen.flow_from_directory(train_data_dir,
                                        target_size=(img_width, img_height),
                                        batch_size=size_batch, 
                                        class_mode='binary', 
                                        shuffle=False) 


# repeat with the validation data

 test_generator = test_datagen.flow_from_directory(validation_data_dir,
                                       target_size=(img_width, img_height),
                                       batch_size=size_batch,
                                       class_mode='binary',
                                       shuffle=False)


 model = Sequential()
 model.add(Flatten(input_shape=model1.output_shape[1:]))
 model.add(Dense(256, activation='relu'))
 model.add(Dropout(0.2))
 model.add(Dense(1, activation='sigmoid'))

 new_model=Sequential()

 for l in model1.layers:
      new_model.add(l)

  new_model.add(model)

 for layer in new_model.layers[:25]:
       layer.trainable=False

 new_model.compile(optimizer=optimizers.SGD(lr=1e-3, 
 momentum=0.9),loss='binary_crossentropy',
              metrics=['accuracy'])
 checkpoint = ModelCheckpoint(fine_tuned_model_path, monitor='val_acc', 
                             verbose=1, save_best_only=True, 
                             save_weights_only=False, mode='auto')
# fine-tune the model
fit=new_model.fit_generator(train_generator,
                          steps_per_epoch=33,
                          nb_epoch=1,

                          validation_data=test_generator,

                          verbose=1,callbacks=[checkpoint])

然后我试图加载模型:

load_model("C:/Users/hi/POC/Fine_Tune/model.h5")

这是我收到的错误:

ValueError:您正在尝试将包含14个图层的权重文件加载到具有1个图层的模型中 .

2 回答

  • 0

    我不明白为什么你必须定义一个新模型并将前面的VGG16层加载到你的新模型中 .

    关于l建议的最佳工作是冻结你想要的VGG16架构层,并将你想要的层作为可训练层,就像你在上一个 for 循环中所做的那样

    这最终会导致您删除嵌入的两个 for 循环 .

    # the way you loaded your images and did not include_top layer 
    model1 = applications.VGG16(weights='imagenet', include_top=False, input_shape = (img_width, img_height, 3))
    
    #to see the structure of your architecture
    model.summary() 
    
    #freezing the layers you do not want for training in your architecture
    for layer in model1.layers[:25]:
        layer.trainable = False
    
    #the rest is the same from here on forth with the exclusion of the two for loops
    #which you need to remove as they are no longer required.
    train_datagen = ImageDataGenerator(rescale=1./255,
                                   rotation_range=40,
                                   width_shift_range=0.2,
                                   height_shift_range=0.2,
                                   shear_range=0.2,
                                   zoom_range=0.2,
                                   horizontal_flip=True,
                                   fill_mode='nearest')
    
    #etc...
    
  • 0

    根据Keras问题8898,可以通过编辑Keras代码来避免此错误 keras/applications/vgg16.py

    以便用于读取 model.load_weights(weights_path) 的行现在读取 model.load_weights(weights_path, by_name=True)

    我发现这也适用于其他应用程序模型的imagenet权重,例如: nasnet .

相关问题