Keras预测中的神经网络总是返回概率等于1

2024-04-25 04:43:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习ML,MNIST集上的神经网络,我有预测概率函数的问题。我想接收我的模型预测的概率,但是当我调用函数predict_proba时,我总是收到类似于[0,0,1.,0,0,…]的数组,这意味着模型总是以100%的概率进行预测。在

你能告诉我我的模型出了什么问题,为什么会发生这种情况,以及如何解决它?在

我的模型看起来像:

# Load MNIST data set and split to train and test sets
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# Reshaping to format which CNN expects (batch, height, width, channels)
train_images = train_images.reshape(train_images.shape[0], train_images.shape[1], train_images.shape[2], 1).astype(
    "float32")
test_images = test_images.reshape(test_images.shape[0], test_images.shape[1], test_images.shape[2], 1).astype("float32")

# Normalize images from 0-255 to 0-1
train_images /= 255
test_images /= 255

# Use one hot encode to set classes
number_of_classes = 10

train_labels = keras.utils.to_categorical(train_labels, number_of_classes)
test_labels = keras.utils.to_categorical(test_labels, number_of_classes)

# Create model, add layers
model = Sequential()
model.add(Conv2D(32, (5, 5), input_shape=(train_images.shape[1], train_images.shape[2], 1), activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3), activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(128, activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(number_of_classes, activation="softmax"))

# Compile model
model.compile(loss="categorical_crossentropy", optimizer=Adam(), metrics=["accuracy"])

# Learn model
model.fit(train_images, train_labels, validation_data=(test_images, test_labels), epochs=7, batch_size=200)

# Test obtained model
score = model.evaluate(test_images, test_labels, verbose=0)
print("Model loss = {}".format(score[0]))
print("Model accuracy = {}".format(score[1]))

# Save model
model_filename = "cnn_model.h5"
model.save(model_filename)
print("CNN model saved in file: {}".format(model_filename))

对于加载图像,我使用PIL和NP。 我使用keras的save函数保存模型,并使用load_model from将其加载到另一个脚本中keras.型号那我就打电话来

^{pr2}$

使用它看起来像:

predictor.predict_probability(predictor.load_image_for_cnn(filename))

Tags: ofto模型testaddformatnumberlabels
1条回答
网友
1楼 · 发布于 2024-04-25 04:43:29

请看代码的这一部分:

# Normalize images from 0-255 to 0-1
train_images /= 255
test_images /= 255

加载新图像时不执行此操作:

^{pr2}$

应用与训练集相同的规范化是测试任何新图像的必要条件,如果不这样做,就会得到奇怪的结果。您只需按如下方式规范化图像像素:

def load_image_for_cnn(filename):
    img = Image.open(filename).convert("L")
    img = np.resize(img, (28, 28, 1))
    im2arr = np.array(img)
    im2arr = im2arr / 255.0
    return im2arr.reshape(1, 28, 28, 1)

相关问题 更多 >