如何获得Keras的预测值?

时间:2017-08-09 09:57:05

标签: python neural-network 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))

3 个答案:

答案 0 :(得分:10)

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

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

例如2 = model.predict_classes(testx, verbose=1) (因为列表中的索引2最大)

让模型

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

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]

手动执行

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

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;

public class AdController : MonoBehaviour {

    // Use this for initialization
    void Start () {
        RequestBanner ();
    }

    private void RequestBanner() {
        print ("running admob");

        #if UNITY_EDITOR
        string adUnitId = "unused";
        #elif UNITY_ANDROID
        string adUnitId = "ca-app-pub-3940256099942544/6300978111";
        #elif UNITY_IPHONE
        string adUnitId = "INSERT_IOS_BANNER_AD_UNIT_ID_HERE";
        #else
        string adUnitId = "unexpected_platform";
        #endif

        // Create a 320x50 banner at the top of the screen.
        BannerView bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Bottom);
        // Create an empty ad request.
        //AdRequest request = new AdRequest.Builder().Build();
        AdRequest request = new AdRequest.Builder()
        .AddTestDevice(AdRequest.TestDeviceSimulator)       // Simulator.
        .AddTestDevice(SystemInfo.deviceUniqueIdentifier)  // My test device.
        .Build();

        // Load the banner with the request.
        bannerView.LoadAd(request);
        bannerView.Show ();
    }
}

答案 1 :(得分:3)

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

答案 2 :(得分:0)

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