如何在 Keras 中获得预测值?

新手上路,请多包涵

在 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))

原文由 asdfkjasdfjk 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 693
2 个回答

返回的值是每个类别的概率。这些值可能很有用,因为它们指示模型的置信水平。

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

例如 [.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]

原文由 Oliver Rice 发布,翻译遵循 CC BY-SA 3.0 许可协议

Keras 返回一个 np.ndarray 具有类标签的归一化可能性。因此,如果您想将其转换为单一编码,则需要找到每行最大似然的索引,这可以通过沿轴 = 1 使用 np.argmax 来完成。然后,要将其转换为单一编码,可以使用 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]])

原文由 Uvar 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题