在 Keras 分类中实现注意力

The*_*AEZ 5 python keras tensorflow recurrent-neural-network attention-model

我想实现对训练有素的图像分类 CNN 模型的关注。例如,有 30 个类,使用 Keras CNN,我为每个图像获得预测类。但是,要可视化预测结果的重要特征/位置。我想在 FC 层之后添加一个 Soft Attention。我尝试阅读“展示、出席和讲述:具有视觉注意的神经图像字幕生成”以获得类似的结果。但是,我无法理解作者是如何实现的。因为我的问题不是图像标题或文本 seq2seq 问题。

我有一个图像分类 CNN,想提取特征并将其放入 LSTM 以可视化软注意力。虽然我每次都卡住了。

我采取的步骤:

  1. 加载CNN模型
  2. 从单个图像中提取特征(但是,LSTM 会检查同一图像并删除图像中的一些补丁)

我采取的步骤:

  1. 加载 CNN 模型(我之前已经训练了 CNN 进行预测)
  2. 从单个图像中提取特征(但是,LSTM 会检查同一图像并删除图像中的一些补丁)

执行以下步骤后卡住:

  1. 用软注意力创建 LSTM
  2. 获取单个输出

我正在使用具有 TensorFlow 背景的 Keras。使用 ResNet50 提取 CNN 特征。图像为 224x224,FC 层有 2048 个单位作为输出形状。

#Extract CNN features:

base_model = load_model(weight_file, custom_objects={'custom_mae': custom_mae})
last_conv_layer = base_model.get_layer("global_average_pooling2d_3")
cnn_model = Model(input=base_model.input, output=last_conv_layer.output)
cnn_model.trainable = False
bottleneck_features_train_v2 = cnn_model.predict(train_gen.images)


#Create LSTM:    

seq_input = Input(shape=(1, 224, 224, 3 ))
encoded_frame = TimeDistributed(cnn_model)(seq_input)
encoded_vid = LSTM(2048)(encoded_frame) 
lstm = Dropout(0.5)(encoded_vid)

#Add soft attention

attention = Dense(1, activation='tanh')(lstm)
attention = Flatten()(attention)
attention = Activation('softmax')(attention)
attention = RepeatVector(units)(attention)
attention = Permute([2, 1])(attention)


#output 101 classes
predictions = Dense(101, activation='softmax', name='pred_age')(attention)
Run Code Online (Sandbox Code Playgroud)

我期望的是从最后一个 FC 层给出图像特征。将软注意力添加到 LSTM 以训练注意力权重,并希望从输出中获取一个类并将软注意力可视化以了解系统在进行预测时正在查看的位置(与论文中的软注意力可视化类似)。

由于我是注意力机制的新手,我做了很多研究,但找不到对我的问题的解决方案/理解。我想知道我是否做得对。