Keras 绘制CNN每层的类激活图(CAM)

本文介绍了如何利用CAM技术结合Keras来显示卷积神经网络中每层对于目标类别的注意力分布。CAM通过计算注意力层输出与目标类别神经元的梯度加权平均,揭示图像各部位对特定类别的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CAM获取到卷积层(注意力层)的输出和目标类别神经元相对于每一个通道的梯度,使用该梯度对每个通道进行加权处理,最后对通道求均值并归一化处理。CAM可以指示图像每个位置相对于所考虑的类的重要程度。
代码实现:

     引入依赖、模型定义省略
    ...
    
model = Model(inputs=inp, outputs=x)
model.load_weights('WDD_jing3_2_weights.hdf5')    ***#加载自己的模型文件,可以是weights***
   
image=cv2.imread('6.png')     ***#输入图像 ,本人输入的是一个小猫***
image_arr = cv2.resize(image, (224, 224))
image_arr = np.expand_dims(image_arr, axis=0)

preds = model.predict(image_arr)
# find the class index
index = np.argmax(preds[0])

target_output = model.output[:, index]

# last_conv_layer=model.get_layer('norm_l_1')
last_conv_layer=model.get_layer('max_pooling2d_5')    # ***这里是keras定义的层的名字,想看哪一层的输出,改为哪一层的名字***

# compute the gradient of the output feature map with this target class
grads = K.gradients(target_output, last_conv_layer.output)[0]

# mean the gradient over a specific feature
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值