如何在Keras函数式模型中添加层并访问InceptionResNetV2层输出
解决方法:获取InceptionResNetV2最后卷积层输出用于Grad-CAM
要访问预训练模型的中间层输出(比如最后卷积层),不需要重构整个训练流程,有两种直接的实现方式:
方法一:构建多输出模型(训练时同时保留特征输出)
修改你的模型定义,将InceptionResNetV2的最后卷积层输出也作为模型的一个输出。首先确认基础模型的最后卷积层名称——对于include_top=False的InceptionResNetV2,最后一个卷积激活层通常是conv_7b_ac,你可以通过print(base.summary())验证。
修改后的代码如下:
from tensorflow.keras import layers, models import tensorflow as tf InceptionResNetV2 = tf.keras.applications.inception_resnet_v2.InceptionResNetV2 def get_base(): conv_base = InceptionResNetV2(weights=None, include_top=False, input_shape=(224, 224, 3)) conv_base.trainable = False return conv_base def get_model(): base = get_base() # 明确获取最后卷积层的输出 last_conv_output = base.get_layer('conv_7b_ac').output inputs = tf.keras.Input(shape=(224, 224, 3)) # 先让输入经过基础模型,触发层的计算 _ = base(inputs, training=False) x = layers.Flatten()(base.output) x = layers.Dense(512, "relu")(x) x = layers.Dropout(0.25)(x) x = layers.Dense(256, "relu")(x) x = layers.Dropout(0.25)(x) dims = layers.Dense(2, name="Valence_Arousal")(x) expression = layers.Dense(2, name="Emotion_Category")(x) # 模型输出包含分类结果和最后卷积层特征 model = models.Model(inputs=[inputs], outputs=[expression, dims, last_conv_output]) return model # 查看模型结构,确认输出包含三个部分 print(get_model().summary())
训练时可以只关注前两个分类输出的损失,第三个输出不需要计算损失:
model = get_model() model.compile( optimizer='adam', loss=['sparse_categorical_crossentropy', 'mse', None], # 第三个输出无损失 metrics=['accuracy'] )
推理时,直接获取第三个输出就是最后卷积层的特征图:
expression_pred, dims_pred, last_conv_feat = model.predict(your_input_data)
方法二:训练完成后,单独构建特征提取模型
如果不想修改原训练模型,可以在训练完成后,基于原模型的输入和目标层输出创建一个新的特征提取模型:
# 假设你已经训练好原模型,加载或获取原模型实例 original_model = get_model() # 获取基础模型的最后卷积层 base_model = original_model.get_layer(original_model.layers[1].name) last_conv_layer = base_model.get_layer('conv_7b_ac') # 构建特征提取模型 feature_extractor = models.Model( inputs=original_model.input, outputs=[ original_model.output[0], # Emotion_Category输出 original_model.output[1], # Valence_Arousal输出 last_conv_layer.output # 最后卷积层特征 ] ) # 使用该模型获取所需输出 expression_pred, dims_pred, last_conv_feat = feature_extractor.predict(your_input_data)
注意事项
- 层名称确认:不同版本的TensorFlow可能会有层名称细微差异,一定要通过
base.summary()查看准确的最后卷积层名称。 - Grad-CAM后续步骤:拿到最后卷积层特征图后,需要结合对应分类头的梯度进行加权求和,再经过ReLU和上采样得到热力图,这部分逻辑可以基于获取到的特征图和模型梯度实现。
内容的提问来源于stack exchange,提问作者Salih F. Canpolat
相关产品推荐
相关产品推荐

