【问题标题】:How to get the name of the class predicted by keras trained model for categorical output?如何获取 keras 训练模型预测的类别名称以进行分类输出?
【发布时间】:2020-05-03 13:59:24
【问题描述】:

我有一个训练有素的 CNN 模型,它可以预测 5 种情绪中的一种:愤怒、厌恶、恐惧、中性或悲伤。 我正在使用

ImageDataGenerator(rescale = 1./255,
                      shear_range=0.1,
                      zoom_range=0.1,
                      horizontal_flip=True)

low_from_directory('../large-dataset-copy/training/',
                            color_mode='grayscale',
                            target_size=(48,48),
                            class_mode = 'categorical',
                            batch_size = 32)

用于读取和转换图像。

训练后我不知道如何提取模型预测的对应类。 我使用下面的代码来读取和转换图像:

def test_data(img_path):
    img_array = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
    new_img = cv2.resize(img_array,(48,48))
    return new_img.reshape(-1,48,48,1)

img = test_data('Abdullah_Gul_0006.jpg')
emotionClassifier = k.models.load_model('moedel.h5',compile=False)
emotion = emotionClassifier.predict(img)
print(emotion)

这是我得到的输出总是[[0. 1. 0. 0. 0.]]

print(test_data.class_indices) 的输出也是 {'anger': 0, 'disgust': 1, 'fear': 2, 'neutral': 3, '悲伤':4}

【问题讨论】:

    标签: keras label conv-neural-network


    【解决方案1】:

    由于在 flow_from_directory 方法中将 class-mode 设置为“categorical”,因此结果将在 2D one-hot 编码标签数组中返回。您得到的结果 [0,1,0,0,0] 意味着图片标签是“厌恶”,因为它是 class_indices 列表中的第二个。

    顺便说一句,如果您使用的是顺序模型,您应该使用 predict_classes 而不是 predict 来获得结果。

    【讨论】:

    • 谢谢。在 90% 的情况下获得相同输出的一个原因可能是模型过度拟合?准确率似乎很高。下一个代码 scores =emotionClassifier.evaluate(validation_data) print("%s: %.2f%%" % (emotionClassifier.metrics_names[1], scores[1]*100)) 打印出 88 %
    • 可能是。我还会交叉检查标签以确保使用正确的信息来训练系统。顺便说一句,如果我的回答对您有帮助,您可以接受。
    • 您可能还应该检查训练集和验证集中的类不平衡情况。
    猜你喜欢
    • 2019-01-31
    • 2017-07-16
    • 2020-09-07
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多