Python 如何在 Keras 中获得预测值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45587378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:08:27  来源:igfitidea点击:

How to get predicted values in Keras?

pythonneural-networkkeras

提问by asdfkjasdfjk

In Keras test sample evaluation is done like this

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

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

This does not return predicted values. There is a method predictwhich return predicted values

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

model.predict(testx, verbose=1)

returns

返回

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

testyis one hot encode and its values are like this

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

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

How can the predicted values like testyor how to convert the predicted values to one hot encoded?

预测值testy如何或如何将预测值转换为一个热编码?

note: my model looks like this

注意:我的模型看起来像这样

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

回答by Oliver Rice

The values being returned are probabilities of each class. Those values can be useful because they indicates the model's level of confidence.

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

If you are only interested in the class with the highest probability:

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

For example[.19 .15 .64]= 2(because index 2 in the list is largest)

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

Let the model to it

让模型给它

Tensorflow models have a built in method that returns the index of the highest class probability.

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

model.predict_classes(testx, verbose=1)

Do it manually

手动操作

argmaxis a generic function to return the index of the highest value in a sequence.

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]

回答by Uvar

Keras returns a np.ndarray with the normalized likelihood of class labels. So, if you want to transform this into a onehotencoding, you will need to find the indices of the maximum likelihood per row, this can be done by using np.argmaxalong axis=1. Then, to transform this into a onehotencoding, the np.eyefunctionality can be used. This will place a 1 at the indices specified. The only care to be taken, is to dimensionalize to appropriate row length.

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