在 Keras 中获得预测 [英] Obtaining a prediction in Keras

查看:38
本文介绍了在 Keras 中获得预测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 Keras 中成功训练了一个简单的模型来对图像进行分类:

I have successfully trained a simple model in Keras to classify images:

model = Sequential()

model.add(Convolution2D(32, 3, 3, border_mode='valid', input_shape=(img_channels, img_rows, img_cols),
                        activation='relu', name='conv1_1'))
model.add(Convolution2D(32, 3, 3, activation='relu', name='conv1_2'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Convolution2D(64, 3, 3, border_mode='valid', activation='relu', name='conv2_1'))
model.add(Convolution2D(64, 3, 3, activation='relu', name='conv2_2'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))

model.add(Dense(nb_classes, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])

我还可以使用

y_pred = model.predict_classes(img, 1, verbose=0)

然而,y_pred 的输出总是二进制的.使用 predict_probapredict 时似乎也是这种情况.我的输出是这种形式

However the output of y_pred is always binary. This also seems to be the case when using predict_proba and predict. My outputs are in this form

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

这行得通,但我希望每个分类都有一个概率百分比,例如

This works OK, but I'd like to have a probability percent for each classification, for example

[[ 0.8  0.1  0.1  0.4]]

我如何在 Keras 中获得这个?

How do I get this in Keras?

推荐答案

Softmax 可能会产生类似one-hot"的输出.考虑以下示例:

Softmax might yield "one-hot" like output. Consider the following example:

# Input; Exponent; Softmax value 
20    485165195  0.99994
 9         8103  0.00002
 5          148  0.00000
10        22026  0.00005
------------------------
# Sum 485195473  1

由于指数函数增长非常快 softmax 从数量级 1 开始产生类似 one-hot 的输出.在 Keras softmax 函数的实现 从输入中减去最大值,但在如果它不会有任何区别.

Since the exponential function grows very fast softmax starts yielding one-hot like output starting from order of magnitude 1. In Keras implementation of the softmax function the maximum value is subtracted from the input, but in the stated above case it won't make any difference.

解决此问题的可能方法:

Possible ways to fix this:

  1. 确保重新缩放输入图像,使像素值介于 01 之间.

向您的模型添加一些regularizers.

这篇关于在 Keras 中获得预测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