当前位置: 代码迷 >> python >> CNN分类模型。预测给出0和1的数组,而不是概率
  详细解决方案

CNN分类模型。预测给出0和1的数组,而不是概率

热度:29   发布时间:2023-07-14 09:49:45.0

我已经训练了CNN模型对我可以正常工作的数字进行分类。 但是我面临的问题是当我使用命令model.predict()时,它给了我一个0和1而不是概率的数组。

如果我将图像传递给模型,我希望model.predict的输出具有概率。 例如:

假设我传递了一个数字4的图像。期望的输出为[[0.2 0.1 0.1 0.1 0.9 ...]],但是我得到的输出为[[0。 0. 0. 0. 1. 1. 0. 0. 0. 0. 0.]]

我是神经网络的新手。 有人可以帮忙吗? 还要引用它不是过度拟合的情况,也不是0和1的数组是概率(我尝试过乘以100并将类型更改为float32)
下面是我的模型:

(X_train, y_train), (X_test, y_test) = mnist.load_data()
# reshape to be [samples][pixels][width][height]
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32')
# normalize inputs from 0-255 to 0-1
X_train = X_train / 255
X_test = X_test / 255
print(y_train)
# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
print(y_train)
print(num_classes)

# define the larger model
def larger_model():
    # create model
    model = Sequential()
    model.add(Conv2D(30, (5, 5), input_shape=(1, 28, 28), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Conv2D(15, (3, 3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.2))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dense(50, activation='relu'))
    model.add(Dense(num_classes, activation='softmax'))
    # Compile model
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

#build the model
model = larger_model()
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200)

一个可能的原因可能是测试数据的预处理方式与火车/ VAL数据的预处理方式不同。 您需要确保在调用model.predict()之前将测试图像像素值在0-1之间进行归一化 ,因为模型是在归一化图像上训练的。

  相关解决方案