【问题标题】:Keras: how to get predicted labels for more than two classesKeras:如何获得两个以上类别的预测标签
【发布时间】:2019-02-02 16:57:45
【问题描述】:

我使用 TensorFlow 后端在 Keras 中实现了一个图像分类器。使用具有两个输出类的数据集,我检查了预测标签如下:

if  result[0][0] == 1:
    prediction ='adathodai'
else:
    prediction ='thamarathtai'

完整代码链接: here

通过三个类,我得到[[0. 0. 1.]] 作为结果输出。如何以 if else 格式检查两个以上类别的预测标签?

【问题讨论】:

    标签: python numpy tensorflow keras


    【解决方案1】:

    对于具有k个标签的多类分类问题,您可以使用model.predict_classes()检索预测类的索引。玩具示例:

    import keras
    import numpy as np
    
    # Simpel model, 3 output nodes
    model = keras.Sequential()
    model.add(keras.layers.Dense(3, input_shape=(10,), activation='softmax'))
    
    # 10 random input data points
    x = np.random.rand(10, 10)
    model.predict_classes(x)
    > array([1, 1, 2, 1, 2, 1, 2, 1, 1, 1])
    

    如果列表中有标签,则可以使用预测的类来获取预测的标签:

    labels = ['label1', 'label2', 'label3']
    [labels[i] for i in model.predict_classes(x)]
    > ['label2', 'label2', 'label3', 'label2', 'label3', 'label2', 'label3', 'label2', 'label2', 'label2']
    

    在后台,model.predict_classes 返回预测中每一行的最大预测类概率的索引:

    model.predict_classes(x)
    > array([1, 1, 2, 1, 2, 1, 2, 1, 1, 1])
    model.predict(x).argmax(axis=-1) # same thing
    > array([1, 1, 2, 1, 2, 1, 2, 1, 1, 1])
    

    【讨论】:

    • 我是在上面实现的,但我得到“只有整数标量数组可以转换为标量索引”的错误。
    • 我认为是因为 predict_class 是二维的。尝试将其重塑为 1d,或仅使用 predict_class[0][i]
    • 我更新了我的答案,最简单的解决方案是使用model.predict_classes
    • 我的形状有尺寸错误。我真的不明白你能解释一下吗。我上传了我的完整代码。谢谢。
    • 它为我的示例生成一些随机数据,10 个数据点和 10 个特征。
    猜你喜欢
    • 2019-11-06
    • 1970-01-01
    • 2021-07-24
    • 2017-09-15
    • 1970-01-01
    • 2017-08-23
    • 2020-05-11
    • 2020-03-07
    • 2018-10-18
    相关资源
    最近更新 更多