使用keras构建CNN模型,用于不均匀的训练和测试图像文件夹的数据

问题描述 投票:0回答:2

我有两个用于训练和测试图像数据集的文件夹,但它们都包含不同的标签,

training-
         |-a  -img1.png
               img2.png
         |-as -img1.png
               img2.png
         |-are-img1.png
testing -
         |-as -img1.png
         |-and-img1.png
               img1.png

如何使用此数据集创建训练和测试?

我尝试了以下代码,

datagen = ImageDataGenerator(rescale=1. / 255)  
generator = datagen.flow_from_directory(train_data_dir,  
target_size=(img_width, img_height),  
batch_size=batch_size,  
class_mode=None,  
shuffle=False)  

nb_train_samples = len(generator.filenames)  
num_classes = len(generator.class_indices)  

共找到316个图像,分属于68个班级。

generator = datagen.flow_from_directory(  
test_data_dir,  
target_size=(img_width, img_height),  
batch_size=batch_size,  
class_mode=None,  
shuffle=False)  
nb_test_samples = len(generator.filenames)

共找到226个属于48个类的图像。 这是做标签的正确方法吗?因为两个数据集都包含不同的文件夹名称(a,as,are)和(as,and)

当我构建模型时,我的准确率为0%

model = Sequential()  
model.add(Flatten(input_shape=train_data.shape[1:]))  
model.add(Dense(256, activation='relu'))  
model.add(Dropout(0.5))  
model.add(Dense(num_classes, activation='sigmoid'))  

model.compile(optimizer='rmsprop',  
          loss='categorical_crossentropy', metrics=['accuracy'])  

history = model.fit(train_data, 
train_labels,epochs=epochs,batch_size=batch_size,test_data=(test_data, test_labels))  

model.save_weights(top_model_weights_path)  

(eval_loss, eval_accuracy) = model.evaluate(  
 test_data, test_labels, batch_size=batch_size, verbose=1)
python keras deep-learning classification
2个回答
1
投票

我建议你合并两个数据集,将它们混合然后再分割它们以获得具有相同标签的列车和测试数据集。这是正确的标记方式,因为模型需要“看到”所有可能的标签,并将它们与测试数据集进行比较。

为此你可以使用gapcv

安装库:

pip install gapcv

混合文件夹:

from gapcv.utils.img_tools import ImgUtils
gap = ImgUtils(root_path='root_folder{}/training'.format('_t2'))
gap.transf='2to1'
gap.transform()

这将创建一个具有以下结构的文件夹:

root_folder-
         |-a  -img1.png
               img2.png
         |-as -img1.png
               img2.png
         |-are-img1.png
         |-and-img1.png
               img1.png

选项1

使用gapcv将您的数据集预处理到可共享的h5文件中,并用于将图像拟合到keras模型中:

import os
if not os.path.isfile('name_data_set.h5'):
    # this will create the `h5` file if it doesn't exist
    images = Images('name_data_set', 'root_folder', config=['resize=(224,224)', 'store'])

# this will stream the data from the `h5` file so you don't overload your memory
images = Images(config=['stream'], augment=['flip=both', 'edge', 'zoom=0.3', 'denoise']) # augment if it's needed if not use just Images(config=['stream']), norm 1.0/255.0 by default.
images.load('name_data_set')

#Metadata

print('images train')
print('Time to load data set:', images.elapsed)
print('Number of images in data set:', images.count)
print('classes:', images.classes)

发电机:

images.split = 0.2
images.minibatch = 32
gap_generator = images.minibatch
X_test, Y_test = images.test

适合keras模型:

model.fit_generator(generator=gap_generator,
                    validation_data=(X_test, Y_test),
                    epochs=epochs,
                    steps_per_epoch=steps_per_epoch)

为什么要使用gapcv?好吧,它比ImageDataGenerator()更适合模型两倍:)

选项2

使用gapcv对数据集进行混洗和拆分,使用相同的标签:

gap = ImgUtils(root_path='root_folder')

# Tree 2
gap.transform(shufle=True, img_split=0.2)

像往常一样继续使用keras ImageDataGenerator()

文档:

训练notebook混合和拆分文件夹。 gapcv文档。

让我知道事情的后续。 :)


1
投票

Gap对于这些类型的问题非常灵活。我最喜欢的组合分离训练和测试数据集的方法是使用Gap的数据集合并功能(+ =运算符),如下所示:

# load the images from the Training directory
images = Images('name_of_dataset', 'training', config=['resize=(224,224)', 'store'])

# load the images from the Testing directory and merge them with the Training data
images += Images('name_of_dataset', 'testing', config=['resize=(224,224)', 'store'])
© www.soinside.com 2019 - 2024. All rights reserved.