我正在研究一个多标签分类模型,我试图将两个模型,一个CNN和一个文本分类器组合成一个使用Keras的模型并将它们一起训练,如下所示:
#cnn_model is a vgg16 model
#text_model looks as follows:
### takes the vectorized text as input
text_model = Sequential()
text_model .add(Dense(vec_size, input_shape=(vec_size,), name='aux_input'))
## merging both models
merged = Merge([cnn_model, text_model], mode='concat')
### final_model takes the combined models and adds a sofmax classifier to it
final_model = Sequential()
final_model.add(merged)
final_model.add(Dense(n_classes, activation='softmax'))
因此,我正在使用ImageDataGenerator来处理图像和相应的标签 .
对于图像,我使用自定义辅助函数,通过pandas数据帧提供的路径将图像读入模型 - 一个用于训练(df_train),另一个用于验证(df_validation) . 数据框还在“label_vec”列中提供模型的最终标签:
# From https://github.com/keras-team/keras/issues/5152
def flow_from_dataframe(img_data_gen, in_df, path_col, y_col, **dflow_args):
base_dir = os.path.dirname(in_df[path_col].values[0])
print('## Ignore next message from keras, values are replaced anyways')
df_gen = img_data_gen.flow_from_directory(base_dir, class_mode = 'sparse', **dflow_args)
df_gen.filenames = in_df[path_col].values
df_gen.classes = numpy.stack(in_df[y_col].values)
df_gen.samples = in_df.shape[0]
df_gen.n = in_df.shape[0]
df_gen._set_index_array()
df_gen.directory = '' # since we have the full path
print('Reinserting dataframe: {} images'.format(in_df.shape[0]))
return df_gen
from keras.applications.vgg16 import preprocess_input
train_datagen = keras.preprocessing.image.ImageDataGenerator(preprocessing_function=preprocess_input) horizontal_flip=True)
validation_datagen = keras.preprocessing.image.ImageDataGenerator(preprocessing_function=preprocess_input)#rescale=1./255)
train_generator = flow_from_dataframe(train_datagen, df_train,
path_col = 'filename',
y_col = 'label_vec',
target_size=(224, 224), batch_size=128, shuffle=False)
validation_generator = flow_from_dataframe(validation_datagen, df_validation,
path_col = 'filename',
y_col = 'label_vec',
target_size=(224, 224), batch_size=64, shuffle=False)
现在我试图向模型提供我的单热编码文本向量(即 [0,0,0,1,0,0]
),它们也存储在pandas数据帧中 .
由于我的train_generator为我提供了图像和标签数据,我现在正在寻找一种解决方案,将这个发生器与一个发生器结合起来,这使得我可以另外输入相应的文本向量
1 回答
您可能需要考虑编写自己的生成器(使用Keras的
Sequence
对象来允许多处理)而不是修改ImageDataGenerator
代码 . 来自Keras文档:您可以在单个pandas数据帧中拥有标签,图像路径和文本文件路径,并从上面修改
__getitem__
方法,让您的生成器同时生成所有这三个:一个numpy数组列表X
包含所有输入,一个包含输出的numpy数组Y
.