我一直在尝试简单的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.]来说,像p[5]=1,即p[k]=0k这样的概率分布应该没有什么奇怪的...所有条目都在[0, 1]中并且它们总计为1.0

实际上,您犯了一个错误,就是没有对输入数据trainX进行规范化(Keras MNIST MLP example应该是您的指南);加



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


在拟合模型之前,我们得到了(请注意,与您自己的试验相比,拟合期间的损失将更小):

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


看来确实是...

09-25 20:02