如何使用keras(tf.keras.utils.Sequence)为多个输入创建自定义数据生成器?

uqjltbpv  于 2022-11-13  发布在  其他
关注(0)|答案(1)|浏览(206)

该模型有四个输入,一个输出。在这四个输入中,两个是数字数据,一个是分类数据,另一个是图像数据。输出是二进制的(0或1)。我需要创建一个自定义的数据生成器,它可以从数据框架中获取这些输入,并将这些输入输入到模型中。
我把图像输入CNN模型。图像数据集太大了,不使用数据生成器就无法输入模型。
我怎样才能把这些图像批量输入模型呢?如果我能学会如何根据任何特定的模型创建自定义的数据生成器,这将是非常有帮助的。
谢谢你,谢谢你

8iwquhpp

8iwquhpp1#

您可能不需要使用tf.keras.utils.Sequence。我认为您可以使用ImageDataGenerator.flow_from_dataframe来实现它。让我们假设您有一个名为df的 Dataframe ,其中包含以下列:

column 0 is the filepaths column that contains the full path to the image file
column 1 first numerical data column let it have column name num1
column 2 2nd numerical data column let it have column name num2
column 3 is the categorical data column, give it the column name cat

现在创建一个表单列表

input_list=[num1, num2, cat]

现在创建生成器

bs=30 # batch_size
img_size=(224,224) # image size to use
gen=ImageDataGenerator(rescale=1/255)
train_gen=gen.flow_from_dataframe(df, xcol='filepaths', y_col=input_list, target_size=img_size, batch_size=bs, shuffle=True, seed=123, class_mode='raw', color_mode='rgb')

注意确保class_mode设置为'raw'。要测试生成器,请尝试以下代码

images, labels=next(train_gen)
print (images.shape) # should get (30, 224,224,3)
print (labels.shape) # should get (30, 3)

我已经使用了这种方法,其中input_list中的所有输入列都是数值型的,并且能够训练一个模型。我不确定这种方法是否适用于数值型和分类型输入的混合,但我认为它适用。注意,当然,您可能首先希望使用sklearn的train_test_split将df划分为train_df、test_df和valid_df。在这种情况下,您将希望创建一个train,测试和有效的生成器。2在测试生成器中设置shuffle=False。3让我知道这是否有效。

相关问题