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

时间:2018-12-23 01:46:29

标签: tensorflow keras resnet

我正在尝试使用预先训练的权重来训练模型,但是在加载模型时却不断出现此错误。

我的模型参数:

python train.py \
--gpu "0"  \
--fold "0,1,2,3" \
--num_workers 8  \
--network resnet101_2 \
--freeze_till_layer input_1  \
--loss double_head_loss \
--optimizer adam  \
--learning_rate 0.0001  \
--decay 0.0001  \
--batch_size 16  \
--crop_size 256 \
--steps_per_epoch 500 \
--epochs 70 \
--use_full_masks \
--preprocessing_function caffe \
--weights "nn_models/best_resnet101_2_fold{}.h5"

我的train()函数:

def main():
    if args.crop_size:
        print('Using crops of shape ({}, {})'.format(args.crop_size, args.crop_size))
    else:
        print('Using full size images')
    folds = [int(f) for f in args.fold.split(",")]
    for fold in folds:
        channels = 3
        if args.multi_gpu:
            with K.tf.device("/cpu:0"):
                model = make_model(args.network, (None, None, 3))
        else:
            model = make_model(args.network, (None, None, channels))
        if args.weights is None:
            print('No weights passed, training from scratch')
        else:
            weights_path = args.weights.format(fold)
            print('Loading weights from {}'.format(weights_path))
            model.load_weights(weights_path, by_name=True)

我的ResNet101 2折模型:

def resnet101_fpn(input_shape, channels=1, activation="softmax"):
    img_input = Input(input_shape)
    resnet_base = ResNet101(img_input, include_top=True)
    resnet_base.load_weights('./best_resnet101_2_fold0.h5')
    conv1 = resnet_base.get_layer("conv1_relu").output
    conv2 = resnet_base.get_layer("res2c_relu").output
    conv3 = resnet_base.get_layer("res3b3_relu").output
    conv4 = resnet_base.get_layer("res4b22_relu").output
    conv5 = resnet_base.get_layer("res5c_relu").output
    P1, P2, P3, P4, P5 = create_pyramid_features(conv1, conv2, conv3, conv4, conv5)
    x = concatenate(
        [
            prediction_fpn_block(P5, "P5", (8, 8)),
            prediction_fpn_block(P4, "P4", (4, 4)),
            prediction_fpn_block(P3, "P3", (2, 2)),
            prediction_fpn_block(P2, "P2"),
        ]
    )
    x = conv_bn_relu(x, 256, 3, (1, 1), name="aggregation")
    x = decoder_block_no_bn(x, 128, conv1, 'up4')
    x = UpSampling2D()(x)
    x = conv_relu(x, 64, 3, (1, 1), name="up5_conv1")
    x = conv_relu(x, 64, 3, (1, 1), name="up5_conv2")
    if activation == 'softmax':
        name = 'mask_softmax'
        x = Conv2D(channels, (1, 1), activation=activation, name=name)(x)
    else:
        x = Conv2D(channels, (1, 1), activation=activation, name="mask")(x)
    model = Model(img_input, x)
    return model

要应用该模型,我需要更改什么?我读到这是2.1.x版本的Keras错误,我已经升级到2.2.0。

致谢

1 个答案:

答案 0 :(得分:0)

我通过将resnet_base.load_weights('./best_resnet101_2_fold0.h5')更改为resnet_base.load_weights('./best_resnet101_2_fold0.h5', by_name=True)

来解决