我正在尝试从经过训练的对象检测模型中创建可视化解释,如GradCAM。为了实现该算法,我需要访问中间张量并计算到特征映射的梯度。冻结的推理图似乎省略了许多信息,如张量名称,在使用导出脚本(exporter_main_v2.py)之后,因此我无法访问特定的张量。
使用“训练模型”(在转换到pb之前),我也很难访问特定的张量,因为模型不是普通的Keras/Tensorflow,而是在SSDMetaArch、SSDMobileNetFeatureExtractor等类中抽象出模型的一部分,这些类隐藏了模型的实际实现。
知道怎么解决这个问题吗?
发布于 2021-09-29 08:23:08
最后,事实证明这比原来想象的要容易得多。利用SSDMetaArch类型的检测模型,通过指定一个输入层并使用检测模型的各个构建块,即特征提取器和盒预测器,可以将模型重新创建为keras模型。
input_layer = tf.keras.layers.Input(input_shape)
feature_maps = detection_model.feature_extractor(input_layer)
outputs = detection_model._box_predictor(feature_maps)
outputs['feature_maps'] = feature_maps # add feature_maps to outputs to access them with GradientTape
cam_model = tf.keras.Model(inputs=[input_layer], outputs=outputs)现在,可以使用GradientTape计算从任何输出神经元到特征映射的梯度。在下面的示例中,计算了从具有最高置信度的边界盒的检测分数到特征映射的梯度。
with tf.GradientTape() as tape:
input_image = image[None, ...]
predictions = cam_model(image)
feature_maps = predictions['feature_maps']
tape.watch(feature_maps)
idx = tf.argmax(predictions['class_predictions_with_background'][0])[query_class]
output_neuron = predictions['class_predictions_with_background'][0, idx, 0]
grads = tape.gradient(output_neuron, feature_maps)https://datascience.stackexchange.com/questions/102567
复制相似问题