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