如何用 keras.layers.Layer 实现 Grad-CAM?
解读
Grad-CAM(Gradient-weighted Class Activation Mapping)是面试高频考点,核心目的是“不改动原模型权重,只利用梯度与特征图,生成可解释的热力图”。
国内面试官通常从三个维度打分:
- 是否真正继承
keras.layers.Layer并做到“即插即用”; - 是否掌握 TensorFlow 2.x 的梯度Tape机制,避免
model.fit外手工求导的 rookie 错误; - 是否能在 batch 维度、混合精度、TPU/GPU 多场景下鲁棒运行。
因此,答案必须给出“自定义层 + 重写 call + 静态图兼容”的完整范式,而不是脚本式 demo。
知识点
tf.GradientTape(persistent=True)的 nested 用法与显式 watch 机制;- Keras 层生命周期:
build()仅创建权重,call()写前向,get_config()保证序列化; - 特征图梯度回传后,沿 H、W 做 Global Average Pooling 得到 α_k^c,再与特征图加权求和;
- 热力图后处理:ReLU 过滤负值、归一化到 0~255、双线性插值 resize 到原图尺寸;
- 层内部禁止出现
numpy运算,全部用tf.raw_ops或tf.image保证图模式兼容; - 多输出网络需用
tf.stop_gradient冻结分支,防止梯度回传干扰主网络; - 量化/混合精度场景下,梯度类型为
tf.float16,需在层内强制tf.cast到float32再计算,否则出现 NaN; - 保存模型时,自定义层必须实现
get_config并在custom_objects中注册,否则model.save('xxx')后无法重新加载。
答案
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
class GradCAM(layers.Layer):
"""
即插即用 Grad-CAM 层。
用法:
grad_cam = GradCAM(model, last_conv_layer_name)
heatmap = grad_cam([image_tensor, class_id])
"""
def __init__(self, model, last_conv_layer_name, **kwargs):
super().__init__(**kwargs)
self.model = model
# 定位最后一层卷积
self.conv_layer = self.model.get_layer(last_conv_layer_name)
# 新建一个“截断”模型:输入与原模型相同,输出为 (conv_features, logits)
self.grad_model = keras.Model(
inputs=model.inputs,
outputs=[self.conv_layer.output, model.output]
)
def call(self, inputs, training=None):
"""
inputs: [image_tensor, class_id]
image_tensor: shape [B, H, W, C]
class_id: shape [B, 1] tf.int32,若为 None 则取预测 top1
return: heatmap [B, H, W, 1] 值域 [0, 1]
"""
images, class_id = inputs
B = tf.shape(images)[0]
with tf.GradientTape() as tape:
tape.watch(images)
conv_out, logits = self.grad_model(images, training=False) # [B, h, w, k], [B, num_cls]
if class_id is None:
class_id = tf.argmax(logits, axis=-1, output_type=tf.int32)[:, tf.newaxis]
# 构造索引,取出对应类别得分
idx = tf.stack([tf.range(B, dtype=tf.int32), tf.squeeze(class_id, axis=1)], axis=1)
score = tf.gather_nd(logits, idx) # [B]
# 求梯度: [B, h, w, k]
grads = tape.gradient(score, conv_out)
# 全局平均池化 -> α [B, k]
alpha = tf.reduce_mean(grads, axis=[1, 2])
# 加权求和: [B, h, w, k] * [B, k] -> [B, h, w]
cam = tf.einsum('bhwk,bk->bhw', conv_out, alpha)
# ReLU + 归一化
cam = tf.nn.relu(cam)
cam = cam / (tf.reduce_max(cam, axis=[1, 2], keepdims=True) + 1e-8)
# resize 到原图尺寸
cam = tf.image.resize(cam[..., tf.newaxis], tf.shape(images)[1:3])
return cam
def get_config(self):
cfg = super().get_config()
cfg.update({'last_conv_layer_name': self.conv_layer.name})
return cfg
使用示例(单张图片推理):
base_model = keras.applications.ResNet50(weights='imagenet')
model = keras.Model(inputs=base_model.input,
outputs=base_model.output)
grad_cam = GradCAM(model, 'conv5_block3_out')
img = tf.io.decode_image(tf.io.read_file('cat.jpg'))
img = tf.image.resize(img, [224, 224])[tf.newaxis, ...]
img = tf.cast(img, tf.float32)
heatmap = grad_cam([img, None]) # None 表示取 top1 类别
该层可直接塞进 tf.keras.Sequential 或 Functional API,作为可视化节点,也可在 model.save('xxx') 时通过 custom_objects={'GradCAM': GradCAM} 完整导出,满足生产部署需求。
拓展思考
- 高分辨率图像(>2K)场景下,特征图过大导致显存爆炸,可在
GradCAM内部引入tf.nn.avg_pool2d对梯度与特征图同步下采样,再计算 α,实现亚线性显存占用。 - 若面试官追问“如何支持多塔网络(如 Siamese)”,可在
__init__阶段传入conv_layer_list,在call中对每塔分别求梯度后做平均,体现你对复杂拓扑的掌控。 - 国内工业界常要求“端侧实时”,可把
GradCAM改造成tf.function静态图 + FP16 量化,并用 TFLite Delegate 在 NPU 上跑,面试时主动提到这一点,可展示你对“算法落地最后一公里”的认知。