您当前的位置:首页 > IT编程 > 深度学习
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch |

自学教程:Keras CAM实现-绘制CNN每层的类激活图(CAM)

51自学网 2022-12-09 14:53:16
  深度学习
这篇教程Keras CAM实现-绘制CNN每层的类激活图(CAM)写得很实用,希望能帮到您。

Keras 绘制CNN每层的类激活图(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 map channel
pooled_grads = K.mean(grads, axis=(0, 1, 2))

# this function returns the output of last_conv_layer and grads
# given the input picture
iterate = K.function([model.input], [pooled_grads, last_conv_layer.output[0]])
pooled_grads_value, conv_layer_output_value = iterate([image_arr])

# We multiply each channel in the feature map array
# by "how important this channel is" with regard to the target class

for i in range(conv_layer_output_value.shape[-1]):
    conv_layer_output_value[:, :, i] *= pooled_grads_value[i]

# The channel-wise mean of the resulting feature map
# is our heatmap of class activation
heatmap = np.mean(conv_layer_output_value, axis=-1)
heatmap = np.maximum(heatmap, 0)
heatmap /= np.max(heatmap)

img=image #加载原始图像
heatma=cv2.resize(heatmap,(img.shape[1],img.shape[0]))
#将热力图调整为与原始图像一样大小
heatmap=np.uint8(255*heatma)#将热力图改为rgb格式
heatmap=cv2.applyColorMap(heatmap,cv2.COLORMAP_JET)#将热力图应用于原始图像
superimposed_img=heatmap*3+img#3是热力图的强度因子

img_write = cv2.imencode(".jpg",superimposed_img)[1].tofile('CAM6_1.jpg')# ***存图***

用代码的话,需要改一下图像的输入输出,改一下加载的模型,改一下last layer的名字。此处展示一下本文的输入输出:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


Keras 的预训练权值模型用来进行预测、特征提取和微调(fine-tuning)
深度学习模型复用——模型的保存与加载
51自学网,即我要自学网,自学EXCEL、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。
京ICP备13026421号-1