【问题标题】:How to use first 10 layers of pre trained model like VGG19 keras?如何使用 VGG19 keras 等前 10 层预训练模型?
【发布时间】:2019-12-15 17:35:26
【问题描述】:

我正在尝试使用 VGG19 的前 10 层进行图像分类任务的迁移学习。

我尝试使用前 10 层,但是当我将它添加到顺序模型并显示摘要时,我遇到了错误。

basemodel = VGG19(include_top = False)    
x = basemodel.layers[-10]    
model = Sequential()    
model.add(keras.layers.Conv2D(32,(7,7),input_shape = (256,256,3),activation = 'relu'))    
model.add(x)    
model.summary()

【问题讨论】:

  • 请格式化您的代码和错误以便更好地阅读
  • 你能显示错误代码吗?
  • 它显示模型必须在编译前构建

标签: python tensorflow keras transfer-learning vgg-net


【解决方案1】:

我运行模型,错误是: ValueError: Input 0 is incompatible with layer block4_conv1: expected axis -1 of input shape to have value 256 but got shape (None, 250, 250, 32)

keras.layers.Conv2D 中删除输入形状 并将其添加到 basemodel:

basemodel = VGG19(include_top = False,input_shape=(256,256,3),weights='None')

或者如果你想使用 Imagenet:

basemodel = VGG19(include_top = False,input_shape=(256,256,3),weights='imagenet')

拟合模型并让我知道发生的任何错误。

【讨论】:

    【解决方案2】:

    您只从 VGG 模型中提取了一层,并以错误的方式连接它们。 这是正确的方法之一:

    basemodel = VGG19(include_top = False)    
    model = tf.keras.Sequential(basemodel.layers[:10])
    model.add(keras.layers.Conv2D(32, (7, 7), activation = 'relu'))
    model.summary()
    

    请注意VGG 的第一层是InputLayer,因此您应该使用basemodel.layers[:11]

    请注意,要微调您的模型,最好修复 VGG 层的权重:

    for layer in model.layers[:10]:
        layer.trainable = False
    

    【讨论】:

      【解决方案3】:

      问题在于,您没有添加前 10 层,而是从顶部添加了第 10 层。此外,该层的输入应该具有 256 的倍数的通道。只需将代码替换为:

      model.add(keras.layers.Conv2D(256,(7,7),input_shape = (256,256,3),activation = 'relu')) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-25
        • 1970-01-01
        • 2019-11-28
        • 2021-04-17
        • 1970-01-01
        • 2018-12-21
        相关资源
        最近更新 更多