python - 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 有什么东西吗?
解决方案
推荐阅读
- javascript - 将 $.each 和 $.getJSON 转换为 vanilla javascript
- javascript - 多个 Javascript 文件不起作用
- c++ - 模板函数重载。理解字符
- xml - 使用 XSL 获取第二次出现的值
- authentication - User.Identity.IsAuthenticated 为假,尽管 SignInManager.PasswordSignInAsync() 成功
- java - 如何在蓝牙耳机和手机之间切换麦克风?
- c++ - 链接来自另一个文件的函数时,Qt 上出现错误 LNK 2019
- python - Python Nvidia 在使用 cuml 训练机器学习模型时出现内存错误
- c# - 为什么 Microsoft EmailAddressAttribute 使用的 Regex 接受超过 254 个字符的值?
- reactjs - 构建应用程序时:GET http://localhost ......json 404 (Not Found)