Python 基于keras-ResNet50模型的二元分类输出层

Python 基于keras-ResNet50模型的二元分类输出层,python,tensorflow,machine-learning,keras,computer-vision,Python,Tensorflow,Machine Learning,Keras,Computer Vision,我试图使用Keras ResNet50实现来训练二值图像分类模型 我想在不使用转移学习的情况下测试模型,但当我尝试使用简单的密集层(带sigmoid激活)来更改输出层时,我在形状大小方面出现了错误 我的代码是: baseModel= ResNet50(weights=None, include_top=False, classes=2, pooling=max) output = baseModel.output output = layers.Dense(1, activation='sig

我试图使用Keras ResNet50实现来训练二值图像分类模型

我想在不使用转移学习的情况下测试模型,但当我尝试使用简单的密集层(带sigmoid激活)来更改输出层时,我在形状大小方面出现了错误

我的代码是:

baseModel= ResNet50(weights=None, include_top=False, classes=2, pooling=max)

output = baseModel.output
output = layers.Dense(1, activation='sigmoid')(output)

model = keras.models.Model(inputs=baseModel.input, outputs=output)

model.compile(optimizer=Adam(learning_rate=0.0001), loss='binary_crossentropy',  metrics=['accuracy'])
执行此操作时,我出现以下错误:

ValueError: logits and labels must have the same shape ((None, 7, 7, 1) vs (None, 1))
如果我在得到致密层之前添加一个展平层:

ValueError: The last dimension of the inputs to `Dense` should be defined. Found `None`.

我错过了什么?如何更改稠密层的输入形状?

对于您指定的ResNet,Top=False,pooling='max',因此当前模型已向模型添加了最终的max pooling层。因此,请使用下面的代码:您不需要添加展平层,max pooling会为您展平输出

out=basemodel.layers[-1].output 
output = layers.Dense(1, activation='sigmoid')(out)
可以使用model.summary()查看模型结构。
此外,不应使用class=2。当top为false时,不应指定类。

为什么不使用
ResNet50(weights=None,include\u top=True,classes=1)
?使用默认top,而不使用包含的权重不会包括imageNet数据集中用于预测的所有类?好的,我最好阅读文档和“类”为此目的,有很多争论。对于二进制分类,我应该使用1或2?您可以使用带有sigmoid激活函数的1个类,或者使用带有softmax激活函数的2个类。在您的代码中,您有output=layers.Dense(1,activation='sigmoid')(out),但out在哪里定义?我猜你指的是输出。你能提供模型的第一行和最后一行吗?classes is:将图像分类到的可选类数,仅在include_top为True且未指定权重参数时指定。您有Top=False,所以不要为扩展回复指定classesThanks,这有助于我更好地理解修改现有模型的正确方法。这样做基本上与@jakub的评论相同,对吗?不管怎样,我尝试过这种方法,但它给了我同样的错误。我本应该理解这个逻辑,所以我会设法解决它。