如何在Keras中获取预测值?

16

在Keras中,测试样本的评估是这样进行的

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

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

model.predict(testx, verbose=1)
返回
[ 
[.57 .21 .21]
[.19 .15 .64]
[.23 .16 .60] 
.....
]

testy 经过独热编码后,其值如下所示。

Translated text:

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))
3个回答

15

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

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

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

返回的值是概率,而不是对数似然。 - Dr. Snoopy
verbose=1是什么意思? - DataMan
1
问题:我如何根据索引获取标签名称?谢谢。 - The-IT

6
Keras返回一个np.ndarray,其中包含类标签的归一化似然值。因此,如果您想将其转换为独热编码,则需要找到每行最大可能性的索引,可以使用np.argmax沿axis=1执行此操作。然后,要将其转换为独热编码,可以使用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]])

谢谢您的回答!这正是我需要的! - matteblack

0

predict_classes()函数将被弃用。现在,为了获得独热编码,你只需要在softmax上执行以下操作:(model.predict(q) > 0.5).astype("int32")


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接