2017-08-09 104 views
2

在Keras試樣評估這樣如何獲得預測Keras值?

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

這不返回預測值進行。有其返回預測值

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的預測值或方法predict如何將預測值轉換爲一個熱編碼?

:我的模型看起來像這樣

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

回答

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] 
+0

返回的值是概率值,而不是對數似然值。 –

+0

@MatiasValdenegro謝謝你用來捕獲 –

+0

什麼詳細= 1嗎? – Eddy

1

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