首页 文章

微调resnet50时如何冻结一些图层

提问于
浏览
3

我试图用keras微调resnet 50 . 当我冻结resnet50中的所有图层时,一切正常 . 但是,我想冻结一些resnet50层,而不是所有层 . 但是当我这样做时,我会遇到一些错误 . 这是我的代码:

base_model = ResNet50(include_top=False, weights="imagenet", input_shape=(input_size, input_size, input_channels))
model = Sequential()
model.add(base_model)
model.add(Flatten())
model.add(Dense(80, activation="softmax"))

#this is where the error happens. The commented code works fine
"""
for layer in base_model.layers:
    layer.trainable = False
"""
for layer in base_model.layers[:-26]:
    layer.trainable = False
model.summary()
optimizer = Adam(lr=1e-4)
model.compile(loss="categorical_crossentropy", optimizer=optimizer, metrics=["accuracy"])

callbacks = [
    EarlyStopping(monitor='val_loss', patience=4, verbose=1, min_delta=1e-4),
    ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=2, cooldown=2, verbose=1),
    ModelCheckpoint(filepath='weights/renet50_best_weight.fold_' + str(fold_count) + '.hdf5', save_best_only=True,
                    save_weights_only=True)
    ]

model.load_weights(filepath="weights/renet50_best_weight.fold_1.hdf5")
model.fit_generator(generator=train_generator(), steps_per_epoch=len(df_train) // batch_size,  epochs=epochs, verbose=1,
                  callbacks=callbacks, validation_data=valid_generator(), validation_steps = len(df_valid) // batch_size)

错误如下:

Traceback (most recent call last):
File "/home/jamesben/ai_challenger/src/train.py", line 184, in <module> model.load_weights(filepath="weights/renet50_best_weight.fold_" + str(fold_count) + '.hdf5')
File "/usr/local/lib/python3.5/dist-packages/keras/models.py", line 719, in load_weights topology.load_weights_from_hdf5_group(f, layers)
File "/usr/local/lib/python3.5/dist-packages/keras/engine/topology.py", line 3095, in load_weights_from_hdf5_group K.batch_set_value(weight_value_tuples)
File "/usr/local/lib/python3.5/dist-packages/keras/backend/tensorflow_backend.py", line 2193, in batch_set_value get_session().run(assign_ops, feed_dict=feed_dict)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 767, in run run_metadata_ptr)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 944, in _run % (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (128,) for Tensor 'Placeholder_72:0', which has shape '(3, 3, 128, 128)'

任何人都可以给我一些帮助,我应该用resnet50冻结多少层?

1 回答

  • 5

    load_weights()save_weights() 与嵌套模型一起使用时,如果 trainable 设置不相同,则很容易出错 .

    要解决此错误,请确保在调用 model.load_weights() 之前冻结相同的图层 . 也就是说,如果保存权重文件并冻结所有图层,则过程将为:

    • 重新创建模型

    • 冻结 base_model 中的所有图层

    • 加载重量

    • 解冻您要训练的那些图层(在本例中为 base_model.layers[-26:]

    例如,

    base_model = ResNet50(include_top=False, input_shape=(224, 224, 3))
    model = Sequential()
    model.add(base_model)
    model.add(Flatten())
    model.add(Dense(80, activation="softmax"))
    
    for layer in base_model.layers:
        layer.trainable = False
    model.load_weights('all_layers_freezed.h5')
    
    for layer in base_model.layers[-26:]:
        layer.trainable = True
    

    潜在原因:

    当您调用 model.load_weights() 时,(大致)通过以下步骤加载每个图层的权重(在topology.py中的函数 load_weights_from_hdf5_group() 中):

    • 调用 layer.weights 以获得权重张量

    • 将每个重量张量与hdf5文件中相应的重量值相匹配

    • 调用 K.batch_set_value() 将权重值分配给权重张量

    如果您的模型是嵌套模型,则必须小心 trainable ,因为步骤1 .

    我将用一个例子来解释它 . 对于与上述相同的型号, model.summary() 给出:

    _________________________________________________________________
    Layer (type)                 Output Shape              Param #
    =================================================================
    resnet50 (Model)             (None, 1, 1, 2048)        23587712
    _________________________________________________________________
    flatten_10 (Flatten)         (None, 2048)              0
    _________________________________________________________________
    dense_5 (Dense)              (None, 80)                163920
    =================================================================
    Total params: 23,751,632
    Trainable params: 11,202,640
    Non-trainable params: 12,548,992
    _________________________________________________________________
    

    在加载重量期间,内部 ResNet50 模型被视为 model 的一层 . 加载图层 resnet50 时,在步骤1中,调用 layer.weights 等同于调用 base_model.weights . 将收集并返回 ResNet50 模型中所有图层的权重张量列表 .

    现在的问题是,在构建权重张量列表时, trainable weights will come before non-trainable weights . 在 Layer 类的定义中:

    @property
    def weights(self):
        return self.trainable_weights + self.non_trainable_weights
    

    如果 base_model 中的所有图层都被冻结,则权重张量将按以下顺序排列:

    for layer in base_model.layers:
        layer.trainable = False
    print(base_model.weights)
    
    [<tf.Variable 'conv1/kernel:0' shape=(7, 7, 3, 64) dtype=float32_ref>,
     <tf.Variable 'conv1/bias:0' shape=(64,) dtype=float32_ref>,
     <tf.Variable 'bn_conv1/gamma:0' shape=(64,) dtype=float32_ref>,
     <tf.Variable 'bn_conv1/beta:0' shape=(64,) dtype=float32_ref>,
     <tf.Variable 'bn_conv1/moving_mean:0' shape=(64,) dtype=float32_ref>,
     <tf.Variable 'bn_conv1/moving_variance:0' shape=(64,) dtype=float32_ref>,
     <tf.Variable 'res2a_branch2a/kernel:0' shape=(1, 1, 64, 64) dtype=float32_ref>,
     <tf.Variable 'res2a_branch2a/bias:0' shape=(64,) dtype=float32_ref>,
     ...
     <tf.Variable 'res5c_branch2c/kernel:0' shape=(1, 1, 512, 2048) dtype=float32_ref>,
     <tf.Variable 'res5c_branch2c/bias:0' shape=(2048,) dtype=float32_ref>,
     <tf.Variable 'bn5c_branch2c/gamma:0' shape=(2048,) dtype=float32_ref>,
     <tf.Variable 'bn5c_branch2c/beta:0' shape=(2048,) dtype=float32_ref>,
     <tf.Variable 'bn5c_branch2c/moving_mean:0' shape=(2048,) dtype=float32_ref>,
     <tf.Variable 'bn5c_branch2c/moving_variance:0' shape=(2048,) dtype=float32_ref>]
    

    但是,如果某些层是可训练的,可训练层的重量张量将先于冷冻层的重量张量:

    for layer in base_model.layers[-5:]:
        layer.trainable = True
    print(base_model.weights)
    
    [<tf.Variable 'res5c_branch2c/kernel:0' shape=(1, 1, 512, 2048) dtype=float32_ref>,
     <tf.Variable 'res5c_branch2c/bias:0' shape=(2048,) dtype=float32_ref>,
     <tf.Variable 'bn5c_branch2c/gamma:0' shape=(2048,) dtype=float32_ref>,
     <tf.Variable 'bn5c_branch2c/beta:0' shape=(2048,) dtype=float32_ref>,
     <tf.Variable 'conv1/kernel:0' shape=(7, 7, 3, 64) dtype=float32_ref>,
     <tf.Variable 'conv1/bias:0' shape=(64,) dtype=float32_ref>,
     <tf.Variable 'bn_conv1/gamma:0' shape=(64,) dtype=float32_ref>,
     <tf.Variable 'bn_conv1/beta:0' shape=(64,) dtype=float32_ref>,
     <tf.Variable 'bn_conv1/moving_mean:0' shape=(64,) dtype=float32_ref>,
     <tf.Variable 'bn_conv1/moving_variance:0' shape=(64,) dtype=float32_ref>,
     <tf.Variable 'res2a_branch2a/kernel:0' shape=(1, 1, 64, 64) dtype=float32_ref>,
     <tf.Variable 'res2a_branch2a/bias:0' shape=(64,) dtype=float32_ref>,
     ...
     <tf.Variable 'bn5c_branch2b/moving_mean:0' shape=(512,) dtype=float32_ref>,
     <tf.Variable 'bn5c_branch2b/moving_variance:0' shape=(512,) dtype=float32_ref>,
     <tf.Variable 'bn5c_branch2c/moving_mean:0' shape=(2048,) dtype=float32_ref>,
     <tf.Variable 'bn5c_branch2c/moving_variance:0' shape=(2048,) dtype=float32_ref>]
    

    顺序的变化是你得到张量形状错误的原因 . 保存在hdf5文件中的权重值与上述步骤2中的错误权重张量相匹配 . 冻结所有图层时一切正常的原因是因为模型检查点也被保存,所有图层都被冻结,因此顺序正确 .


    可能更好的解决方案:

    您可以使用功能API来避免嵌套模型 . 例如,以下代码应该可以正常工作:

    base_model = ResNet50(include_top=False, weights="imagenet", input_shape=(input_size, input_size, input_channels))
    x = Flatten()(base_model.output)
    x = Dense(80, activation="softmax")(x)
    model = Model(base_model.input, x)
    
    for layer in base_model.layers:
        layer.trainable = False
    model.save_weights("all_nontrainable.h5")
    
    base_model = ResNet50(include_top=False, weights="imagenet", input_shape=(input_size, input_size, input_channels))
    x = Flatten()(base_model.output)
    x = Dense(80, activation="softmax")(x)
    model = Model(base_model.input, x)
    
    for layer in base_model.layers[:-26]:
        layer.trainable = False
    model.load_weights("all_nontrainable.h5")
    

相关问题