【问题标题】:How to get predicted values in Keras?如何在 Keras 中获得预测值?
【发布时间】:2017-08-09 09:57:05
【问题描述】:

在 Keras 测试样本评估是这样完成的

score = model.evaluate(testx, testy, verbose=1)

这不会返回预测值。有一个方法predict 返回预测值

model.predict(testx, verbose=1)

返回

[ 
[.57 .21 .21]
[.19 .15 .64]
[.23 .16 .60] 
.....
]

testy 是一种热编码,它的值是这样的

[
[1 0 0]
[0 0 1]
[0 0 1]
]

testy 之类的预测值如何转换为热编码?

注意:我的模型是这样的

# setup the model, add layers
model = Sequential()
model.add(Conv2D(32, kernel_size=(3,3), activation='relu', input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(classes, activation='softmax'))

# compile model
model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])

# fit the model
model.fit(trainx, trainy, batch_size=batch_size, epochs=iterations, verbose=1, validation_data=(testx, testy))

【问题讨论】:

    标签: python neural-network keras


    【解决方案1】:

    返回的值是每个类的概率。这些值很有用,因为它们表明了模型的置信度。

    如果你只对概率最高的类感兴趣:

    例如[.19 .15 .64] = 2(因为列表中的索引2最大)

    让模型来吧

    Tensorflow 模型有一个内置方法,可以返回最高类别概率的索引。

    model.predict_classes(testx, verbose=1)
    

    手动操作

    argmax 是一个通用函数,用于返回序列中最大值的索引。

    import tensorflow as tf
    
    # Create a session
    sess = tf.InteractiveSession()
    
    # Output Values
    output = [[.57, .21, .21], [.19, .15, .64], [.23, .16, .60]]
    
    # Index of top values
    indexes = tf.argmax(output, axis=1)
    print(indexes.eval()) # prints [0 2 2]
    

    【讨论】:

    • 返回的值是概率,而不是对数似然。
    • verbose=1 有什么作用?
    • 问题:如何根据索引获取标签名称?谢谢
    【解决方案2】:

    Keras 返回一个 np.ndarray 与类标签的归一化似然。 因此,如果要将其转换为 onehotencoding,则需要找到每行最大似然的索引,这可以通过沿轴 = 1 使用 np.argmax 来完成。然后,要将其转换为 onehotencoding,可以使用 np.eye 功能。这将在指定的索引处放置一个 1。唯一需要注意的是将维度化为适当的行长度。

    a #taken from your snippet
    Out[327]: 
    array([[ 0.57,  0.21,  0.21],
           [ 0.19,  0.15,  0.64],
           [ 0.23,  0.16,  0.6 ]])
    
    b #onehotencoding for this array
    Out[330]: 
    array([[1, 0, 0],
           [0, 0, 1],
           [0, 0, 1]])
    
    n_values = 3; c = np.eye(n_values, dtype=int)[np.argmax(a, axis=1)]
    c #Generated onehotencoding from the array of floats. Also works on non-square matrices
    Out[332]: 
    array([[1, 0, 0],
           [0, 0, 1],
           [0, 0, 1]])
    

    【讨论】:

    • 感谢您的回答!这正是我所需要的!
    【解决方案3】:

    函数predict_classes() 将被弃用。现在,为了获得一种热编码,您只需在 softmax (model.predict(q) > 0.5).astype("int32") 上进行操作。

    【讨论】:

      猜你喜欢
      • 2016-11-06
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多