ValueError:图层global_average_pooling2d的输入0与该图层不兼容:预期ndim = 4,找到的ndim = 2收到的完整图形:[无,128]

问题描述

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

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,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]

任何人都可以帮助我,从错误中告诉我什么以及如何解决此问题。 谢谢!

解决方法

如果您共享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,cols)的4D张量。

在此tensorflow tutorial中,您将学习如何通过使用来自预先训练的网络的转移学习以及微调来对猫和狗的图像进行分类。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...