python - Keras:结合数据生成器来处理图像+文本

标签 python tensorflow keras

我正在开发一种多标签分类模型,尝试使用 Keras 将两个模型(CNN 和文本分类器)组合成一个模型,并将它们一起训练,如下所示:

#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 为我提供了图像和标签数据,我现在正在寻找一种解决方案来将此生成器与一个生成器结合起来,该生成器允许我另外提供相应的文本向量

最佳答案

您可能需要考虑编写自己的生成器(利用 Keras 的 Sequence 对象来允许多处理)而不是修改 ImageDataGenerator代码。来自 Keras 文档:

class CIFAR10Sequence(Sequence):

    def __init__(self, x_set, y_set, batch_size):
        self.x, self.y = x_set, y_set
        self.batch_size = batch_size

    def __len__(self):
        return int(np.ceil(len(self.x) / float(self.batch_size)))

    def __getitem__(self, idx):
        batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size]
        batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size]

        return np.array([
            resize(imread(file_name), (200, 200))
               for file_name in batch_x]), np.array(batch_y)

您可以将标签、图像路径和文本文件路径放在单个 pandas 数据框中,并修改 __getitem__上面的方法让你的生成器同时生成所有三个:一个 numpy 数组列表 X其中包含所有输入,一个 numpy 数组 Y其中包含输出。

关于python - Keras:结合数据生成器来处理图像+文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51697695/

相关文章:

python - 'SparseTensor' 对象不是可订阅的 keras

python - Pandas 两个分组的 DataFrame 列的简单关联

python - 返回一个字符串,如何格式化输出

python - Keras 中 sigmoid 激活函数的使用

neural-network - 端到端训练 CNN-LSTM?

python - 带有用于可变长度输入的屏蔽层的 Keras lstm

tensorflow - keras 中预训练的目标检测模型

python - 为什么 __setattr__ 的 "name"参数包含类,而 __getattr__ 不包含?

python - 给定 2d pdf 生成随机值

python - 资源耗尽: OOM when allocating tensor only on gpu