python - Keras 预测在二元问题中只返回一个类

标签 python keras efficientnet

我已经在 Keras 中使用图像生成器针对二进制问题实现了一个 EfficientNet。在测试用例中,当我预测输出时,它返回一个具有一组概率但仅涉及一个类的数组,这里是代码和输出:

test_image_generator = ImageDataGenerator(
rescale=1./255
)
real_test=test_image_generator.flow_from_directory(
directory='/content/real_test',
target_size=(224, 224),
color_mode="rgb",
batch_size=1,
class_mode=None,
shuffle=False,
#seed=42
)

输出是:

real_test.reset()
from keras.models import load_model
efficient_net_custom_model = load_model('model_efficientnet4.h5',compile=False)
pred = efficient_net_custom_model.predict_(real_test, steps = len(real_test), verbose = 1)
print (pred)

现在,当打印 4 个不同图像的预测时,它返回:

[[0.45415235]
[0.52390164]
[0.9999932 ]
[0.99946016]]

基本上每个图像只有一个输出概率(我认为),并且不可能说哪个是实际类别。不是吗? 我该怎么做才能解决这个问题?

谢谢

编辑:

包括模型代码

def output_custom_model(prebuilt_model):
print(f"Processing {prebuilt_model}")
prebuilt = prebuilt_model(include_top=False,
                        input_shape=(224, 224, 3),
                        weights='imagenet')
output = prebuilt.output
output = GlobalMaxPooling2D()(output)
output = Dense(128, activation='relu')(output)
output = Dropout(0.2)(output)
output = Dense(1, activation='sigmoid')(output)

model = Model(inputs=prebuilt.input, outputs=output)
model.compile(optimizer='sgd', loss='binary_crossentropy',
          metrics=METRICS)
return model


efficient_net_custom_model = output_custom_model(EfficientNetB4)
filepath='model_efficientnet4.h5'


efficient_net_history = 
efficient_net_custom_model.fit_generator(train_generator,
                             epochs=20,
                             validation_data=validation_generator,
                             )

最佳答案

在某些类型的网络中,二进制输出只是一个,它代表第一类训练数据。我们假设你的训练数据是这样的:

img1data, class1
img2data, class1
..
imgNdata, class2

您的网络已接受 class1 作为默认类别,给定的结果是该类别的分数。所以这些结果显示了 class1 的分数。

[[0.45415235]
[0.52390164]
[0.9999932 ]
[0.99946016]]

由于二分类,第一个结果显示class1的分数是0.45,所以class2一定是0.55,图像属于class2。 最后的结果显示class1的分数是0.999,所以class2一定是0.0006,图像属于class1。 等等……

您可以编写一个方法来进行这些操作并找到图像所属的类。

def find_class(result):
    if result >= 0.5:
        return "class1"
    else:
        return "class2"

find_class(result[0])

关于python - Keras 预测在二元问题中只返回一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62812563/

相关文章:

Python 检测并检索打开的 csv 文件的文件名

python - 有理数生成器 (Python)

python - Keras:TensorFlow 1.3 模型在 TensorFlow 1.4 或更高版本下失败(错误预测)

python - 为分组数据的 RNN 生成具有特定长度的序列/批处理

python - Keras Transfer-Learning 设置 layers.trainable 为 True 无效

tensorflow - 无法将 EfficientNet 与迁移学习结合使用

python - 如何在列表中构建压缩 for 循环

python - 离线显示MPLD3图

python - 如何在tensorflow中实现提前停止

python - 如何从 Keras 模型中删除前 N 层?