我正在尝试为 DenseNet121 中的灰度图像创建 grad-cam 显着图。我在运行代码时遇到问题,无法使我的图像适合所需的输入形状。
这是我的热图代码
def get_class_activation_map(path) :
img_path = path
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.resize(img, (150, 150))
img = np.expand_dims(img,axis=0)
predict = model.predict(img)
target_class = np.argmax(predict[0])
last_conv = model.get_layer('conv2d_119')
grads =K.gradients(model.output[:,target_class],last_conv.output)[0]
pooled_grads = K.mean(grads,axis=(0,1,2))
iterate = K.function([model.input],[pooled_grads,last_conv.output[0]])
pooled_grads_value,conv_layer_output = iterate([img])
for i in range(512):
conv_layer_output[:,:,i] *= pooled_grads_value[i]
heatmap = np.mean(conv_layer_output,axis=-1)
for x in range(heatmap.shape[0]):
for y in range(heatmap.shape[1]):
heatmap[x,y] = np.max(heatmap[x,y],0)
heatmap = np.maximum(heatmap,0)
heatmap /= np.max(heatmap)
plt.imshow(heatmap)
我得到的错误
ValueError: Error when checking input: expected densenet121_input to have shape (150, 150, 1) but got array with shape (1, 150, 150)
您能告诉我如何更改我的代码以更改尺寸本身吗?
答案 0 :(得分:1)
在线执行预测之前:
predict = model.predict(img)
这样做:
img = np.moveaxis(img, -1, 0)
这会将形状从 channels_first 反转为 channels_last,这在您的模型中是预期的。