[已解决] CNN图像分类:它总是给我相同的预测

时间:2020-05-03 06:03:16

标签: python tensorflow neural-network jupyter-notebook cnn

我是该领域的新手,仍然在学习,很抱歉,如果这被认为是愚蠢的问题。 因此,最近我尝试使用Python和TensorFlow学习图像分类。我遵循了一些视频的教程。但是我的代码中存在一些问题,因为当我尝试模型时,验证损失趋于增加,而验证准确性却不断波动。当我尝试预测样本图像时,它一直在给我相同的预测。我的数据集中的图像总计为730张图像。

这是我进行预测的代码:

import cv2
import tensorflow as tf

CATEGORIES = ["Bike", "Car"]
IMAGE_SIZE = 50

def prepare(filepath):
    image_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
    image_array = image_array/255.0
    new_image_array = cv2.resize(image_array, (IMAGE_SIZE,IMAGE_SIZE))
    return new_image_array.reshape(-1, IMAGE_SIZE, IMAGE_SIZE, 1)

model = tf.keras.models.load_model("prototype.model")

prediction = model.predict([prepare('car.jpg')])
print( CATEGORIES[int(prediction[0][0])] )

非常感谢您。

1 个答案:

答案 0 :(得分:1)

我曾经有过类似的问题。由于您需要将图像分类为“自行车”或“汽车”,因此请尝试将最终输出图层更改为

model.add(Dense(2))
model.add(Activation('softmax'))

如果仍然无法正常运行,请尝试使用sparse_categorical_crossentropy作为您的loss