You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改LIME代码以正确解释ResNet50迁移学习模型输出?

问题描述

我正在尝试使用LIME解释Keras中基于ResNet50的4类别图像分类迁移学习模型的输出,参考了相关教程。以下是使用的LIME代码片段:

img = cv2.imread('/content/drive/MyDrive/Dataset/cat/cat129.png')
img = cv2.resize(img, (224,224))
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)

import lime
from lime import lime_image


explainer = lime_image.LimeImageExplainer()


img[0].shape

explanation = explainer.explain_instance(img[0].astype('double'), model.predict,  
                                         top_labels=3, hide_color=0, num_samples=1000)
from skimage.segmentation import mark_boundaries

temp_1, mask_1 = explanation.get_image_and_mask(explanation.top_labels[0], positive_only=True ,negative_only=False, num_features=5, hide_rest=True)
temp_2, mask_2 = explanation.get_image_and_mask(explanation.top_labels[0], positive_only=False ,negative_only=True, num_features=10, hide_rest=False)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15,15))
ax1.imshow(mark_boundaries(temp_1, mask_1))
ax2.imshow(mark_boundaries(temp_2, mask_2))
ax1.axis('off')
ax2.axis('off')

预期能得到带有清晰正负样本边界标记的可视化结果,但实际输出颜色失真、边界标记混乱,需要修改哪行代码才能达成预期效果?

解决方案

问题根源是OpenCV与LIME/Matplotlib的图像通道顺序不匹配:

  • OpenCV默认以BGR通道顺序读取图像,而LIME和Matplotlib渲染图像时使用的是RGB顺序,这直接导致了颜色显示错误和可视化异常。

只需在图像缩放后添加一行通道转换代码即可解决:

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

修改后的关键代码段如下:

img = cv2.imread('/content/drive/MyDrive/Dataset/cat/cat129.png')
img = cv2.resize(img, (224,224))
# 新增:转换BGR通道为RGB
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)

提前转换通道顺序能确保后续LIME的解释和Matplotlib的可视化都基于正确的颜色空间,避免出现颜色失真和标记混乱的问题。

内容的提问来源于stack exchange,提问作者Rezuana Haque

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 04:15:37