Keras模型预测相同类别

我是深度学习领域的新手,我尝试训练一个用于图像分类的模型。我使用了一个预训练模型(ResNet50)并添加了自己的层。我用于训练的数据集包含每个类别大约1000张图像,并且我将其分成了训练集和测试集。我的问题是,当我使用model.evaluate(test_set_generator)评估模型时,我得到了大约90%的准确率

如果我加载一张图像并使用model.predict(img)进行预测,结果总是相同的类别

我的生成器如下:

img_height = 128img_width = 128train_datagen = ImageDataGenerator(    rescale=1./255,    shear_range=0.2,    zoom_range=0.2,    horizontal_flip=True)test_datagen = ImageDataGenerator(rescale=1./255)train_generator = train_datagen.flow_from_directory(    data_dir_path,    target_size=(img_height, img_width),    batch_size=16,    shuffle=True,    class_mode='categorical')validation_generator = test_datagen.flow_from_directory(    test_dir_path,    target_size=(img_height, img_width),    batch_size=16,    class_mode='categorical')

我的模型如下:

    base_model = tf.keras.applications.ResNet50(input_shape=(img_height,img_width,3),                                                   include_top=False,                                                   weights='imagenet')    prediction_layer = tf.keras.layers.Dense(5)    model = models.Sequential()    model.add(base_model)    model.add(tf.keras.layers.GlobalAveragePooling2D())    model.add(prediction_layer)    base_learning_rate = 0.0005    model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=base_learning_rate),                  loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),                  metrics=['accuracy'])

我加载图像的方式如下:

test_image = image.load_img(path_to_image, target_size=(128, 128))test_image = image.img_to_array(test_image)test_image = np.expand_dims(test_image, axis=0)

我尝试加载并预测测试集中的每张图像,结果总是相同的(这是一个较小的输出,但大体上每个输出看起来都差不多):

 [[ -38774.88  -228962.86    20932.826 -169404.3   -265980.06 ]] [[ -54851.016 -320424.4     31585.99  -236997.28  -374307.2  ]] [[ -36518.344 -212326.48    18832.361 -156810.19  -244721.2  ]] [[ -31010.965 -196458.73    19816.562 -146228.39  -230922.06 ]] [[ -37712.95  -222710.1     19780.334 -164643.36  -256392.48 ]] 

我不明白为什么评估结果正确而预测结果不正确。我使用model.predict(test_set_generator)预测了test_set_generator,得到的结果看起来对我来说是正确的。结果并不总是相同的。

我尝试更改学习率、增加层数、添加 dropout 层、更改训练轮数和每轮步骤数、使用不同的预训练模型以及不同的批次大小。

我对任何建议表示感谢


回答:

你的模型期望图像值在(0, 1)范围内。

尝试如下操作:

test_image = image.load_img(path_to_image, target_size=(128, 128))test_image = image.img_to_array(test_image) / 255  # < - 除以255test_image = np.expand_dims(test_image, axis=0)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注