def Grad_Cam(model, image, layer_name): # 获取模型提取全链接之前的特征图 new_model = nn.Sequential(*list(model.children())[:44]) print(new_model) new_model.eval() feature_maps = new_model(image) # 获取模型最后一层卷积层 target_layer = model._modules.get(layer_name) # 将模型最后一层卷积层的输出结果作为反向传播的梯度 gradient = torch.zeros(feature_maps.size()) # 返回一个形状与feature_maps相同全为标量 0 的张量 gradient[:, :, feature_maps.size()[2]//2, feature_maps.size()[3]//2] = 1 target_layer.zero_grad() # 将模型中参数的梯度置为0 feature_maps.backward(gradient=gradient) # 获取模型最后一层卷积层的输出结果和梯度 _, _, H, W = feature_maps.size() output_activations = feature_maps.detach().numpy()[0] gradients = target_layer.weight.grad.detach().numpy() # 计算特征图中每个像素点的权重 weights = np.mean(gradients, axis=(2, 3))[0] cam = np.zeros((H, W), dtype=np.float32) for i, w in enumerate(weights): cam += w * output_activations[i, :, :] # 对权重进行归一化处理 cam = np.maximum(cam, 0) cam = cv2.resize(cam, (1440, 1440)) cam = cam - np.min(cam) cam = cam / np.max(cam) # 将热力图叠加到原图上 heatmap = cv2.applyColorMap(np.uint8(255 * cam), cv2.COLORMAP_JET) heatmap = np.float32(heatmap) / 255 image = image.detach().numpy() image = np.transpose(image, (0, 2, 3, 1)) img_CCT = cv2.imread("F:/BaiduSyncdisk/python/svm_CCT/picture CCT_CP/2L5830N023_CCT.png") img_CP = cv2.imread("F:/BaiduSyncdisk/python/svm_CCT/picture CCT_CP/2L5830N023_CP.png") img_CCT = cv2.resize(img_CCT, (1440, 1440)) img_CP = cv2.resize(img_CP, (1440, 1440)) cam_img = heatmap + np.float32(img_CCT[0]) cam_img = cam_img / np.max(cam_img) return np.uint8(255 * cam_img) 上述代码不显示热力图,怎么解决
时间: 2023-12-27 07:04:49 浏览: 35
可能是因为在使用 OpenCV 的 `cv2.imshow()` 函数显示图像时,会因为使用了多线程导致程序崩溃。可以尝试使用 `matplotlib` 库来显示热力图,代码如下:
```python
import matplotlib.pyplot as plt
# 将热力图进行归一化处理
heatmap = cv2.resize(cam, (image.shape[2], image.shape[3]))
heatmap = heatmap - np.min(heatmap)
heatmap = heatmap / np.max(heatmap)
# 将热力图叠加到原图上
heatmap = cv2.applyColorMap(np.uint8(255 * heatmap), cv2.COLORMAP_JET)
cam_img = np.float32(heatmap) / 255 + np.transpose(image[0], (1, 2, 0))
cam_img = cam_img / np.max(cam_img)
# 使用 matplotlib 显示热力图
plt.imshow(cam_img)
plt.show()
```
这样就可以在 Jupyter Notebook 或者 Python IDE 中显示热力图了。如果仍然无法显示,可以尝试将 `plt.show()` 替换为 `plt.savefig('heatmap.png')`,将热力图保存为图片进行查看。
相关问题
grad_norm = torch.nn.utils.clip_grad_norm_( model.parameters(), CFG.max_grad_norm)
这段代码是用来进行梯度裁剪的。在深度学习模型训练过程中,梯度值可能会变得非常大,从而导致模型的不稳定性。为了避免这种情况,我们可以使用梯度裁剪的方法,将梯度值控制在一个可接受的范围内。
`torch.nn.utils.clip_grad_norm_()` 函数是 PyTorch 提供的梯度裁剪工具,它的作用是对模型的所有参数进行梯度裁剪,使得它们的梯度范数不超过 `CFG.max_grad_norm`。这样做可以保证模型在训练过程中的稳定性,并且防止梯度爆炸的问题。
class FeatureExtractor(): def __init__(self, model, target_layers): self.model = model self.target_layers = target_layers self.gradients = [] def save_gradient(self, grad): self.gradients.append(grad) def __call__(self, x): outputs = [] self.gradients = [] for name, module in self.model._modules.items(): ##遍历目标层的每一个模块,比如卷积、BN,ReLU x = module(x) if name in self.target_layers: x.register_hook(self.save_gradient) #利用hook来记录目标层的梯度 outputs += [x] return outputs, x def __init__(self, model, target_layers): self.model = model model_features = nn.Sequential(*list(model.children())[:8]) self.feature_extractor = FeatureExtractor(model_features, target_layers) def get_gradients(self): return self.feature_extractor.gradients one_hot.backward() grads_val = self.extractor.get_gradients()[-1].cpu().data.numpy() 报错list index out of range ,如何修改代码解决
这个错误可能是因为 `self.feature_extractor.gradients` 这个列表为空,也就是说在调用 `get_gradients()` 函数之前,`save_gradient()` 函数没有被执行,因此没有梯度可供提取。
你可以尝试在调用 `one_hot.backward()` 之前,先通过 `self.feature_extractor(x)` 函数来提取梯度,这样就能保证在调用 `get_gradients()` 函数时,`self.feature_extractor.gradients` 列表中至少有一个梯度值了。具体代码修改如下:
```
def __init__(self, model, target_layers):
self.model = model
model_features = nn.Sequential(*list(model.children())[:8])
self.feature_extractor = FeatureExtractor(model_features, target_layers)
def get_gradients(self, x, one_hot):
self.feature_extractor(x)
one_hot.backward()
grads_val = self.feature_extractor.gradients[-1].cpu().data.numpy()
return grads_val
```
这样应该就能够成功提取到梯度值了。