简体   繁体   English

尝试使用 grad-CAM 热图可视化 ML,但 K.gradients 返回零值

[英]Trying to visualize ML with a grad-CAM heatmap but K.gradients returning zero values

for visualizing the results of the ML process i decided to use a CAM heatmap.为了可视化 ML 过程的结果,我决定使用 CAM 热图。 I used the code provided here on my model yet the return of pooled_grads_value, conv_layer_output_value = iterate([x]) is all zeros for pooled_grads_value but the conv_layer_output_value has values in it.我在我的模型上使用了此处提供的代码,但pooled_grads_value, conv_layer_output_value = iterate([x])conv_layer_output_value值对于pooled_grads_value全为零,但conv_layer_output_value有值。

this is how i used it:这就是我使用它的方式:

import matplotlib.image as mpimg
from keras import backend as K
import matplotlib.pyplot as plt
import pandas as pd
import keras
import numpy as np
#%%
model_path = "pathto/model.h5"
img_path = "pathto/pic.tif"
output_path = "pathto/output.jpeg"
size = (1000,200)
#%%

model = keras.models.load_model(model_path)

img=mpimg.imread(img_path)
plt.imshow(img)
#%%

from keras.preprocessing import image
img = image.load_img(img_path, target_size=size)
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)

#%%
preds = model.predict(x)

argmax = np.argmax(preds[0])

output = model.output[:, argmax]
#%%
last_conv_layer = model.get_layer( "conv_6_l")
grads = K.gradients(output, last_conv_layer.output)[0]
pooled_grads = K.mean(grads, axis=(0, 1, 2))
iterate = K.function([model.input], [pooled_grads, last_conv_layer.output[0]])
#%%
pooled_grads_value,  conv_layer_output_value = iterate([x])
#%%
for i in range(64):
    conv_layer_output_value[:, :, i] *= pooled_grads_value[i]
#%%
heatmap = np.mean(conv_layer_output_value, axis=-1)
heatmap = np.maximum(heatmap, 0)
#heatmap /= np.max(heatmap)
#%%
import cv2
img = cv2.imread(img_path)
heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
heatmap = np.uint8(255 * heatmap)
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
hif = .8
superimposed_img = heatmap * hif + img
cv2.imwrite("pathto/justheatmap.jpeg", heatmap * hif)
#%%
cv2.imwrite(output_path, superimposed_img)

my model looks like this:我的模型是这样的:

model = Sequential()
model.add(Conv2D(8, (3, 3), input_shape=(1000, 200, 3), name = "conv_1"))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(16, (3, 3), name="conv_2"))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3), name="conv_3"))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3),name="conv_4"))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(128, (3, 3),name="conv_5"))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3),name="conv_6_l"))
model.add(Activation('relu'))

model.add(GlobalAveragePooling2D())

model.add(Dropout(0.33))
model.add(Dense(5))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
          optimizer='Adam',
          metrics=['accuracy'])

Does anyone know what the source of my problem is?有谁知道我的问题的根源是什么?

I also tried a different aproach shown here using tensorflow.keras.GradientTape() function , yet this gives me an error module 'tensorflow' has no attribute 'GradientTape so I sticked to the first aproach.我还使用 tensorflow.keras.GradientTape() 函数尝试了此处显示的不同方法,但这给了我一个错误module 'tensorflow' has no attribute 'GradientTape因此我坚持使用第一种方法。

I'm using keras V 2.3.1 and tensorflow V 2.1.0 in python.我在 python 中使用 keras V 2.3.1 和 tensorflow V 2.1.0。

I also uploaded a zip-file containing the .h5 file of my model and one picture for testing我还上传了一个zip 文件,其中包含我的模型的 .h5 文件和一张用于测试的图片

Thanks in advance for everyone trying to help!预先感谢所有试图提供帮助的人!

Hans汉斯

We can capture Gradients using Keras Backend OR Tensorflow tf.GradientTape() function.我们可以使用 Keras Backend或 Tensorflow tf.GradientTape()函数捕获梯度。 Later we can use these Gradients to visualize as Heatmap.稍后我们可以使用这些梯度来可视化为热图。 Would like to route you to two SO Answers that have explained on how to capture the gradients and visualize them as Heatmap.想将您引导至两个 SO Answers,其中解释了如何捕获梯度并将其可视化为热图。 These 2 SO Answers would suffice your requirements.这 2 个 SO 答案足以满足您的要求。

Please refer to this SO Answer for capturing the gradients using Keras Backend and also for visualizing the gradients as heat map.请参阅此SO 答案以使用 Keras Backend捕获梯度并将梯度可视化为热图。

If you are keen on capturing the gradients using the Tensorflow tf.GradientTape() function then please refer to this SO Answer and for visualizing the Gradients as heatmap you can use the same code mentioned in the earlier answer.如果您热衷于使用 Tensorflow tf.GradientTape()函数捕获梯度,请参阅此SO 答案,并将梯度可视化为热图,您可以使用前面答案中提到的相同代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 keras 中实施 Grad-Cam 时出现未连接梯度错误 - Error unconnected gradients while implementing Grad-Cam in keras 如何使用 pytorch 获取从损失到目标层 output 的梯度以进行 Grad-CAM 计算 - How to get the gradients from loss to target layer output for Grad-CAM computation with pytorch 如何在训练有素的网络上实施 Grad-CAM - How to implement Grad-CAM on a trained network Keras:使用 K.gradients 进行梯度上升 - Keras: Gradient Ascent using K.gradients Grad-cam在使用inceptionv3的keras中无法正常工作 - Grad-cam not working properly in keras with inceptionv3 如何在 Keras 的循环中加速 Grad-CAM 计算? - How to speed up the Grad-CAM calculation within a loop in Keras? Grad-CAM 迁移学习错误:尝试将值(无)转换为不受支持的类型(<class 'nonetype'> ) 到张量</class> - Grad-CAM Transfer learning error: Attempt to convert a value (None) with an unsupported type (<class 'NoneType'>) to a Tensor 热图以可视化值的百分比 - Heatmap to visualize percentage of values Grad-CAM可视化:无效参数错误:您必须使用dtype float和shape [x]输入占位符张量&#39;X&#39;的值 - Grad-CAM visualization: Invalid Argument Error: You must feed a value for placeholder tensor 'X' with dtype float and shape [x] K.gradients(loss, input_img)[0] 返回“无”。 (带有 tensorflow 后端的 Keras CNN 可视化) - K.gradients(loss, input_img)[0] return “None”. (Keras CNN visualization with tensorflow backend)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM