首页 文章

如何使用VGG-16的预训练功能作为Keras中GlobalAveragePooling2D()图层的输入

提问于
浏览
1

是否可以使用VGG-16的预训练模型特征并传递到Keras中其他模型的GlobalAveragePooling2D()图层?

存储VGG-16网络离线功能的示例代码:

model = applications.VGG16(include_top=False, weights='imagenet')
bottleneck_features_train = model.predict(input)

顶级型号的示例代码:

model = Sequential()
model.add(GlobalAveragePooling2D()) # Here I want to use pre-trained feature from VGG-16 net as input.

我不能使用Flatten()图层,因为我想用多类来预测多标签 .

1 回答

  • 1

    当然,你绝对可以 . 你有几个选择:

    汇集kwarg

    在VGG16构造函数中使用 pooling kwarg,它将使用指定的类型替换最后一个池化层 . 即

    model_base = keras.applications.vgg16.VGG16(include_top=False, input_shape=(*IMG_SIZE, 3), weights='imagenet', pooling="avg")
    

    将图层添加到输出中

    您还可以向预训练模型添加更多图层:

    from keras.models import Model
    
    model_base = keras.applications.vgg16.VGG16(include_top=False, input_shape=(*IMG_SIZE, 3), weights='imagenet')
    output = model_base.output
    output = GlobalAveragePooling2D()(output)
    # Add any other layers you want to `output` here...
    model = Model(model_base.input, output)
    for layer in model_base.layers:
        layer.trainable = False
    

    最后一行冻结预训练的图层,以便保留预训练模型的特征,并训练新图层 .

    我写了一篇博文,介绍了使用预训练模型的基础知识,并将它们扩展到各种图像分类问题 . 它还有一些链接到一些可能提供更多上下文的工作代码示例:http://innolitics.com/10x/pretrained-models-with-keras/

相关问题