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

LIME图直接存PNG空白问题求解决方案:无需imgkit/wkhtmltoimage

解决LIME图直接存PNG空白或HTML转PNG的问题(禁用imgkit/wkhtmltoimage)

问题背景

生成LIME解释图时,直接保存为PNG会得到空白文件。目前先存HTML再转PNG,但需要不用imgkit或wkhtmltoimage的替代方案。之前尝试的代码如下:

exp = explainer.explain_instance(
    X_test.values[value_index], model.predict_proba, top_labels=1
)
exp.show_in_notebook(show_table=True)
exp.save_to_file(
    f"{output_path}//graphics/lime_plot_high_{j}.html",     
    labels=None,
    predict_proba=True,
    show_predicted_value=True,
)

hti.screenshot(
    html_file=f"{output_path}//graphics/lime_plot_high_{j}.html",
    save_as=f"lime_plot_high_{j}.png",
)

im = Image.open(f"{output_path}//graphics/lime_plot_high_{j}.png")
im = im.crop((0, 0, im.size[0] / 2, im.size[1] / 2.5))
im.save(f"{output_path}//graphics/lime_plot_high_{j}.png")

两种可行解决方案

方案1:直接生成PNG(无需HTML转换)

LIME的解释对象支持通过as_pyplot_figure()方法生成matplotlib图形,直接保存就能得到非空白的PNG,步骤更简单:

import matplotlib.pyplot as plt

exp = explainer.explain_instance(
    X_test.values[value_index], model.predict_proba, top_labels=1
)

# 基于LIME解释生成matplotlib图
fig = exp.as_pyplot_figure(label=exp.top_labels[0])

# 调整布局防止标签被截断
plt.tight_layout()

# 保存为高分辨率PNG
fig.savefig(
    f"{output_path}//graphics/lime_plot_high_{j}.png",
    dpi=300,
    bbox_inches='tight'  # 确保所有元素都被保存
)
plt.close(fig)  # 释放内存

方案2:用Selenium将HTML转PNG

如果要保留LIME原生的HTML样式(和Notebook里显示的一致),可以用Selenium加载本地HTML并截图:

  1. 先安装依赖:pip install selenium,并下载对应浏览器的驱动(比如ChromeDriver,要和浏览器版本匹配)
  2. 代码示例:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import os
from PIL import Image

# 配置Chrome无头模式(不弹出浏览器窗口)
chrome_options = Options()
chrome_options.add_argument("--headless=new")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--window-size=1200,800")  # 适配LIME图的尺寸

# 启动浏览器
driver = webdriver.Chrome(options=chrome_options)

# 加载本地HTML文件(转成file协议路径)
html_full_path = os.path.abspath(f"{output_path}//graphics/lime_plot_high_{j}.html")
driver.get(f"file:///{html_full_path}")

# 等待页面渲染完成
driver.implicitly_wait(5)

# 截图保存
driver.save_screenshot(f"{output_path}//graphics/lime_plot_high_{j}.png")

# 关闭浏览器
driver.quit()

# 按需求裁剪图片(和原逻辑一致,改用整数除法避免问题)
im = Image.open(f"{output_path}//graphics/lime_plot_high_{j}.png")
im = im.crop((0, 0, im.size[0] // 2, im.size[1] // 2))
im.save(f"{output_path}//graphics/lime_plot_high_{j}.png")

内容的提问来源于stack exchange,提问作者Ayush sharma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 20:22:48