给出我gradcam热力图的代码
时间: 2023-05-25 17:03:46 浏览: 88
热力图源码
以下是使用Keras实现Grad-CAM热力图的代码:
```python
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Activation, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout
from tensorflow.keras.optimizers import Adam
# 构建模型
input_tensor = Input(shape=(224, 224, 3))
x = Conv2D(32, (3, 3), activation='relu', padding='same')(input_tensor)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Conv2D(128, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Flatten()(x)
x = Dense(64)(x)
x = Activation('relu')(x)
x = Dropout(0.5)(x)
output_tensor = Dense(1, activation='sigmoid')(x)
model = Model(inputs=input_tensor, outputs=output_tensor)
model.compile(optimizer=Adam(lr=0.001),
loss='binary_crossentropy',
metrics=['accuracy'])
# 加载预训练权重
model.load_weights('weights.h5')
# 加载图像,并进行预处理
img_path = 'image.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x /= 255.
# 创建Grad-CAM实例
class GradCAM:
def __init__(self, model, layer_name):
self.model = model
self.layer_name = layer_name
self.grad_model = Model(
inputs=[self.model.inputs],
outputs=[self.model.get_layer(self.layer_name).output, self.model.output])
def compute_heatmap(self, image, class_idx, eps=1e-8):
grad_model = self.grad_model
with tf.GradientTape() as tape:
inputs = tf.cast(image, tf.float32)
conv_output, predictions = grad_model(inputs)
loss = predictions[:, class_idx]
grads = tape.gradient(loss, conv_output)[0]
guided_grads = tf.cast(conv_output > 0, 'float32') * tf.cast(grads > 0, 'float32') * grads
guided_grads /= tf.reduce_mean(guided_grads, axis=(0, 1))
heatmap = tf.reduce_mean(tf.multiply(guided_grads, conv_output), axis=-1)
heatmap = tf.maximum(heatmap, 0)
heatmap /= tf.reduce_max(heatmap) + eps
return heatmap.numpy()
# 使用Grad-CAM生成热力图
grad_cam = GradCAM(model, 'conv2d_3')
heatmap = grad_cam.compute_heatmap(x, 0)
# 可视化热力图
import cv2
heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
heatmap = cv2.applyColorMap(np.uint8(255 * heatmap), cv2.COLORMAP_JET)
output_img = cv2.addWeighted(cv2.cvtColor(img, cv2.COLOR_RGB2BGR), 0.5, heatmap, 0.5, 0)
cv2.imshow('Grad-CAM', output_img)
cv2.waitKey(0)
```
阅读全文