为什么 softmax 总是提供 1.0 的概率?

Why does softmax provide always a probability of 1.0?

我一直在尝试使用简单的 mnist 示例。抱歉,如果问题是最基本的问题。

from keras.datasets import mnist
from keras.layers import Input, Conv2D, Dense
from keras.models import Sequential
from keras.utils import np_utils

def myModel():

    model= Sequential()
    layer1 = Dense(1024, input_shape=(784,), activation='relu')
    layer2 = Dense(512, activation='relu')
    layer3 = Dense(10, activation='softmax')
    model.add (layer1)
    model.add (layer2)
    model.add(layer3)
    model.compile(loss='categorical_crossentropy', optimizer='adam')
    return model


if __name__ == '__main__':
    print "Inside the main function "
    model = myModel()
    (trainX, trainY), (testX, testY) = mnist.load_data()
    print ("TrainX shape is ", trainX.shape)
    trainX = trainX.reshape(trainX.shape[0], trainX.shape[1] * trainX.shape[2])
    trainY = np_utils.to_categorical(trainY, 10)
    model.fit(trainX, trainY, batch_size=200, epochs=1)

    print ("Let's predict now..")
    print ("Shae of x and shape of 100" , trainX.shape, trainX[10].shape)
    result = model.predict(trainX[100].reshape(1,784 ))
    print result

    import matplotlib.pyplot as plt 
    plt.subplot(2,2,1)
    plt.imshow(trainX[1100].reshape(28,28))
    plt.show()

最后一层的输出值为

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

我该如何解释这个结果?。这不是结果的概率分布吗?。如果不是我怎么得到相同的?

理论上,像[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]这样的概率分布应该没有什么奇怪的,即对于所有其他k...所有条目都在 [0, 1] 中,它们总计为 1.0.

实际上,你犯了一个错误,没有规范化你的输入数据trainXKeras MNIST MLP example 应该是你的指南);添加

trainX = trainX.astype('float32')
trainX /= 255

在拟合模型之前,我们得到(注意与您自己的试验相比,在拟合过程中 loss 会小得多):

result = model.predict(trainX[100].reshape(1,784 ))
# result:
array([[6.99907425e-04, 7.85773620e-04, 1.73144764e-03, 9.31426825e-04,
        5.75593032e-04, 9.49266493e-01, 1.22108115e-02, 1.03891856e-04,
        3.18745896e-02, 1.82012399e-03]], dtype=float32)

结果好吗?

np.argmax(result)
# 5

np.argmax(trainY[100])  # true label
# 5

看来确实是...

有两个问题,一个在您的标题中,一个在 body 中。对于第一个,是的,softmax 总和为 1。回想一下 it is defined:

exp(x) / ∑ exp(x)

由于归一化,总和为 1。在训练开始时,输出应该是随机的并且大致均匀,经过良好的训练后,您会期望得到像您一样的输出;至少对于清晰的图像。对于其他图像,您可能会得到 [0,0.3, 0.7, 0,…],其中可以看到图像的两个(或更多)标签。