You need to enable JavaScript to run this app. Keras子类化ResNet模型实现GradCAM时获取中间层输出报错求助
优惠活动
大模型
产品
解决方案
定价
更多

Keras子类化ResNet模型实现GradCAM时获取中间层输出报错求助

问题描述

我基于Keras和TensorFlow开发了嵌套keras.Model结构的ResNet风格模型,想要获取中间层输出用于GradCAM,但运行时出现如下错误:

AttributeError: Layer conv2d_11 has no inbound nodes.

模型结构包含ResBlock、ConvBlock和顶层ResNet模型,尝试通过自定义的GradResNet获取子模型内部卷积层输出时触发上述错误。

错误原因

嵌套的keras.Model(如ResBlock)内部的层属于子模型的私有层,顶层ResNet模型的计算图中并没有直接注册这些内部层的节点连接。当通过resnet.get_layer("res_block_6").get_layer("conv2d_11")获取内部卷积层并访问其output属性时,该层未被纳入顶层模型的计算图,因此不存在输入节点(inbound nodes),导致报错。

解决方案

以下提供三种可行的解决方式:

方法一:直接使用子模型输出替代内部卷积层输出

对于GradCAM任务,ResBlock的输出(经过BN和激活后的特征图)完全可以满足需求,无需强行获取Conv层的原始输出。修改GradResNet类如下:

class GradResNet(keras.Model):
    def __init__(self, resnet, conv_layer_idx, **kwargs):
        super().__init__(**kwargs)
        if conv_layer_idx < 0:
            self.conv_layer_idx = len(resnet.res_blocks) + conv_layer_idx
        elif conv_layer_idx <= len(resnet.res_blocks):
            self.conv_layer_idx = conv_layer_idx
        else:
            raise ValueError("conv_layer_idx must be a valid index for res_blocks")

        if not resnet.built:
            raise ValueError("Please provide a built model or call the model with dummy inputs to build it")
        
        # 直接获取ResBlock的输出,而非内部Conv层
        target_res_block = resnet.get_layer(f"res_block_{self.conv_layer_idx}")
        self.grad_model = keras.Model(
            [resnet.inputs], 
            [target_res_block.output, resnet.output]
        )

    def call(self, x, training = None):
        return self.grad_model(x, training = training)

同步修改GradCAM函数,移除无效的last_conv_layer_name参数:

def make_gradcam_heatmap(img_array, grad_model, pred_index = None):
    with tf.GradientTape() as tape:
        last_conv_layer_output, (_, pred_dis) = grad_model(img_array)
        if pred_index is None:
            pred_index = tf.argmax(pred_dis[0])
        class_channel = pred_dis[:, pred_index]

    grads = tape.gradient(class_channel, last_conv_layer_output)

    pooled_grads = tf.reduce_mean(grads, axis = (0, 1, 2))

    last_conv_layer_output = last_conv_layer_output[0]
    heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]
    heatmap = tf.squeeze(heatmap)

    heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)
    return heatmap.numpy()

方法二:在子模型中暴露内部卷积层输出

若必须获取Conv层的原始输出,可修改ResBlock类,在call方法中保存Conv层的输出张量:

class ResBlock(keras.Model):
    def __init__(self, filters, activation = tf.nn.relu, **kwargs):
        super().__init__(**kwargs)
        self.filters = filters
        self.act = keras.activations.get(activation)

    def build(self, input_shape):
        self.conv = layers.Conv2D(filters = self.filters, kernel_size = 1, strides = 1, padding = 'same', activation = None)
        self.bn = layers.BatchNormalization()
        self.activation = layers.Activation(self.act)

    def call(self, x, training = None):
        self.conv_output = self.conv(x, training = training)  # 保存Conv层输出张量
        y = self.bn(self.conv_output, training = training)
        y = self.activation(y, training = training)
        return y

然后修改GradResNet,通过子模型的属性获取Conv层输出:

