Keras 中的图像字幕

数据挖掘 神经网络 深度学习 图像分类 喀拉斯
2021-09-17 20:51:49

我正在尝试从Keras 文档中实现图像字幕系统的演示。从文档中我可以理解培训部分。

max_caption_len = 16
vocab_size = 10000

# first, let's define an image model that
# will encode pictures into 128-dimensional vectors.
# it should be initialized with pre-trained weights.
image_model = VGG-16 CNN definition
image_model.load_weights('weight_file.h5')

# next, let's define a RNN model that encodes sequences of words
# into sequences of 128-dimensional word vectors.
language_model = Sequential()
language_model.add(Embedding(vocab_size, 256, input_length=max_caption_len))
language_model.add(GRU(output_dim=128, return_sequences=True))
language_model.add(TimeDistributedDense(128))

# let's repeat the image vector to turn it into a sequence.
image_model.add(RepeatVector(max_caption_len))

# the output of both models will be tensors of shape (samples, max_caption_len, 128).
# let's concatenate these 2 vector sequences.
model = Merge([image_model, language_model], mode='concat', concat_axis=-1)
# let's encode this vector sequence into a single vector
model.add(GRU(256, 256, return_sequences=False))
# which will be used to compute a probability
# distribution over what the next word in the caption should be!
model.add(Dense(vocab_size))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy', optimizer='rmsprop')

model.fit([images, partial_captions], next_words, batch_size=16, nb_epoch=100)

但是现在我对如何为测试图像生成标题感到困惑。此处输入的是 [image, partial_caption] 对,现在测试图像如何输入部分标题?

1个回答

此示例训练图像和部分标题以预测标题中的下一个单词。

Input: [🐱, "<BEGIN> The cat sat on the"]
Output: "mat"

请注意,该模型不会仅预测下一个单词的标题的整个输出。要构建新的标题,您必须对每个单词进行多次预测。

Input: [🐱, "<BEGIN>"] # predict "The"
Input: [🐱, "<BEGIN> The"] # predict "cat"
Input: [🐱, "<BEGIN> The cat"] # predict "sat"
...

要预测整个序列,相信你需要用到TimeDistributedDense输出层。

Input: [🐱, "<BEGIN> The cat sat on the mat"]
Output: "The cat sat on the mat <END>"

看到这个问题:https ://github.com/fchollet/keras/issues/1029