简体   繁体   English

Output 使用 keras ResNet50 model 进行二进制分类的层

[英]Output layer for binary classification using keras ResNet50 model

I'm trying to use the Keras ResNet50 implementation for training a binary image classification model.我正在尝试使用 Keras ResNet50 实现来训练二值图像分类 model。

I want to test the model without using transfer learning but when i try to change the output layer using a simple dense layer with sigmoid activation for the binary classification i got errors regarding shape size.我想在不使用迁移学习的情况下测试 model,但是当我尝试使用一个简单的密集层更改 output 层并为二进制分类激活 sigmoid 时,我得到了关于形状大小的错误。

My code is this:我的代码是这样的:

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'])

Doing this i got this error:这样做我得到了这个错误:

ValueError: logits and labels must have the same shape ((None, 7, 7, 1) vs (None, 1))

If i add a flatten layer before the dense layer i got:如果我在致密层之前添加一个展平层,我得到:

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

What I'm missing here?我在这里缺少什么? How i can change the imput shape for the dense layer?我如何更改致密层的输入形状?

For ResNet you specified Top=False and pooling = 'max' so the Resent model has added a final max pooling layer to the model. So use the code below: You do not need to add a flatten layer, max pooling flattens the output for you.对于 ResNet,您指定了 Top=False 和 pooling = 'max',因此 Resent model 已将最终的最大池化层添加到 model。因此请使用以下代码:您不需要添加展平层,最大池化将 output 展平为你。

out=basemodel.layers[-1].output 
output = layers.Dense(1, activation='sigmoid')(out)

You can use model.summary() to see the model structure.您可以使用 model.summary() 查看 model 结构。 Also you should not use classes=2.你也不应该使用 classes=2。 When top is false classes should not be specified.当 top 为 false 时,不应指定类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM