python - 无论我输入什么图像,我的 CNN 模型都只能预测第一类

标签 python tensorflow machine-learning keras conv-neural-network

我是机器学习的初学者,并按照一门 ML 类(class)中的模板来训练猫和狗的图像以对其进行分类。

如果我在模型中加载要预测的图像,无论如何,预测都会成为我在最后的列表platetype中定义的第一个类。

我这样做是为了对其他类型的图像进行分类,但是我对该数据集遇到了相同的错误,因此我考虑使用经典的猫和狗数据集。

我想预测我提供给训练模型的文本图像是否具有精美的文本或标准文本字体。

这是我的代码。

#create classifier 
classifier = Sequential()

#adding convolution layer
classifier.add(Convolution2D(32, 3, 3, input_shape = (64, 64, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2,2), strides = (2,2)))
classifier.add(Convolution2D(32, 3, 3, activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2,2), strides = (2,2)))
classifier.add(Flatten())
classifier.add(Dense(output_dim = 128, activation = 'relu'))
classifier.add(Dense(output_dim = 1, activation = 'sigmoid'))


# In[54]:

#compiling
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

# In[55]:
#making Image size same
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1./255)

training_set = train_datagen.flow_from_directory(
        'D:/Third Year/kaggle/cats/New Data/Convolutional_Neural_Networks/dataset/training_set',
        target_size=(64, 64),
        batch_size=32,
        class_mode='binary')

test_set = test_datagen.flow_from_directory(
        'D:/Third Year/kaggle/cats/New Data/Convolutional_Neural_Networks/dataset/test_set',
        target_size=(64, 64),
        batch_size=32,
        class_mode='binary')
print('TRAINING:',training_set)
print('TEST: ',test_set)


# In[56]:

#checking if already a weight file exists. if it does loads it into the model
if os.path.isfile("modelCNN_CD.h5") :
        classifier.load_weights("modelCNN_CD.h5")

#checkpoint saves the model.
filepath="modelCNN_CD.h5"       
checkpoint1 = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')


classifier.summary()
classifier.fit_generator(
        training_set,
        steps_per_epoch=8000,
        epochs=25,
        validation_data=test_set,
        validation_steps=2000,callbacks=[checkpoint1,])


# In[67]:
# load the model
#model = VGG16()
# load an image from file
image = load_img('D:/Third Year/kaggle/cats/New Data/Convolutional_Neural_Networks/dog.4029.jpg', target_size=(64, 64))
# convert the image pixels to a numpy array
image = img_to_array(image)
# reshape data for the model
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))

yhat = classifier.predict(image)
print(yhat)

import numpy as np
print(platetype[np.argmax(yhat)])

# In[57]:

platetype = ['Cat','Dog']

# In[9]:

from keras.models import load_model
classifier = load_model('modelCNN_LP.h5')

最佳答案

您的预测器是否总是返回 0 作为类别?

我问的原因是我遇到了同样的问题,问题出在 "platetype[np.argmax(yhat)]" 以及您正在使用二进制类模式分类的事实。

argmax 将返回结果的索引位置,但是当您使用二进制类并且在最后一层中您有 1 个密集。它只会返回一个值,因此它将始终返回第一个类(0 作为索引位置)。由于网络只设置,返回一类。

有 2 种解决方案,这取决于您更喜欢哪一种:

  1. 是将训练和测试生成器的 class_mode 更改为“分类”,将最终的密集层从 1 更改为 2,以便这将返回两个类的分数/概率。因此,当您使用 argmax 时,它将返回最高分数的索引位置,指示它预测的是哪个类别。
  2. 另一种方法是坚持你所拥有的,但你必须改变确定类别的方式。您将使用分数,因此这将是一个列表。您需要访问分数并根据分数确定模型预测的类别。也许有人可以澄清这一点,因为我没有使用过这种方法,而且我不确定。

希望这有帮助!我遇到了和你一样的问题,这为我解决了这个问题(我选择了选项 1)。

请告诉我它是否对您有用。

关于python - 无论我输入什么图像,我的 CNN 模型都只能预测第一类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52960555/

相关文章:

python - super() 返回的 super 对象的类型是什么?

python - OS X 上的 Tensorflow ImportError

python - Tensorflow GAN 没有为任何变量提供梯度

algorithm - 设计相似度表

php - 读取 .csv 文件 PHP-ML

python - 每个 bin 中数据的 "label fraction"的 2D 直方图颜色

python - 初始化 SQLite3 数据库的多行

python - 如何正确使用 Python 中的 multiprocessing 模块?

python - tf.keras 和 tf.python.keras 有什么区别?

machine-learning - 类别数量不断增加的多类别分类