首页 > 解决方案 > Keras:在 flow_from_directory() 中使用多个目录

问题描述

train/对于大多数数据集,图像是独立的,将它们随机分成 80%-20% 到和test/目录以供 Keras 使用是没有问题的flow_from_directory(). 但是,对于我的应用程序,情况并非如此。例如,假设我想对人们是在微笑还是在皱眉进行分类。我没有使用在网上随机找到的数千张微笑和皱眉的照片,而是招募了 10 名志愿者,并为每个志愿者拍摄了 100 张微笑和皱眉的照片。在我最终的应用程序中,我想对新用户是微笑还是皱眉进行分类。为了公平测试,我必须确保我的测试集中没有用户的图像出现在训练集中(否则我的分类器可能会选择特定于该用户的特征,这是我不想要的),所以我省略了一个用户并在其他九个用户上训练我的模型。我的目录结构如下:

user1/
    smile/
        100 images
    frown/
        100 images
...
user10/
    smile/
        100 images
    frown/
        100 images

有什么方法可以将 Kerasuser1/作为test/目录并user2/作为user10/目录提供train/

注意:我的问题不是这个问题的重复,因为这涉及并行输入多个目录以用于单个训练示例。我的问题与类似,但这个问题写得非常糟糕,我不确定用户是否问我同样的问题。

标签: pythonkeras

解决方案


@TimD1 我相信如果您稍微改变目录结构的方式,如下所示,您可以在 keras 中使用 flow_from_directory。

Test_Directory/
             User1/
                  200 images here(don't create separate folders for smile and frown here) 

Train_Directory/
               Smile/
                     All the images for smile for users 2-10 
               Frown/
                     All the images for frown for users 2-10    

一旦你有了这个目录结构,你就可以使用下面的代码并根据你的应用程序的需要更改细节。重要的是目录的路径以及是否要创建验证集。

from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale = 1./255,
                               shear_range = 0.1,
                               zoom_range = 0.1,
                               validation_split=0.1 
                               ) # validation set of 10% from training data

test_datagen = ImageDataGenerator(rescale = 1./255,
                               shear_range = 0.1,
                               zoom_range = 0.1,
                               )

training_set = train_datagen.flow_from_directory('desktop/Train_Directory',target_size = (64,64),shuffle=True,
                                             seed=13,batch_size = 32,class_mode = 'binary',
                                             subset="training")

val_set = train_datagen.flow_from_directory('desktop/Train_Directory',target_size = (64,64),shuffle=True,
                                             seed=13,batch_size = 32,class_mode = 'categorical',
                                             subset="validation")

test_set= test_datagen.flow_from_directory('desktop/Test_Directory',target_size = (input_size,input_size),shuffle=False,
                                             seed=13,class_mode=None,batch_size = 1)# for test the batch size should be set to 1 and the shuffle should be false to get the correct number of outputs in the right order your predicting the test labels

在此之后使用fit_generator训练和predict_generator测试。如果您选择设置shuffle为 True fortest_set那么您需要test_set.reset()在预测测试标签之前做


推荐阅读