首页 > 解决方案 > Tensorflow:使用 ImageDataGenerator 时训练不正确。尽管模型仅输出 1 个类别,但仍提供 99% 的训练准确度

问题描述

我正在创建一个对人和马进行分类的简单模型。在 Google Colab 上执行此操作。

我正在使用以下两个 URL 来训练和验证数据集。 https://storage.googleapis.com/laurencemoroney-blog.appspot.com/horse-or-human.zip https://storage.googleapis.com/laurencemoroney-blog.appspot.com/validation-horse-or-human 。压缩

我将数据集保存在我的 tmp 文件夹中,然后为它们创建了图像数据生成器

train_generator = train_datagen.flow_from_directory('/tmp/horse-or-human', target_size=(300, 300), color_mode='rgb',\
                                                    class_mode='binary', batch_size=128)
validation_generator = validation_datagen.flow_from_directory('/tmp/validation-horse-or-human', target_size=(300, 300), \
                                                       color_mode='rgb', class_mode='binary', batch_size=128)

这是我创建和编译的模型

i = Input(shape=(300, 300, 3))

#Convolution 1
x = Conv2D(8, (3, 3), strides=(1, 1), padding='valid', activation='relu')(i)
x = BatchNormalization()(x)
x = MaxPool2D((2, 2), strides=(2, 2))(x)

#Convolution 2
x = Conv2D(16, (3, 3), strides=(1, 1), padding='valid', activation='relu')(x)
x = BatchNormalization()(x)
x = MaxPool2D((2, 2), strides=(2, 2))(x)

x = Flatten()(x)

x = Dense(100, activation='relu')(x)
x = Dropout(rate=dropout_rate)(x)
# x = Dense(100, activation=LeakyReLU(alpha=alpha))(x)
# x = Dropout(rate=dropout_rate)(x)
x = Dense(1, activation='sigmoid')(x)

model = Model(i, x)

model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])

然后我开始使用这两个生成器进行训练

history = model.fit(train_generator, steps_per_epoch=8, epochs=5, validation_data=validation_generator)

在此处输入图像描述

从训练来看,应该很明显它已经过拟合了。同样从验证准确度,我知道它输出的输入概率只有 1 类(因为 1 类占总数的 51.31%)。训练集和验证集的进一步 model.predict 测试证实了这一点。

我检查了两个生成器,看看它们中的一个是否只向模型提供 1 个类数据。事实并非如此。

labels = validation_generator[7][1]
print(len(labels[labels==0]))    #Output is 64 out of 128, Output is 64 also for labels==1

当模型仅返回 1 个类时,模型如何在训练时获得 100% 的训练准确度?我缺少 train_generator 有什么东西吗?

标签: pythonmachine-learningkerasdeep-learningtensorflow2.0

解决方案


推荐阅读