【问题标题】:ValueError: Input 0 of layer global_average_pooling2d is incompatible with the layer: expected ndim=4, found ndim=2. Full shape received: [None, 128]ValueError: 层 global_average_pooling2d 的输入 0 与层不兼容:预期 ndim=4,发现 ndim=2。收到的完整形状:[无,128]
【发布时间】:2021-01-24 08:31:07
【问题描述】:

我加载保存的模型,出于微调的原因,我将分类层添加到加载模型的输出中,所以这是我写的:

def create_keras_model():
    model = tf.keras.models.load_model('model.h5', compile=False)
    resnet_output = model.output
    layer1 = tf.keras.layers.GlobalAveragePooling2D()(resnet_output)
    layer2 = tf.keras.layers.Dense(units=256, use_bias=False, name='nonlinear')(layer1)
    model_output = tf.keras.layers.Dense(units=2, use_bias=False, name='output', activation='relu')(layer2)
    model = tf.keras.Model(model.input, model_output)
    return model

但我发现这个错误:

ValueError: Input 0 of layer global_average_pooling2d is incompatible with the layer: expected ndim=4, found ndim=2. Full shape received: [None, 128]

谁能帮助我,告诉我这个错误是什么,我该如何解决这个问题。 谢谢!

【问题讨论】:

    标签: python tensorflow2


    【解决方案1】:

    如果您共享model.h5 架构或model.h5 的最后一层,可能会得到更好的回答。

    在您的情况下,输入维度为 2,其中 tf.keras.layers.GlobalAveragePooling2D() 期望输入维度为 4

    根据tf.keras.layers.GlobalAveragePooling2D 文档,tf.keras.layers.GlobalAveragePooling2D 层期望低于输入形状 -

    输入形状:如果data_format='channels_last':4D张量与形状 (batch_size, rows, cols, channels)。如果data_format='channels_first': 形状为(batch_size, channels, rows, cols)的4D张量。

    在这个tensorflow tutorial 中,您将学习如何使用来自预训练网络的迁移学习和微调来对猫和狗的图像进行分类。

    【讨论】:

      猜你喜欢
      • 2021-01-21
      • 1970-01-01
      • 2021-10-18
      • 2020-11-15
      • 1970-01-01
      • 2020-08-01
      • 2021-08-25
      • 2021-05-19
      相关资源
      最近更新 更多