class GradResNet(keras.Model):
    def __init__(self, resnet, conv_layer_idx, **kwargs):
        super().__init__(**kwargs)
        if conv_layer_idx < 0:
            self.conv_layer_idx = len(resnet.res_blocks) + conv_layer_idx
        elif conv_layer_idx <= len(resnet.res_blocks):
            self.conv_layer_idx = conv_layer_idx
        else:
            raise ValueError("conv_layer_idx must be a valid index for res_blocks")

        if not resnet.built:
            raise ValueError("Please provide a built model or call the model with dummy inputs to build it")
        
        target_res_block = resnet.get_layer(f"res_block_{self.conv_layer_idx}")
        # 使用子模型保存的Conv层输出张量
        self.grad_model = keras.Model(
            [resnet.inputs], 
            [target_res_block.conv_output, resnet.output]
        )

    def call(self, x, training = None):
        return self.grad_model(x, training = training)

注意:此方式需确保模型已被调用过(如执行model(img_array)),否则conv_output属性未被赋值。

方法三:改用函数式API构建模型

嵌套keras.Model虽灵活,但在获取中间层输出时存在节点注册问题。改用函数式API可让所有层注册到同一计算图中,更易获取任意中间层输出:

def ResBlock(filters, activation=tf.nn.relu, name=None):
    def block(x):
        conv = layers.Conv2D(filters, 1, padding='same', name=f"{name}_conv")(x)
        bn = layers.BatchNormalization(name=f"{name}_bn")(conv)
        act = layers.Activation(activation, name=f"{name}_act")(bn)
        return act, conv  # 返回ResBlock输出和Conv层输出
    return block

def ConvBlock(filters, kernel_size, padding='same', activation=tf.nn.relu, dropout=0, name=None):
    def block(x):
        conv = layers.Conv2D(filters, kernel_size, strides=2, padding=padding, activation=activation, name=f"{name}_conv")(x)
        bn = layers.BatchNormalization(name=f"{name}_bn")(conv)
        act = layers.Activation(activation, name=f"{name}_act")(bn)
        dr = layers.Dropout(dropout, name=f"{name}_dr")(act)
        return dr
    return block

def build_resnet(depth, num_classes, filters=None, dropout=0, layer_activation=tf.nn.relu, classifier_activation=tf.nn.sigmoid):
    if filters is None:
        filters = [64*(2**i) for i in range(depth)]
    
    inputs = layers.Input(shape=(224,224,3))
    x = inputs
    
    # 保存需要的中间层输出
    intermediate_outputs = []
    
    for i in range(depth):
        conv_block = ConvBlock(filters[i], 7 if i==0 else 3, dropout=dropout, activation=layer_activation, name=f"conv_block_{i+1}")(x)
        res_block, res_conv = ResBlock(filters[i], activation=layer_activation, name=f"res_block_{i+1}")(conv_block)
        intermediate_outputs.append(res_conv)  # 保存Conv层输出
        x = layers.Add(name=f"add_{i+1}")([conv_block, res_block])
    
    x = layers.GlobalAveragePooling2D(name="avg_pool")(x)
    x = layers.Flatten(name="flatten")(x)
    risk = layers.Dense(1, activation=tf.nn.sigmoid, name="risk_classification_head")(x)
    disease = layers.Dense(num_classes, activation=classifier_activation, name="disease_classification_head")(x)
    
    # 构建主模型和包含中间层的Grad模型
    model = keras.Model(inputs=inputs, outputs=[risk, disease], name="resnet")
    # 示例:获取第6个ResBlock的Conv输出
    grad_model = keras.Model(inputs=inputs, outputs=[intermediate_outputs[5], [risk, disease]])
    
    return model, grad_model

此方式下所有层都在同一计算图中,获取中间层输出更直接,不会出现节点相关错误。

来源标注

内容的提问来源于stack exchange,提问作者Arijit Dey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 04:59:51