[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-meta-pytorch--captum":3,"tool-meta-pytorch--captum":61},[4,18,26,36,44,53],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":17},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[13,14,15,16],"Agent","开发框架","图像","数据工具","ready",{"id":19,"name":20,"github_repo":21,"description_zh":22,"stars":23,"difficulty_score":10,"last_commit_at":24,"category_tags":25,"status":17},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,"2026-04-05T11:01:52",[14,15,13],{"id":27,"name":28,"github_repo":29,"description_zh":30,"stars":31,"difficulty_score":32,"last_commit_at":33,"category_tags":34,"status":17},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",150037,2,"2026-04-10T23:33:47",[14,13,35],"语言模型",{"id":37,"name":38,"github_repo":39,"description_zh":40,"stars":41,"difficulty_score":32,"last_commit_at":42,"category_tags":43,"status":17},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",108322,"2026-04-10T11:39:34",[14,15,13],{"id":45,"name":46,"github_repo":47,"description_zh":48,"stars":49,"difficulty_score":32,"last_commit_at":50,"category_tags":51,"status":17},6121,"gemini-cli","google-gemini\u002Fgemini-cli","gemini-cli 是一款由谷歌推出的开源 AI 命令行工具，它将强大的 Gemini 大模型能力直接集成到用户的终端环境中。对于习惯在命令行工作的开发者而言，它提供了一条从输入提示词到获取模型响应的最短路径，无需切换窗口即可享受智能辅助。\n\n这款工具主要解决了开发过程中频繁上下文切换的痛点，让用户能在熟悉的终端界面内直接完成代码理解、生成、调试以及自动化运维任务。无论是查询大型代码库、根据草图生成应用，还是执行复杂的 Git 操作，gemini-cli 都能通过自然语言指令高效处理。\n\n它特别适合广大软件工程师、DevOps 人员及技术研究人员使用。其核心亮点包括支持高达 100 万 token 的超长上下文窗口，具备出色的逻辑推理能力；内置 Google 搜索、文件操作及 Shell 命令执行等实用工具；更独特的是，它支持 MCP（模型上下文协议），允许用户灵活扩展自定义集成，连接如图像生成等外部能力。此外，个人谷歌账号即可享受免费的额度支持，且项目基于 Apache 2.0 协议完全开源，是提升终端工作效率的理想助手。",100752,"2026-04-10T01:20:03",[52,13,15,14],"插件",{"id":54,"name":55,"github_repo":56,"description_zh":57,"stars":58,"difficulty_score":32,"last_commit_at":59,"category_tags":60,"status":17},4721,"markitdown","microsoft\u002Fmarkitdown","MarkItDown 是一款由微软 AutoGen 团队打造的轻量级 Python 工具，专为将各类文件高效转换为 Markdown 格式而设计。它支持 PDF、Word、Excel、PPT、图片（含 OCR）、音频（含语音转录）、HTML 乃至 YouTube 链接等多种格式的解析，能够精准提取文档中的标题、列表、表格和链接等关键结构信息。\n\n在人工智能应用日益普及的今天，大语言模型（LLM）虽擅长处理文本，却难以直接读取复杂的二进制办公文档。MarkItDown 恰好解决了这一痛点，它将非结构化或半结构化的文件转化为模型“原生理解”且 Token 效率极高的 Markdown 格式，成为连接本地文件与 AI 分析 pipeline 的理想桥梁。此外，它还提供了 MCP（模型上下文协议）服务器，可无缝集成到 Claude Desktop 等 LLM 应用中。\n\n这款工具特别适合开发者、数据科学家及 AI 研究人员使用，尤其是那些需要构建文档检索增强生成（RAG）系统、进行批量文本分析或希望让 AI 助手直接“阅读”本地文件的用户。虽然生成的内容也具备一定可读性，但其核心优势在于为机器",93400,"2026-04-06T19:52:38",[52,14],{"id":62,"github_repo":63,"name":64,"description_en":65,"description_zh":66,"ai_summary_zh":67,"readme_en":68,"readme_zh":69,"quickstart_zh":70,"use_case_zh":71,"hero_image_url":72,"owner_login":73,"owner_name":74,"owner_avatar_url":75,"owner_bio":76,"owner_company":77,"owner_location":77,"owner_email":77,"owner_twitter":77,"owner_website":78,"owner_url":79,"languages":80,"stars":104,"forks":105,"last_commit_at":106,"license":107,"difficulty_score":108,"env_os":76,"env_gpu":109,"env_ram":109,"env_deps":110,"category_tags":115,"github_topics":117,"view_count":10,"oss_zip_url":77,"oss_zip_packed_at":77,"status":17,"created_at":123,"updated_at":124,"faqs":125,"releases":154},3710,"meta-pytorch\u002Fcaptum","captum","Model interpretability and understanding for PyTorch","Captum 是一款专为 PyTorch 打造的模型可解释性与理解库，其名称源自拉丁语“理解”。随着深度学习模型日益复杂，其决策过程往往像“黑盒”一样难以捉摸，Captum 正是为了解决这一透明度缺失的问题而生。它帮助开发者清晰地看到是哪些输入特征、训练样本或抽象概念影响了模型的最终预测，从而让 AI 的决策逻辑变得有据可依。\n\n无论是希望优化模型性能、排查异常输出的算法工程师，还是致力于研究新型解释算法的科研人员，亦或是需要在生产环境中向终端用户解释推荐结果的應用开发者，都能从 Captum 中获益。它不仅提供了集成梯度（Integrated Gradients）、显著性图（Saliency Maps）、SmoothGrad 等经典归因算法的原生实现，还涵盖了 TCAV、TracIn 等前沿技术，甚至支持对抗攻击与最小输入扰动分析，用于生成反事实解释。\n\nCaptum 的最大亮点在于其与 PyTorch 生态的无缝集成，能够直接适配 torchvision、torchtext 等主流领域库构建的模型，让用户无需重写代码即可快速上手。通过可视化的归因分析，Captum 让模型调试更高效","Captum 是一款专为 PyTorch 打造的模型可解释性与理解库，其名称源自拉丁语“理解”。随着深度学习模型日益复杂，其决策过程往往像“黑盒”一样难以捉摸，Captum 正是为了解决这一透明度缺失的问题而生。它帮助开发者清晰地看到是哪些输入特征、训练样本或抽象概念影响了模型的最终预测，从而让 AI 的决策逻辑变得有据可依。\n\n无论是希望优化模型性能、排查异常输出的算法工程师，还是致力于研究新型解释算法的科研人员，亦或是需要在生产环境中向终端用户解释推荐结果的應用开发者，都能从 Captum 中获益。它不仅提供了集成梯度（Integrated Gradients）、显著性图（Saliency Maps）、SmoothGrad 等经典归因算法的原生实现，还涵盖了 TCAV、TracIn 等前沿技术，甚至支持对抗攻击与最小输入扰动分析，用于生成反事实解释。\n\nCaptum 的最大亮点在于其与 PyTorch 生态的无缝集成，能够直接适配 torchvision、torchtext 等主流领域库构建的模型，让用户无需重写代码即可快速上手。通过可视化的归因分析，Captum 让模型调试更高效，也让 AI 系统的可信度显著提升，是连接复杂模型与人类理解之间的重要桥梁。","![Captum Logo](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmeta-pytorch_captum_readme_3675d3588780.png)\n\n\u003Chr\u002F>\n\n\u003C!--- BADGES: START --->\n[![GitHub - License](https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Flicense\u002Fpytorch\u002Fcaptum?logo=github&style=flat&color=green)][#github-license]\n[![Conda](https:\u002F\u002Fimg.shields.io\u002Fconda\u002Fvn\u002Fpytorch\u002Fcaptum?logo=anaconda&style=flat&color=orange)](https:\u002F\u002Fanaconda.org\u002Fpytorch\u002Fcaptum)\n[![PyPI](https:\u002F\u002Fimg.shields.io\u002Fpypi\u002Fv\u002Fcaptum.svg)][#pypi-package]\n[![Conda - Platform](https:\u002F\u002Fimg.shields.io\u002Fconda\u002Fpn\u002Fconda-forge\u002Fcaptum?logo=anaconda&style=flat)][#conda-forge-package]\n[![Conda (channel only)](https:\u002F\u002Fimg.shields.io\u002Fconda\u002Fvn\u002Fconda-forge\u002Fcaptum?logo=anaconda&style=flat&color=orange)][#conda-forge-package]\n[![Conda Recipe](https:\u002F\u002Fimg.shields.io\u002Fstatic\u002Fv1?logo=conda-forge&style=flat&color=green&label=recipe&message=captum)][#conda-forge-feedstock]\n[![Docs - GitHub.io](https:\u002F\u002Fimg.shields.io\u002Fstatic\u002Fv1?logo=captum&style=flat&color=pink&label=docs&message=captum)][#docs-package]\n\n[#github-license]: https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum\u002Fblob\u002Fmaster\u002FLICENSE\n[#pypi-package]: https:\u002F\u002Fpypi.org\u002Fproject\u002Fcaptum\u002F\n[#conda-forge-package]: https:\u002F\u002Fanaconda.org\u002Fconda-forge\u002Fcaptum\n[#conda-forge-feedstock]: https:\u002F\u002Fgithub.com\u002Fconda-forge\u002Fcaptum-feedstock\n[#docs-package]: https:\u002F\u002Fcaptum.ai\u002F\n\u003C!--- BADGES: END --->\n\n\nCaptum is a model interpretability and understanding library for PyTorch.\nCaptum means comprehension in Latin and contains general purpose implementations\nof integrated gradients, saliency maps, smoothgrad, vargrad and others for\nPyTorch models. It has quick integration for models built with domain-specific\nlibraries such as torchvision, torchtext, and others.\n\n\n#### About Captum\n\nWith the increase in model complexity and the resulting lack of transparency, model interpretability methods have become increasingly important. Model understanding is both an active area of research as well as an area of focus for practical applications across industries using machine learning. Captum provides state-of-the-art algorithms such as Integrated Gradients, Testing with Concept Activation Vectors (TCAV), TracIn influence functions, just to name a few, that provide researchers and developers with an easy way to understand which features, training examples or concepts contribute to a models' predictions and in general what and how the model learns. In addition to that, Captum also provides adversarial attacks and minimal input perturbation capabilities that can be used both for generating counterfactual explanations and adversarial perturbations.\n\n\u003C!--For model developers, Captum can be used to improve and troubleshoot models by facilitating the identification of different features that contribute to a model’s output in order to design better models and troubleshoot unexpected model outputs. -->\n\nCaptum helps ML researchers more easily implement interpretability algorithms that can interact with PyTorch models. Captum also allows researchers to quickly benchmark their work against other existing algorithms available in the library.\n\n![Overview of Attribution Algorithms](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmeta-pytorch_captum_readme_7d8e676114b9.png)\n\n#### Target Audience\n\nThe primary audiences for Captum are model developers who are looking to improve their models and understand which concepts, features or training examples are important and interpretability researchers focused on identifying algorithms that can better interpret many types of models.\n\nCaptum can also be used by application engineers who are using trained models in production. Captum provides easier troubleshooting through improved model interpretability, and the potential for delivering better explanations to end users on why they’re seeing a specific piece of content, such as a movie recommendation.\n\n## Installation\n\n**Installation Requirements**\n- Python >= 3.10\n- PyTorch >= 2.3\n\n\n##### Installing the latest release\n\nInstall released Captum via `pip`.\n\n**With `pip`**\n\n```bash\npip install captum\n```\n\n**Manual \u002F Dev install**\n\nIf you'd like to try our bleeding edge features (and don't mind potentially\nrunning into the occasional bug here or there), you can install the latest\nmaster directly from GitHub. For a basic install, run:\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum.git\ncd captum\npip install -e .\n```\n\nTo customize the installation, you can also run the following variants of the\nabove:\n* `pip install -e .[dev]`: Also installs all tools necessary for development\n  (testing, linting, docs building; see [Contributing](#contributing) below).\n* `pip install -e .[tutorials]`: Also installs all packages necessary for running the tutorial notebooks.\n\nTo execute unit tests from a manual install, run:\n```bash\n# running a single unit test\npython -m unittest -v tests.attr.test_saliency\n# running all unit tests\npytest -ra\n```\n\n## Getting Started\nCaptum helps you interpret and understand predictions of PyTorch models by\nexploring features that contribute to a prediction the model makes.\nIt also helps understand which neurons and layers are important for\nmodel predictions.\n\nLet's apply some of those algorithms to a toy model we have created for\ndemonstration purposes.\nFor simplicity, we will use the following architecture, but users are welcome\nto use any PyTorch model of their choice.\n\n\n```python\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\n\nfrom captum.attr import (\n    GradientShap,\n    DeepLift,\n    DeepLiftShap,\n    IntegratedGradients,\n    LayerConductance,\n    NeuronConductance,\n    NoiseTunnel,\n)\n\nclass ToyModel(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.lin1 = nn.Linear(3, 3)\n        self.relu = nn.ReLU()\n        self.lin2 = nn.Linear(3, 2)\n\n        # initialize weights and biases\n        self.lin1.weight = nn.Parameter(torch.arange(-4.0, 5.0).view(3, 3))\n        self.lin1.bias = nn.Parameter(torch.zeros(1,3))\n        self.lin2.weight = nn.Parameter(torch.arange(-3.0, 3.0).view(2, 3))\n        self.lin2.bias = nn.Parameter(torch.ones(1,2))\n\n    def forward(self, input):\n        return self.lin2(self.relu(self.lin1(input)))\n```\n\nLet's create an instance of our model and set it to eval mode.\n```python\nmodel = ToyModel()\nmodel.eval()\n```\n\nNext, we need to define simple input and baseline tensors.\nBaselines belong to the input space and often carry no predictive signal.\nZero tensor can serve as a baseline for many tasks.\nSome interpretability algorithms such as `IntegratedGradients`, `Deeplift` and `GradientShap` are designed to attribute the change\nbetween the input and baseline to a predictive class or a value that the neural\nnetwork outputs.\n\nWe will apply model interpretability algorithms on the network\nmentioned above in order to understand the importance of individual\nneurons\u002Flayers and the parts of the input that play an important role in the\nfinal prediction.\n\nTo make computations deterministic, let's fix random seeds.\n\n```python\ntorch.manual_seed(123)\nnp.random.seed(123)\n```\n\nLet's define our input and baseline tensors. Baselines are used in some\ninterpretability algorithms such as `IntegratedGradients, DeepLift,\nGradientShap, NeuronConductance, LayerConductance, InternalInfluence` and\n`NeuronIntegratedGradients`.\n\n```python\ninput = torch.rand(2, 3)\nbaseline = torch.zeros(2, 3)\n```\nNext we will use `IntegratedGradients` algorithms to assign attribution\nscores to each input feature with respect to the first target output.\n```python\nig = IntegratedGradients(model)\nattributions, delta = ig.attribute(input, baseline, target=0, return_convergence_delta=True)\nprint('IG Attributions:', attributions)\nprint('Convergence Delta:', delta)\n```\nOutput:\n```\nIG Attributions: tensor([[-0.5922, -1.5497, -1.0067],\n                         [ 0.0000, -0.2219, -5.1991]])\nConvergence Delta: tensor([2.3842e-07, -4.7684e-07])\n```\nThe algorithm outputs an attribution score for each input element and a\nconvergence delta. The lower the absolute value of the convergence delta the better\nis the approximation. If we choose not to return delta,\nwe can simply not provide the `return_convergence_delta` input\nargument. The absolute value of the returned deltas can be interpreted as an\napproximation error for each input sample.\nIt can also serve as a proxy of how accurate the integral approximation for given\ninputs and baselines is.\nIf the approximation error is large, we can try a larger number of integral\napproximation steps by setting `n_steps` to a larger value. Not all algorithms\nreturn approximation error. Those which do, though, compute it based on the\ncompleteness property of the algorithms.\n\nPositive attribution score means that the input in that particular position\npositively contributed to the final prediction and negative means the opposite.\nThe magnitude of the attribution score signifies the strength of the contribution.\nZero attribution score means no contribution from that particular feature.\n\nSimilarly, we can apply `GradientShap`, `DeepLift` and other attribution algorithms to the model.\n\n`GradientShap` first chooses a random baseline from baselines' distribution, then\n adds gaussian noise with std=0.09 to each input example `n_samples` times.\nAfterwards, it chooses a random point between each example-baseline pair and\ncomputes the gradients with respect to target class (in this case target=0). Resulting\nattribution is the mean of gradients * (inputs - baselines)\n```python\ngs = GradientShap(model)\n\n# We define a distribution of baselines and draw `n_samples` from that\n# distribution in order to estimate the expectations of gradients across all baselines\nbaseline_dist = torch.randn(10, 3) * 0.001\nattributions, delta = gs.attribute(input, stdevs=0.09, n_samples=4, baselines=baseline_dist,\n                                   target=0, return_convergence_delta=True)\nprint('GradientShap Attributions:', attributions)\nprint('Convergence Delta:', delta)\n```\nOutput\n```\nGradientShap Attributions: tensor([[-0.1542, -1.6229, -1.5835],\n                                   [-0.3916, -0.2836, -4.6851]])\nConvergence Delta: tensor([ 0.0000, -0.0005, -0.0029, -0.0084, -0.0087, -0.0405,  0.0000, -0.0084])\n\n```\nDeltas are computed for each `n_samples * input.shape[0]` example. The user can,\nfor instance, average them:\n```python\ndeltas_per_example = torch.mean(delta.reshape(input.shape[0], -1), dim=1)\n```\nin order to get per example average delta.\n\n\nBelow is an example of how we can apply `DeepLift` and `DeepLiftShap` on the\n`ToyModel` described above. The current implementation of DeepLift supports only the\n`Rescale` rule.\nFor more details on alternative implementations, please see the [DeepLift paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F1704.02685).\n\n```python\ndl = DeepLift(model)\nattributions, delta = dl.attribute(input, baseline, target=0, return_convergence_delta=True)\nprint('DeepLift Attributions:', attributions)\nprint('Convergence Delta:', delta)\n```\nOutput\n```\nDeepLift Attributions: tensor([[-0.5922, -1.5497, -1.0067],\n                               [ 0.0000, -0.2219, -5.1991])\nConvergence Delta: tensor([0., 0.])\n```\n`DeepLift` assigns similar attribution scores as `IntegratedGradients` to inputs,\nhowever it has lower execution time. Another important thing to remember about\nDeepLift is that it currently doesn't support all non-linear activation types.\nFor more details on limitations of the current implementation, please see the\n[DeepLift paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F1704.02685).\n\nSimilar to integrated gradients, DeepLift returns a convergence delta score\nper input example. The approximation error is then the absolute\nvalue of the convergence deltas and can serve as a proxy of how accurate the\nalgorithm's approximation is.\n\nNow let's look into `DeepLiftShap`. Similar to `GradientShap`, `DeepLiftShap` uses\nbaseline distribution. In the example below, we use the same baseline distribution\nas for `GradientShap`.\n\n```python\ndl = DeepLiftShap(model)\nattributions, delta = dl.attribute(input, baseline_dist, target=0, return_convergence_delta=True)\nprint('DeepLiftSHAP Attributions:', attributions)\nprint('Convergence Delta:', delta)\n```\nOutput\n```\nDeepLiftShap Attributions: tensor([[-5.9169e-01, -1.5491e+00, -1.0076e+00],\n                                   [-4.7101e-03, -2.2300e-01, -5.1926e+00]], grad_fn=\u003CMeanBackward1>)\nConvergence Delta: tensor([-4.6120e-03, -1.6267e-03, -5.1045e-04, -1.4184e-03, -6.8886e-03,\n                           -2.2224e-02,  0.0000e+00, -2.8790e-02, -4.1285e-03, -2.7295e-02,\n                           -3.2349e-03, -1.6265e-03, -4.7684e-07, -1.4191e-03, -6.8889e-03,\n                           -2.2224e-02,  0.0000e+00, -2.4792e-02, -4.1289e-03, -2.7296e-02])\n```\n`DeepLiftShap` uses `DeepLift` to compute attribution score for each\ninput-baseline pair and averages it for each input across all baselines.\n\nIt computes deltas for each input example-baseline pair, thus resulting to\n`input.shape[0] * baseline.shape[0]` delta values.\n\nSimilar to GradientShap in order to compute example-based deltas we can average them per example:\n```python\ndeltas_per_example = torch.mean(delta.reshape(input.shape[0], -1), dim=1)\n```\nIn order to smooth and improve the quality of the attributions we can run\n`IntegratedGradients` and other attribution methods through a `NoiseTunnel`.\n`NoiseTunnel` allows us to use `SmoothGrad`, `SmoothGrad_Sq` and `VarGrad` techniques\nto smoothen the attributions by aggregating them for multiple noisy\nsamples that were generated by adding gaussian noise.\n\nHere is an example of how we can use `NoiseTunnel` with `IntegratedGradients`.\n\n```python\nig = IntegratedGradients(model)\nnt = NoiseTunnel(ig)\nattributions, delta = nt.attribute(input, nt_type='smoothgrad', stdevs=0.02, nt_samples=4,\n      baselines=baseline, target=0, return_convergence_delta=True)\nprint('IG + SmoothGrad Attributions:', attributions)\nprint('Convergence Delta:', delta)\n```\nOutput\n```\nIG + SmoothGrad Attributions: tensor([[-0.4574, -1.5493, -1.0893],\n                                      [ 0.0000, -0.2647, -5.1619]])\nConvergence Delta: tensor([ 0.0000e+00,  2.3842e-07,  0.0000e+00, -2.3842e-07,  0.0000e+00,\n        -4.7684e-07,  0.0000e+00, -4.7684e-07])\n\n```\nThe number of elements in the `delta` tensor is equal to: `nt_samples * input.shape[0]`\nIn order to get an example-wise delta, we can, for example, average them:\n```python\ndeltas_per_example = torch.mean(delta.reshape(input.shape[0], -1), dim=1)\n```\n\nLet's look into the internals of our network and understand which layers\nand neurons are important for the predictions.\n\nWe will start with the `NeuronConductance`. `NeuronConductance` helps us to identify\ninput features that are important for a particular neuron in a given\nlayer. It decomposes the computation of integrated gradients via the chain rule by\ndefining the importance of a neuron as path integral of the derivative of the output\nwith respect to the neuron times the derivatives of the neuron with respect to the\ninputs of the model.\n\nIn this case, we choose to analyze the first neuron in the linear layer.\n\n```python\nnc = NeuronConductance(model, model.lin1)\nattributions = nc.attribute(input, neuron_selector=1, target=0)\nprint('Neuron Attributions:', attributions)\n```\nOutput\n```\nNeuron Attributions: tensor([[ 0.0000,  0.0000,  0.0000],\n                             [ 1.3358,  0.0000, -1.6811]])\n```\n\nLayer conductance shows the importance of neurons for a layer and given input.\nIt is an extension of path integrated gradients for hidden layers and holds the\ncompleteness property as well.\n\nIt doesn't attribute the contribution scores to the input features\nbut shows the importance of each neuron in the selected layer.\n```python\nlc = LayerConductance(model, model.lin1)\nattributions, delta = lc.attribute(input, baselines=baseline, target=0, return_convergence_delta=True)\nprint('Layer Attributions:', attributions)\nprint('Convergence Delta:', delta)\n```\nOutputs\n```\nLayer Attributions: tensor([[ 0.0000,  0.0000, -3.0856],\n                            [ 0.0000, -0.3488, -4.9638]], grad_fn=\u003CSumBackward1>)\nConvergence Delta: tensor([0.0630, 0.1084])\n```\n\nSimilar to other attribution algorithms that return convergence delta, `LayerConductance`\nreturns the deltas for each example. The approximation error is then the absolute\nvalue of the convergence deltas and can serve as a proxy of how accurate integral\napproximation for given inputs and baselines is.\n\nMore details on the list of supported algorithms and how to apply\nCaptum on different types of models can be found in our tutorials.\n\n## Captum Insights (Retired)\n\nCaptum Insights was retired after v0.8.0 and is no longer supported. You can check out\nthe repository at the v0.8.0 tag to view the defunct code.\n\n## FAQ\nIf you have questions about using Captum methods, please check this [FAQ](docs\u002Ffaq.md), which addresses many common issues.\n\n## Contributing\nSee the [CONTRIBUTING](CONTRIBUTING.md) file for how to help out.\n\n## Talks and Papers\n**NeurIPS 2019:**\nThe slides of our presentation  can be found [here](docs\u002Fpresentations\u002FCaptum_NeurIPS_2019_final.key)\n\n**KDD 2020:**\nThe slides of our presentation from KDD 2020 tutorial can be found [here](https:\u002F\u002Fpytorch-tutorial-assets.s3.amazonaws.com\u002FCaptum_KDD_2020.pdf).\nYou can watch the recorded talk [here](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=hY_XzglTkak)\n\n**GTC 2020:**\nOpening Up the Black Box: Model Understanding with Captum and PyTorch.\nYou can watch the recorded talk [here](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=0QLrRyLndFI)\n\n**XAI Summit 2020:**\nUsing Captum and Fiddler to Improve Model Understanding with Explainable AI.\nYou can watch the recorded talk [here](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=dvuVld5Hyc8)\n\n**PyTorch Developer Day 2020**\nModel Interpretability.\nYou can watch the recorded talk [here](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=Lj5hHBGue58)\n\n**NAACL 2021**\nTutorial on Fine-grained Interpretation and Causation Analysis in Deep NLP Models.\nYou can watch the recorded talk [here](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=ayhBHZYjeqs\n)\n\n**ICLR 2021 workshop on Responsible AI**:\n- [Paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F2009.07896) on the Captum Library\n- [Paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F2106.07475) on Investigating Sanity Checks for Saliency Maps\n\n\nSummer school on medical imaging at University of Lyon has a class on model explainability you can watch [here](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=vn-jLzY67V0)\n\n## References of Algorithms\n\n* `IntegratedGradients`, `LayerIntegratedGradients`: [Axiomatic Attribution for Deep Networks, Mukund Sundararajan et al. 2017](https:\u002F\u002Farxiv.org\u002Fabs\u002F1703.01365) and [Did the Model Understand the Question?, Pramod K. Mudrakarta, et al. 2018](https:\u002F\u002Farxiv.org\u002Fabs\u002F1805.05492)\n* `InputXGradient`: [Not Just a Black Box: Learning Important Features Through Propagating Activation Differences, Avanti Shrikumar et al. 2016](https:\u002F\u002Farxiv.org\u002Fabs\u002F1605.01713)\n* `SmoothGrad`: [SmoothGrad: removing noise by adding noise, Daniel Smilkov et al. 2017](https:\u002F\u002Farxiv.org\u002Fabs\u002F1706.03825)\n* `NoiseTunnel`: [Sanity Checks for Saliency Maps, Julius Adebayo et al. 2018](https:\u002F\u002Farxiv.org\u002Fabs\u002F1810.03292)\n* `NeuronConductance`: [How Important is a neuron?, Kedar Dhamdhere et al. 2018](https:\u002F\u002Farxiv.org\u002Fabs\u002F1805.12233)\n* `LayerConductance`: [Computationally Efficient Measures of Internal Neuron Importance, Avanti Shrikumar et al. 2018](https:\u002F\u002Farxiv.org\u002Fabs\u002F1807.09946)\n* `DeepLift`, `NeuronDeepLift`, `LayerDeepLift`: [Learning Important Features Through Propagating Activation Differences, Avanti Shrikumar et al. 2017](https:\u002F\u002Farxiv.org\u002Fabs\u002F1704.02685) and [Towards better understanding of gradient-based attribution methods for deep neural networks, Marco Ancona et al. 2018](https:\u002F\u002Fopenreview.net\u002Fpdf?id=Sy21R9JAW)\n* `NeuronIntegratedGradients`: [Computationally Efficient Measures of Internal Neuron Importance, Avanti Shrikumar et al. 2018](https:\u002F\u002Farxiv.org\u002Fabs\u002F1807.09946)\n* `GradientShap`, `NeuronGradientShap`, `LayerGradientShap`, `DeepLiftShap`, `NeuronDeepLiftShap`, `LayerDeepLiftShap`: [A Unified Approach to Interpreting Model Predictions, Scott M. Lundberg et al. 2017](https:\u002F\u002Fproceedings.neurips.cc\u002Fpaper\u002F2017\u002Fhash\u002F8a20a8621978632d76c43dfd28b67767-Abstract.html)\n* `InternalInfluence`: [Influence-Directed Explanations for Deep Convolutional Networks, Klas Leino et al. 2018](https:\u002F\u002Farxiv.org\u002Fabs\u002F1802.03788)\n* `Saliency`, `NeuronGradient`: [Deep Inside Convolutional Networks: Visualising\nImage Classification Models and Saliency Maps, K. Simonyan, et. al. 2014](https:\u002F\u002Farxiv.org\u002Fabs\u002F1312.6034)\n* `GradCAM`, `Guided GradCAM`: [Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization, Ramprasaath R. Selvaraju et al. 2017](https:\u002F\u002Farxiv.org\u002Fabs\u002F1610.02391)\n* `Deconvolution`, `Neuron Deconvolution`: [Visualizing and Understanding Convolutional Networks, Matthew D Zeiler et al. 2014](https:\u002F\u002Farxiv.org\u002Fabs\u002F1311.2901)\n* `Guided Backpropagation`, `Neuron Guided Backpropagation`: [Striving for Simplicity: The All Convolutional Net, Jost Tobias Springenberg et al. 2015](https:\u002F\u002Farxiv.org\u002Fabs\u002F1412.6806)\n* `Feature Permutation`: [Permutation Feature Importance](https:\u002F\u002Fchristophm.github.io\u002Finterpretable-ml-book\u002Ffeature-importance.html)\n* `Occlusion`: [Visualizing and Understanding Convolutional Networks](https:\u002F\u002Farxiv.org\u002Fabs\u002F1311.2901)\n* `Shapley Value`: [A value for n-person games. Contributions to the Theory of Games 2.28 (1953): 307-317](https:\u002F\u002Fapps.dtic.mil\u002Fdtic\u002Ftr\u002Ffulltext\u002Fu2\u002F604084.pdf)\n* `Shapley Value Sampling`: [Polynomial calculation of the Shapley value based on sampling](https:\u002F\u002Fwww.sciencedirect.com\u002Fscience\u002Farticle\u002Fpii\u002FS0305054808000804)\n* `Infidelity and Sensitivity`: [On the (In)fidelity and Sensitivity for Explanations](https:\u002F\u002Farxiv.org\u002Fabs\u002F1901.09392)\n* `TracInCP, TracInCPFast, TracInCPRandProj`: [Estimating Training Data Influence by Tracing Gradient Descent](https:\u002F\u002Farxiv.org\u002Fabs\u002F2002.08484)\n* `SimilarityInfluence`: [Pairwise similarities between train and test examples based on predefined similarity metrics]\n* `BinaryConcreteStochasticGates`: [Stochastic Gates with Binary Concrete Distribution](https:\u002F\u002Farxiv.org\u002Fabs\u002F1712.01312)\n* `GaussianStochasticGates`: [Stochastic Gates with Gaussian Distribution](https:\u002F\u002Farxiv.org\u002Fabs\u002F1810.04247)\n\nMore details about the above mentioned [attribution algorithms](https:\u002F\u002Fcaptum.ai\u002Fdocs\u002Fattribution_algorithms) and their pros and cons can be found on our [website](https:\u002F\u002Fcaptum.ai\u002Fdocs\u002Falgorithms_comparison_matrix).\n\n## License\nCaptum is BSD licensed, as found in the [LICENSE](LICENSE) file.\n","![Captum Logo](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmeta-pytorch_captum_readme_3675d3588780.png)\n\n\u003Chr\u002F>\n\n\u003C!--- 徽章：开始 --->\n[![GitHub - 许可证](https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Flicense\u002Fpytorch\u002Fcaptum?logo=github&style=flat&color=green)][#github-license]\n[![Conda](https:\u002F\u002Fimg.shields.io\u002Fconda\u002Fvn\u002Fpytorch\u002Fcaptum?logo=anaconda&style=flat&color=orange)](https:\u002F\u002Fanaconda.org\u002Fpytorch\u002Fcaptum)\n[![PyPI](https:\u002F\u002Fimg.shields.io\u002Fpypi\u002Fv\u002Fcaptum.svg)][#pypi-package]\n[![Conda - 平台](https:\u002F\u002Fimg.shields.io\u002Fconda\u002Fpn\u002Fconda-forge\u002Fcaptum?logo=anaconda&style=flat)][#conda-forge-package]\n[![Conda (仅通道)](https:\u002F\u002Fimg.shields.io\u002Fconda\u002Fvn\u002Fconda-forge\u002Fcaptum?logo=anaconda&style=flat&color=orange)][#conda-forge-package]\n[![Conda 配方](https:\u002F\u002Fimg.shields.io\u002Fstatic\u002Fv1?logo=conda-forge&style=flat&color=green&label=recipe&message=captum)][#conda-forge-feedstock]\n[![文档 - GitHub.io](https:\u002F\u002Fimg.shields.io\u002Fstatic\u002Fv1?logo=captum&style=flat&color=pink&label=docs&message=captum)][#docs-package]\n\n[#github-license]: https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum\u002Fblob\u002Fmaster\u002FLICENSE\n[#pypi-package]: https:\u002F\u002Fpypi.org\u002Fproject\u002Fcaptum\u002F\n[#conda-forge-package]: https:\u002F\u002Fanaconda.org\u002Fconda-forge\u002Fcaptum\n[#conda-forge-feedstock]: https:\u002F\u002Fgithub.com\u002Fconda-forge\u002Fcaptum-feedstock\n[#docs-package]: https:\u002F\u002Fcaptum.ai\u002F\n\u003C!--- 徽章：结束 --->\n\n\nCaptum 是一个用于 PyTorch 的模型可解释性和理解库。\n“Captum”在拉丁语中意为“理解”，它包含了针对 PyTorch 模型的积分梯度、显著性图、SmoothGrad、Vargrad 等通用实现。该库能够快速集成到使用特定领域库（如 torchvision、torchtext 等）构建的模型中。\n\n\n#### 关于 Captum\n\n随着模型复杂性的增加以及由此带来的透明度不足，模型可解释性方法变得愈发重要。模型理解既是当前活跃的研究领域，也是各行各业在实际应用中关注的重点。Captum 提供了最先进的算法，例如积分梯度、基于概念激活向量的测试（TCAV）、TracIn 影响函数等，这些算法为研究人员和开发者提供了一种简便的方式，以了解哪些特征、训练样本或概念对模型的预测结果产生了影响，以及模型究竟学习了什么、如何学习。此外，Captum 还提供了对抗攻击和最小输入扰动功能，可用于生成反事实解释和对抗性扰动生成。\n\n\u003C!--对于模型开发者而言，Captum 可以通过帮助识别影响模型输出的不同特征来改进和调试模型，从而设计出更优的模型并解决意外的模型输出问题。-->\n\nCaptum 帮助机器学习研究人员更轻松地实现可解释性算法，并使其能够与 PyTorch 模型无缝对接。同时，Captum 也使研究人员能够快速将自己的工作与其他库中已有的算法进行基准比较。\n\n![归因算法概览](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmeta-pytorch_captum_readme_7d8e676114b9.png)\n\n#### 目标用户\n\nCaptum 的主要受众是希望改进模型、理解哪些概念、特征或训练样本重要的模型开发者，以及专注于开发能够更好地解释各类模型的算法的可解释性研究者。\n\n此外，Captum 也可被在生产环境中使用训练好的模型的应用工程师所采用。通过提升模型的可解释性，Captum 能够简化故障排查，并为最终用户提供更好的解释，说明他们为何会看到某一特定内容，例如电影推荐等。\n\n## 安装\n\n**安装要求**\n- Python >= 3.10\n- PyTorch >= 2.3\n\n\n##### 安装最新版本\n\n通过 `pip` 安装发布的 Captum 版本。\n\n**使用 `pip`**\n\n```bash\npip install captum\n```\n\n**手动\u002F开发版安装**\n\n如果您想尝试我们的前沿功能（并且不介意偶尔遇到一些小 bug），可以直接从 GitHub 克隆最新主分支进行安装。基本安装步骤如下：\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum.git\ncd captum\npip install -e .\n```\n\n若需自定义安装，还可运行以下变体：\n* `pip install -e .[dev]`：同时安装所有开发所需的工具（测试、代码检查、文档构建；详见下方的 [贡献指南](#contributing)）。\n* `pip install -e .[tutorials]`：同时安装运行教程笔记本所需的所有包。\n\n从手动安装中执行单元测试的方法如下：\n```bash\n# 运行单个单元测试\npython -m unittest -v tests.attr.test_saliency\n# 运行所有单元测试\npytest -ra\n```\n\n## 入门\nCaptum 通过探索对模型预测有贡献的特征，帮助您解释和理解 PyTorch 模型的预测结果。它还能帮助您了解哪些神经元和层对模型的预测至关重要。\n\n让我们将其中一些算法应用于我们为演示目的创建的一个玩具模型。为了简单起见，我们将使用以下架构，但用户也可以自由选择任何他们喜欢的 PyTorch 模型。\n\n\n```python\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\n\nfrom captum.attr import (\n    GradientShap,\n    DeepLift,\n    DeepLiftShap,\n    IntegratedGradients,\n    LayerConductance,\n    NeuronConductance,\n    NoiseTunnel,\n)\n\nclass ToyModel(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.lin1 = nn.Linear(3, 3)\n        self.relu = nn.ReLU()\n        self.lin2 = nn.Linear(3, 2)\n\n        # 初始化权重和偏置\n        self.lin1.weight = nn.Parameter(torch.arange(-4.0, 5.0).view(3, 3))\n        self.lin1.bias = nn.Parameter(torch.zeros(1,3))\n        self.lin2.weight = nn.Parameter(torch.arange(-3.0, 3.0).view(2, 3))\n        self.lin2.bias = nn.Parameter(torch.ones(1,2))\n\n    def forward(self, input):\n        return self.lin2(self_relu(self_lin1(input)))\n```\n\n让我们创建一个模型实例，并将其设置为评估模式。\n```python\nmodel = ToyModel()\nmodel.eval()\n```\n\n接下来，我们需要定义简单的输入张量和基线张量。基线属于输入空间，通常不携带任何预测信号。零张量可以作为许多任务的基线。一些可解释性算法，如 `IntegratedGradients`、`DeepLift` 和 `GradientShap`，旨在将输入与基线之间的变化归因于神经网络输出的某个预测类别或值。\n\n我们将对上述网络应用模型可解释性算法，以了解各个神经元\u002F层的重要性，以及输入中对最终预测起重要作用的部分。\n\n为了使计算具有确定性，我们固定随机种子。\n\n```python\ntorch.manual_seed(123)\nnp.random.seed(123)\n```\n\n让我们定义输入和基线张量。基线用于一些可解释性算法，例如 `IntegratedGradients`、`DeepLift`、`GradientShap`、`NeuronConductance`、`LayerConductance`、`InternalInfluence` 和 `NeuronIntegratedGradients`。\n\n```python\ninput = torch.rand(2, 3)\nbaseline = torch.zeros(2, 3)\n```\n接下来，我们将使用 `IntegratedGradients` 算法，针对第一个目标输出，为每个输入特征分配归因分数。\n```python\nig = IntegratedGradients(model)\nattributions, delta = ig.attribute(input, baseline, target=0, return_convergence_delta=True)\nprint('IG Attributions:', attributions)\nprint('Convergence Delta:', delta)\n```\n输出：\n```\nIG Attributions: tensor([[-0.5922, -1.5497, -1.0067],\n                         [ 0.0000, -0.2219, -5.1991]])\nConvergence Delta: tensor([2.3842e-07, -4.7684e-07])\n```\n该算法会输出每个输入元素的归因分数以及收敛误差。收敛误差的绝对值越小，近似效果越好。如果我们不想返回误差，只需不提供 `return_convergence_delta` 参数即可。返回的误差绝对值可以被解释为每个输入样本的近似误差，也可以作为给定输入和基线下积分近似的准确性的代理指标。如果近似误差较大，我们可以尝试增加积分近似的步数，将 `n_steps` 设置为更大的值。并非所有算法都会返回近似误差；而那些会返回的算法，则是基于其算法的完备性属性来计算的。\n\n正的归因分数表示该位置的输入对最终预测有正面贡献，负的则相反。归因分数的大小表明了贡献的强度。归因分数为零意味着该特征没有贡献。\n\n同样地，我们也可以将 `GradientShap`、`DeepLift` 等归因算法应用于该模型。\n\n`GradientShap` 首先从基线分布中随机选择一个基线，然后对每个输入示例添加标准差为 0.09 的高斯噪声，重复 `n_samples` 次。之后，它在每个示例与基线之间随机选取一点，并计算相对于目标类（本例中为 0）的梯度。最终的归因结果是梯度乘以 (输入 - 基线) 的平均值。\n```python\ngs = GradientShap(model)\n\n# 我们定义一个基线分布，并从中抽取 `n_samples` 个样本，以估计所有基线上的梯度期望值\nbaseline_dist = torch.randn(10, 3) * 0.001\nattributions, delta = gs.attribute(input, stdevs=0.09, n_samples=4, baselines=baseline_dist,\n                                   target=0, return_convergence_delta=True)\nprint('GradientShap Attributions:', attributions)\nprint('Convergence Delta:', delta)\n```\n输出：\n```\nGradientShap Attributions: tensor([[-0.1542, -1.6229, -1.5835],\n                                   [-0.3916, -0.2836, -4.6851]])\nConvergence Delta: tensor([ 0.0000, -0.0005, -0.0029, -0.0084, -0.0087, -0.0405,  0.0000, -0.0084])\n```\n对于每个 `n_samples * input.shape[0]` 个示例，都会计算出相应的误差。用户可以对这些误差取平均值：\n```python\ndeltas_per_example = torch.mean(delta.reshape(input.shape[0], -1), dim=1)\n```\n以得到每个示例的平均误差。\n\n\n以下是我们在上述 `ToyModel` 上应用 `DeepLift` 和 `DeepLiftShap` 的示例。目前的 `DeepLift` 实现仅支持 `Rescale` 规则。有关其他实现方式的详细信息，请参阅 [DeepLift 论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F1704.02685)。\n\n```python\ndl = DeepLift(model)\nattributions, delta = dl.attribute(input, baseline, target=0, return_convergence_delta=True)\nprint('DeepLift Attributions:', attributions)\nprint('Convergence Delta:', delta)\n```\n输出：\n```\nDeepLift Attributions: tensor([[-0.5922, -1.5497, -1.0067],\n                               [ 0.0000, -0.2219, -5.1991]])\nConvergence Delta: tensor([0., 0.])\n```\n`DeepLift` 为输入分配的归因分数与 `IntegratedGradients` 类似，但其执行时间更短。关于 `DeepLift` 的另一个重要注意事项是，它目前并不支持所有非线性激活函数。有关当前实现局限性的详细信息，请参阅 [DeepLift 论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F1704.02685)。\n\n与 `IntegratedGradients` 类似，`DeepLift` 也会为每个输入示例返回收敛误差。该误差的绝对值可作为算法近似准确性的代理指标。\n\n现在让我们来看看 `DeepLiftShap`。与 `GradientShap` 类似，`DeepLiftShap` 也使用基线分布。在下面的示例中，我们使用了与 `GradientShap` 相同的基线分布。\n\n```python\ndl = DeepLiftShap(model)\nattributions, delta = dl.attribute(input, baseline_dist, target=0, return_convergence_delta=True)\nprint('DeepLiftSHAP Attributions:', attributions)\nprint('Convergence Delta:', delta)\n```\n输出：\n```\nDeepLiftShap Attributions: tensor([[-5.9169e-01, -1.5491e+00, -1.0076e+00],\n                                   [-4.7101e-03, -2.2300e-01, -5.1926e+00]], grad_fn=\u003CMeanBackward1>)\nConvergence Delta: tensor([-4.6120e-03, -1.6267e-03, -5.1045e-04, -1.4184e-03, -6.8886e-03,\n                           -2.2224e-02,  0.0000e+00, -2.8790e-02, -4.1285e-03, -2.7295e-02,\n                           -3.2349e-03, -1.6265e-03, -4.7684e-07, -1.4191e-03, -6.8889e-03,\n                           -2.2224e-02,  0.0000e+00, -2.4792e-02, -4.1289e-03, -2.7296e-02])\n```\n`DeepLiftShap` 使用 `DeepLift` 来计算每个输入-基线对的归因分数，并对所有基线上的每个输入取平均值。\n\n它会为每个输入样本-基线对计算差异值，因此会产生 `input.shape[0] * baseline.shape[0]` 个差异值。\n\n与 GradientShap 类似，为了计算基于样本的差异值，我们可以按样本对它们进行平均：\n```python\ndeltas_per_example = torch.mean(delta.reshape(input.shape[0], -1), dim=1)\n```\n为了平滑并提高归因的质量，我们可以将 `IntegratedGradients` 和其他归因方法通过 `NoiseTunnel` 运行。`NoiseTunnel` 允许我们使用 `SmoothGrad`、`SmoothGrad_Sq` 和 `VarGrad` 技术，通过对多个添加了高斯噪声的样本进行聚合来平滑归因结果。\n\n以下是一个如何将 `NoiseTunnel` 与 `IntegratedGradients` 结合使用的示例。\n\n```python\nig = IntegratedGradients(model)\nnt = NoiseTunnel(ig)\nattributions, delta = nt.attribute(input, nt_type='smoothgrad', stdevs=0.02, nt_samples=4,\n      baselines=baseline, target=0, return_convergence_delta=True)\nprint('IG + SmoothGrad Attributions:', attributions)\nprint('Convergence Delta:', delta)\n```\n输出：\n```\nIG + SmoothGrad Attributions: tensor([[-0.4574, -1.5493, -1.0893],\n                                      [ 0.0000, -0.2647, -5.1619]])\nConvergence Delta: tensor([ 0.0000e+00,  2.3842e-07,  0.0000e+00, -2.3842e-07,  0.0000e+00,\n        -4.7684e-07,  0.0000e+00, -4.7684e-07])\n\n```\n`delta` 张量中的元素数量等于：`nt_samples * input.shape[0]`。为了得到每个样本的差异值，我们可以例如对它们取平均：\n```python\ndeltas_per_example = torch.mean(delta.reshape(input.shape[0], -1), dim=1)\n```\n\n让我们深入研究我们的网络内部，了解哪些层和神经元对预测很重要。\n\n我们将从 `NeuronConductance` 开始。`NeuronConductance` 帮助我们识别对给定层中某个特定神经元重要的输入特征。它通过链式法则分解集成梯度的计算，将神经元的重要性定义为输出对神经元的导数与神经元对模型输入的导数的路径积分乘积。\n\n在本例中，我们选择分析线性层中的第一个神经元。\n\n```python\nnc = NeuronConductance(model, model.lin1)\nattributions = nc.attribute(input, neuron_selector=1, target=0)\nprint('Neuron Attributions:', attributions)\n```\n输出：\n```\nNeuron Attributions: tensor([[ 0.0000,  0.0000,  0.0000],\n                             [ 1.3358,  0.0000, -1.6811]])\n```\n\n层导通率显示了神经元对于某一层及给定输入的重要性。它是隐藏层路径积分梯度的扩展版本，并且同样具有完备性。\n\n它不会将贡献分数归因于输入特征，而是展示所选层中每个神经元的重要性。\n```python\nlc = LayerConductance(model, model.lin1)\nattributions, delta = lc.attribute(input, baselines=baseline, target=0, return_convergence_delta=True)\nprint('Layer Attributions:', attributions)\nprint('Convergence Delta:', delta)\n```\n输出：\n```\nLayer Attributions: tensor([[ 0.0000,  0.0000, -3.0856],\n                            [ 0.0000, -0.3488, -4.9638]], grad_fn=\u003CSumBackward1>)\nConvergence Delta: tensor([0.0630, 0.1084])\n```\n\n与其他返回收敛差值的归因算法类似，`LayerConductance` 也会为每个样本返回差异值。近似误差即为收敛差值的绝对值，可以作为衡量给定输入和基线下积分近似准确性的指标。\n\n有关支持的算法列表以及如何将 Captum 应用于不同类型模型的更多详细信息，请参阅我们的教程。\n\n\n\n## Captum Insights（已停用）\n\nCaptum Insights 在 v0.8.0 版本之后已被弃用，不再受支持。您可以查看 v0.8.0 标签下的仓库以查看已废弃的代码。\n\n## 常见问题解答\n如果您对使用 Captum 方法有任何疑问，请查阅此 [FAQ](docs\u002Ffaq.md)，其中解答了许多常见问题。\n\n## 贡献\n请参阅 [CONTRIBUTING](CONTRIBUTING.md) 文件，了解如何参与贡献。\n\n## 演讲和论文\n**NeurIPS 2019：**\n我们演讲的幻灯片可以在这里找到 [这里](docs\u002Fpresentations\u002FCaptum_NeurIPS_2019_final.key)\n\n**KDD 2020：**\n我们在 KDD 2020 研讨会上的演讲幻灯片可以在这里找到 [这里](https:\u002F\u002Fpytorch-tutorial-assets.s3.amazonaws.com\u002FCaptum_KDD_2020.pdf)。\n您也可以观看录制的演讲 [这里](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=hY_XzglTkak)\n\n**GTC 2020：**\n打开黑箱：使用 Captum 和 PyTorch 理解模型。\n您可以通过观看录制的演讲 [这里](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=0QLrRyLndFI) 来了解更多信息。\n\n**XAI Summit 2020：**\n使用 Captum 和 Fiddler 通过可解释的人工智能提升模型理解能力。\n您可以通过观看录制的演讲 [这里](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=dvuVld5Hyc8) 来了解更多信息。\n\n**PyTorch Developer Day 2020**\n模型可解释性。\n您可以通过观看录制的演讲 [这里](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=Lj5hHBGue58) 来了解更多信息。\n\n**NAACL 2021**\n关于深度 NLP 模型中细粒度解释和因果分析的教程。\n您可以通过观看录制的演讲 [这里](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=ayhBHZYjeqs) 来了解更多信息。\n\n**ICLR 2021 关于负责任的人工智能的研讨会**：\n- [论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F2009.07896) 关于 Captum 库\n- [论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F2106.07475) 关于探索显著性图的合理性检查\n\n\n里昂大学的医学影像暑期学校有一节关于模型可解释性的课程，您可以通过观看 [这里](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=vn-jLzY67V0) 来了解更多信息。\n\n## 算法参考文献\n\n* `IntegratedGradients`、`LayerIntegratedGradients`：[深度神经网络的公理化归因，Mukund Sundararajan 等人，2017 年](https:\u002F\u002Farxiv.org\u002Fabs\u002F1703.01365) 和 [模型是否理解了问题？，Pramod K. Mudrakarta 等人，2018 年](https:\u002F\u002Farxiv.org\u002Fabs\u002F1805.05492)\n* `InputXGradient`：[不只是黑箱：通过传播激活差异学习重要特征，Avanti Shrikumar 等人，2016 年](https:\u002F\u002Farxiv.org\u002Fabs\u002F1605.01713)\n* `SmoothGrad`：[SmoothGrad：通过添加噪声去除噪声，Daniel Smilkov 等人，2017 年](https:\u002F\u002Farxiv.org\u002Fabs\u002F1706.03825)\n* `NoiseTunnel`：[显著性图的合理性检验，Julius Adebayo 等人，2018 年](https:\u002F\u002Farxiv.org\u002Fabs\u002F1810.03292)\n* `NeuronConductance`：[一个神经元有多重要？，Kedar Dhamdhere 等人，2018 年](https:\u002F\u002Farxiv.org\u002Fabs\u002F1805.12233)\n* `LayerConductance`：[高效的内部神经元重要性度量，Avanti Shrikumar 等人，2018 年](https:\u002F\u002Farxiv.org\u002Fabs\u002F1807.09946)\n* `DeepLift`、`NeuronDeepLift`、`LayerDeepLift`：[通过传播激活差异学习重要特征，Avanti Shrikumar 等人，2017 年](https:\u002F\u002Farxiv.org\u002Fabs\u002F1704.02685) 和 [更好地理解基于梯度的深度神经网络归因方法，Marco Ancona 等人，2018 年](https:\u002F\u002Fopenreview.net\u002Fpdf?id=Sy21R9JAW)\n* `NeuronIntegratedGradients`：[高效的内部神经元重要性度量，Avanti Shrikumar 等人，2018 年](https:\u002F\u002Farxiv.org\u002Fabs\u002F1807.09946)\n* `GradientShap`、`NeuronGradientShap`、`LayerGradientShap`、`DeepLiftShap`、`NeuronDeepLiftShap`、`LayerDeepLiftShap`：[解释模型预测的统一方法，Scott M. Lundberg 等人，2017 年](https:\u002F\u002Fproceedings.neurips.cc\u002Fpaper\u002F2017\u002Fhash\u002F8a20a8621978632d76c43dfd28b67767-Abstract.html)\n* `InternalInfluence`：[面向深度卷积神经网络的影响导向解释，Klas Leino 等人，2018 年](https:\u002F\u002Farxiv.org\u002Fabs\u002F1802.03788)\n* `Saliency`、`NeuronGradient`：[深入卷积神经网络：可视化图像分类模型和显著性图，K. Simonyan 等人，2014 年](https:\u002F\u002Farxiv.org\u002Fabs\u002F1312.6034)\n* `GradCAM`、`Guided GradCAM`：[Grad-CAM：通过基于梯度的定位实现深度网络的视觉解释，Ramprasaath R. Selvaraju 等人，2017 年](https:\u002F\u002Farxiv.org\u002Fabs\u002F1610.02391)\n* `Deconvolution`、`Neuron Deconvolution`：[可视化与理解卷积神经网络，Matthew D Zeiler 等人，2014 年](https:\u002F\u002Farxiv.org\u002Fabs\u002F1311.2901)\n* `Guided Backpropagation`、`Neuron Guided Backpropagation`：[追求简单：全卷积网络，Jost Tobias Springenberg 等人，2015 年](https:\u002F\u002Farxiv.org\u002Fabs\u002F1412.6806)\n* `Feature Permutation`：[特征置换重要性](https:\u002F\u002Fchristophm.github.io\u002Finterpretable-ml-book\u002Ffeature-importance.html)\n* `Occlusion`：[可视化与理解卷积神经网络](https:\u002F\u002Farxiv.org\u002Fabs\u002F1311.2901)\n* `Shapley Value`：[n 人博弈的价值。博弈论贡献 2.28（1953）：307–317](https:\u002F\u002Fapps.dtic.mil\u002Fdtic\u002Ftr\u002Ffulltext\u002Fu2\u002F604084.pdf)\n* `Shapley Value Sampling`：[基于采样的 Shapley 值多项式计算](https:\u002F\u002Fwww.sciencedirect.com\u002Fscience\u002Farticle\u002Fpii\u002FS0305054808000804)\n* `Infidelity and Sensitivity`：[关于解释的（不）忠实性和敏感性](https:\u002F\u002Farxiv.org\u002Fabs\u002F1901.09392)\n* `TracInCP`、`TracInCPFast`、`TracInCPRandProj`：[通过追踪梯度下降估计训练数据的影响](https:\u002F\u002Farxiv.org\u002Fabs\u002F2002.08484)\n* `SimilarityInfluence`：[基于预定义相似性度量的训练样本与测试样本之间的成对相似性]\n* `BinaryConcreteStochasticGates`：[具有二值 Concrete 分布的随机门控机制](https:\u002F\u002Farxiv.org\u002Fabs\u002F1712.01312)\n* `GaussianStochasticGates`：[具有高斯分布的随机门控机制](https:\u002F\u002Farxiv.org\u002Fabs\u002F1810.04247)\n\n有关上述[归因算法](https:\u002F\u002Fcaptum.ai\u002Fdocs\u002Fattribution_algorithms)及其优缺点的更多详细信息，请参阅我们的[网站](https:\u002F\u002Fcaptum.ai\u002Fdocs\u002Falgorithms_comparison_matrix)。\n\n## 许可证\nCaptum 采用 BSD 许可证，具体见[LICENSE](LICENSE) 文件。","# Captum 快速上手指南\n\nCaptum 是专为 PyTorch 打造的模型可解释性库，提供集成梯度（Integrated Gradients）、Saliency Maps、DeepLift 等前沿算法，帮助开发者理解模型预测背后的特征贡献、神经元重要性及训练数据影响。\n\n## 环境准备\n\n在开始之前，请确保您的开发环境满足以下最低要求：\n\n*   **Python**: >= 3.10\n*   **PyTorch**: >= 2.3\n*   **操作系统**: Linux, macOS 或 Windows\n\n## 安装步骤\n\n推荐使用 `pip` 安装最新稳定版。国内用户建议使用清华或阿里镜像源以加速下载。\n\n**使用 pip 安装（推荐）**\n\n```bash\npip install captum -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple\n```\n\n**开发者安装（获取最新特性）**\n\n如果您需要体验 GitHub 上的最新功能（可能包含未稳定的 Bug），可源码安装：\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum.git\ncd captum\npip install -e . -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple\n```\n\n*注：若需运行官方教程笔记，可使用 `pip install -e .[tutorials]`。*\n\n## 基本使用\n\n以下示例演示如何在一个简单的 PyTorch 模型上使用 **Integrated Gradients (IG)** 算法计算输入特征的归因分数。\n\n### 1. 定义模型与数据\n\n首先构建一个简单的全连接网络，并设置输入张量和基线（Baseline）。基线通常设为零张量，代表无预测信号的状态。\n\n```python\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom captum.attr import IntegratedGradients\n\n# 定义一个简单的玩具模型\nclass ToyModel(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.lin1 = nn.Linear(3, 3)\n        self.relu = nn.ReLU()\n        self.lin2 = nn.Linear(3, 2)\n\n        # 初始化权重和偏置以便复现结果\n        self.lin1.weight = nn.Parameter(torch.arange(-4.0, 5.0).view(3, 3))\n        self.lin1.bias = nn.Parameter(torch.zeros(1,3))\n        self.lin2.weight = nn.Parameter(torch.arange(-3.0, 3.0).view(2, 3))\n        self.lin2.bias = nn.Parameter(torch.ones(1,2))\n\n    def forward(self, input):\n        return self.lin2(self.relu(self.lin1(input)))\n\n# 实例化模型并设为评估模式\nmodel = ToyModel()\nmodel.eval()\n\n# 固定随机种子以确保结果可复现\ntorch.manual_seed(123)\nnp.random.seed(123)\n\n# 定义输入和基线\ninput = torch.rand(2, 3)\nbaseline = torch.zeros(2, 3)\n```\n\n### 2. 应用归因算法\n\n使用 `IntegratedGradients` 计算每个输入特征对目标类别（此处为 `target=0`）的贡献度。\n\n```python\n# 初始化算法\nig = IntegratedGradients(model)\n\n# 计算归因分数\n# return_convergence_delta=True 用于检查积分近似误差，值越小越准确\nattributions, delta = ig.attribute(input, baseline, target=0, return_convergence_delta=True)\n\nprint('IG Attributions:', attributions)\nprint('Convergence Delta:', delta)\n```\n\n**输出示例：**\n```text\nIG Attributions: tensor([[-0.5922, -1.5497, -1.0067],\n                         [ 0.0000, -0.2219, -5.1991]])\nConvergence Delta: tensor([2.3842e-07, -4.7684e-07])\n```\n\n### 结果解读\n\n*   **Attributions (归因分数)**: \n    *   **正值**表示该特征对预测结果有正向贡献。\n    *   **负值**表示该特征对预测结果有负向贡献。\n    *   **绝对值大小**代表贡献的强度。\n*   **Convergence Delta**: 表示积分近似的误差。如果该值较大，可以通过增加 `n_steps` 参数来提高计算精度（例如：`ig.attribute(..., n_steps=50)`）。\n\n除了 `IntegratedGradients`，Captum 还支持 `GradientShap`、`DeepLift`、`Saliency` 等多种算法，使用方法类似，只需替换对应的类即可。","某金融风控团队正在优化基于 PyTorch 构建的信贷拒批模型，急需向监管机构和用户解释为何特定申请被拒绝。\n\n### 没有 captum 时\n- 模型如同“黑盒”，开发人员仅能依赖整体准确率指标，无法定位导致拒批的具体特征（如收入、负债比或历史逾期）。\n- 面对用户的申诉，只能给出模糊的官方回复，缺乏数据支撑的具体理由，导致客户信任度下降且投诉率居高不下。\n- 调试模型偏差时，工程师需手动编写复杂的梯度计算代码来验证假设，耗时数天且容易出错，严重拖慢迭代速度。\n- 难以发现模型是否错误地依赖了敏感属性（如邮编隐含的地区歧视），存在合规隐患却无法自证清白。\n\n### 使用 captum 后\n- 利用集成梯度（Integrated Gradients）算法，captum 直接生成可视化的特征贡献图，精确量化每个输入变量对拒批结果的负面影响权重。\n- 系统能自动生成个性化的解释报告（例如：“您的申请主要因近三个月信用卡利用率过高而被拒”），显著提升沟通透明度和用户满意度。\n- 研究人员通过内置的 TCAV 方法快速测试概念激活向量，几小时内即可验证模型是否学到了错误的业务逻辑，大幅缩短排查周期。\n- 借助归因分析轻松识别并剔除模型对敏感特征的隐性依赖，确保决策公平性，轻松满足金融监管的可解释性审计要求。\n\ncaptum 将不可知的深度学习预测转化为清晰可信的决策依据，让 AI 模型在严谨的金融场景中真正落地可用。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmeta-pytorch_captum_7884fa02.png","meta-pytorch","Meta PyTorch","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fmeta-pytorch_1dfd3f76.jpg","",null,"https:\u002F\u002Fpytorch.org","https:\u002F\u002Fgithub.com\u002Fmeta-pytorch",[81,85,89,93,97,101],{"name":82,"color":83,"percentage":84},"Python","#3572A5",97.1,{"name":86,"color":87,"percentage":88},"JavaScript","#f1e05a",1.3,{"name":90,"color":91,"percentage":92},"CSS","#663399",1.1,{"name":94,"color":95,"percentage":96},"Shell","#89e051",0.4,{"name":98,"color":99,"percentage":100},"Batchfile","#C1F12E",0,{"name":102,"color":103,"percentage":100},"Makefile","#427819",5592,558,"2026-04-04T12:50:14","BSD-3-Clause",1,"未说明",{"notes":111,"python":112,"dependencies":113},"该工具是 PyTorch 的模型可解释性库。虽然 README 未明确列出支持的操作系统，但作为 PyTorch 生态的一部分，通常支持 Linux、macOS 和 Windows。GPU 需求和内存需求取决于所分析的具体模型大小及任务复杂度，文中未给出固定硬件指标。可通过 pip 或 conda 安装，开发版支持额外安装测试和教程依赖。",">=3.10",[114],"torch>=2.3",[14,116],"其他",[118,119,120,121,122],"interpretability","interpretable-ai","interpretable-ml","feature-importance","feature-attribution","2026-03-27T02:49:30.150509","2026-04-11T16:52:57.921011",[126,131,136,140,145,150],{"id":127,"question_zh":128,"answer_zh":129,"source_url":130},17011,"如何在 Captum 中为不支持的层（如 nn.Flatten）自定义 LRP 传播规则？","如果遇到 'Can't instantiate abstract class PropagationRule' 错误，需要为该层显式定义规则。根据 LRP 文档，给定层的自定义规则需要定义为属性 `module.rule`，且类型必须为 `PropagationRule`。如果您找到了合适的规则，可以将其添加到 `SUPPORTED_LAYERS_WITH_RULES` 中并提交 PR。","https:\u002F\u002Fgithub.com\u002Fmeta-pytorch\u002Fcaptum\u002Fissues\u002F143",{"id":132,"question_zh":133,"answer_zh":134,"source_url":135},17012,"如何将 Captum 与 BERT 或 Hugging Face Transformers 模型集成以进行归因分析？","可以使用专门针对 BERT 的二分类示例 Notebook 作为参考。社区提供了一个 Colab 笔记本（链接：https:\u002F\u002Fcolab.research.google.com\u002Fdrive\u002F1pgAbzUF2SzF0BdFtGpJbZPWUOhFxT2NZ），展示了如何结合 BERT 和 Captum 进行工作。此外，也可以参考相关的 Gist 代码库获取实现细节。","https:\u002F\u002Fgithub.com\u002Fmeta-pytorch\u002Fcaptum\u002Fissues\u002F150",{"id":137,"question_zh":138,"answer_zh":139,"source_url":135},17013,"在使用 Integrated Gradients 对 BERT 进行归因时，遇到张量尺寸不匹配（如 768 vs 6 或 53）的 RuntimeError 如何解决？","该错误通常是因为基线（baselines）输入的形状与嵌入层输出的形状不一致导致的。在调用 `ig.attribute` 时，确保传入的 `baselines` 张量维度与 `input_embedding` 的维度完全匹配。例如，如果输入是 token IDs，可能需要先将其转换为嵌入向量，或者确保基线张量的形状在除批次维外的所有维度上与输入一致。",{"id":141,"question_zh":142,"answer_zh":143,"source_url":144},17014,"为什么 BERT 序列分类模型的归因可视化结果看起来相似，即使预测分数差异巨大？如何改进？","这可能是因为默认的步数（steps）不足以捕捉细微的梯度变化。尝试增加 `n_steps` 参数（例如增加到 500 或更多）可以获得更好的归因效果，使模型更准确地聚焦于导致分类差异的关键 token（如语法错误处的动词或名词）。","https:\u002F\u002Fgithub.com\u002Fmeta-pytorch\u002Fcaptum\u002Fissues\u002F311",{"id":146,"question_zh":147,"answer_zh":148,"source_url":149},17015,"使用 LayerIntegratedGradients 解释 BERT 模型时，遇到 'forward hooks should never return any values' 错误的原因是什么？","这个错误通常发生在自定义的前向函数（custom_forward）中直接返回了值，而 PyTorch 的 hook 机制要求钩子函数返回 None。请检查您的 `custom_forward` 定义，确保它只是执行前向传播并返回所需的输出张量，而没有在内部钩子中错误地返回值。同时，确保 `additional_forward_args` 中的参数（如 attention_mask）正确传递且未导致内部逻辑异常。","https:\u002F\u002Fgithub.com\u002Fmeta-pytorch\u002Fcaptum\u002Fissues\u002F373",{"id":151,"question_zh":152,"answer_zh":153,"source_url":149},17016,"在使用 Captum 分析 BERT 模型时，为什么除了第一个 token 外，其他所有 token 的归因值都是零？","这种情况通常是由于输入处理或基线设置不当造成的。请检查是否正确地构建了输入张量和基线张量，确保它们具有相同的形状和数据类型。此外，确认模型的前向传播逻辑是否正确处理了注意力掩码（attention_mask）和 token 类型 ID。如果问题依然存在，建议参考官方教程中关于 BERT SQUAD 解释的完整代码流程，对比输入预处理步骤。",[155,160,165,170,175,180,185,190,195,200],{"id":156,"version":157,"summary_zh":158,"released_at":159},99260,"v0.8.0","Captum v0.8.0 版本新增了用于数据归因的影响力函数，改进了特征归因方法（包括对大型语言模型提示词的归因），增强了现代 Python 类型检查的类型注解，并进行了其他多项小幅改进。需要注意的是，该版本已不再支持 Python 3.8 和 PyTorch 1.10，且 Captum Insights 将在下一个主要版本中被弃用。\n\n# 数据归因：新增影响力函数\n\n此版本提供了两种不同的实现方式，它们都按照论文《通过影响力函数理解黑盒预测》（https:\u002F\u002Farxiv.org\u002Fpdf\u002F1703.04730.pdf）中定义的“无穷小”影响力分数进行计算。\n- `NaiveInfluenceFunction`：这是一种计算速度较慢但精确的实现，适用于获取“真值”参考（不过需注意，影响力分数本身是对移除样本后重新训练效果的一种近似）。实际上，已有数篇论文采用这种方法，例如《通过影响力函数学习增强网络》（https:\u002F\u002Fopenaccess.thecvf.com\u002Fcontent_CVPR_2020\u002Fpapers\u002FLee_Learning_Augmentation_Network_via_Influence_Functions_CVPR_2020_paper.pdf）、《量化并缓解标签错误对模型差异性指标的影响》（https:\u002F\u002Fopenreview.net\u002Fforum?id=RUzSobdYy0V）、《通过基于影响力的样本重加权实现无效用损失的公平性》（https:\u002F\u002Fproceedings.mlr.press\u002Fv162\u002Fli22p\u002Fli22p.pdf）。（PR https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum\u002Fpull\u002F1214）\n- `ArnoldiInfluenceFunction`：这是由 Schioppa 等人在论文《扩展影响力函数》（https:\u002F\u002Fl.facebook.com\u002Fl.php?u=https%3A%2F%2Farxiv.org%2Fpdf%2F2112.03052.pdf&h=AT0QVmLyIXhxubw9fqxG6ULdy-lyAHPchGhHbXAwbM3GU1zQEUm1XPAk5ymiw11nONY4mWzJg10CSYlX5R3VJ5Ty7Y-WkawSfnSsWpaJLVPP_k2RpiSNNT80DeP9qS_3yT2a9Y3gb2ZTBhFCLipcnIyLOwWN）中提出的一种计算效率更高的实现。（PR https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum\u002Fpull\u002F1187）\n\n示例：\n\n```python\nfrom captum.influence._core.influence_function import NaiveInfluenceFunction\nfrom torch import nn\nfrom torch.utils.data import DataLoader\n\ntrain_dl = DataLoader(your_dataset, batch_size=8)  # 您的数据加载器\ncriterion = nn.MSELoss(reduction=\"none\")\ninfluence = NaiveInfluenceFunction(\n    net,\n    train_dl,\n    checkpoint_path,  # 您的模型检查点路径\n    loss_fn=criterion,\n    batch_size=batch_size,\n)\n\n# 使用影响力实现计算成对影响\ninfluence_train_test_influences = influence.influence(\n    (test_samples, test_labels)  # 您的测试数据（张量）\n)\n``` \n\n## 什么是“无穷小”影响力分数？\n关于“无穷小”影响力分数的更多细节：该分数近似回答了一个问题：如果将某个训练样本的权重无限微小地降低，并重新训练模型至最优状态，那么给定测试样本上的损失会变化多少？从数学上看，上述影响力分数可表示为 $\\nabla_\\theta L(x)' H^{-1} \\nabla_\\theta L(z)$，其中 $\\nabl","2025-03-27T04:51:30",{"id":161,"version":162,"summary_zh":163,"released_at":164},99261,"v0.7.0","Captum 0.7.0 版本新增了针对语言模型归因、数据集级别归因的功能，并对现有方法进行了一些改进和错误修复。\n\n## 语言模型归因\n\nCaptum 0.7.0 新增了用于语言模型归因的 API，使得定义可解释的文本特征及其对应的基线和掩码变得更加简便。这些新封装器与 Captum 中的大多数归因方法兼容，从而更容易理解提示中的各个部分如何影响大型语言模型的预测结果。更多详细信息请参阅我们的论文：\n\n[使用 Captum 解释生成式语言模型](https:\u002F\u002Farxiv.org\u002Fabs\u002F2312.05491)\n\n示例：\n\n```py\nfrom captum.attr import ShapleyValueSampling, LLMAttribution, TextTemplateInput\n\nshapley_values = ShapleyValueSampling(model)\nllm_attr = LLMAttribution(shapley_values, tokenizer)\n\ninp = TextTemplateInput(\n    # 文本模板\n    \"{} 生活在 {}, {}，是一名 {}. {} 的个人兴趣包括\",\n    # 特征的具体取值\n    [\"Dave\", \"Palm Coast\", \"FL\", \"律师\", \"他的\"],\n    # 特征的参考基线取值\n    baselines=[\"Sarah\", \"Seattle\", \"WA\", \"医生\", \"她的\"],\n)\nres = llm_attr.attribute(inp)\n```\n\n![image](https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum\u002Fassets\u002F5113450\u002F36434dd0-4360-4e3c-bae6-eaa756e5c570)\n\n## 数据加载器归因\n\n数据加载器归因是一个新的封装器，它通过提供数据加载器而非单个输入，为在整个数据集上获取归因提供了一种易于使用的途径（PR #1155、#1158）。\n\n## 归因方法改进\n\nCaptum 0.7.0 对现有归因方法进行了若干改进，包括：\n- 现已支持 Shapley 值和 Shapley 值采样的多任务归因，允许用户同时获得多个目标输出的归因（PR #1173）；\n- LayerGradCam 现在支持独立返回每个通道的归因，而无需对通道进行求和（PR #1086，感谢 @dzenanz 的贡献）。\n\n## 错误修复\n\n- 可视化工具已更新为使用新的关键字参数 `visible`，以确保与 Matplotlib 3.7 兼容（PR #1118）；\n- `visualize_timeseries_attr` 中的默认可视化模式已修复，能够正确地利用 `overlay_individual` 功能（PR #1152，感谢 @teddykoker 的贡献）。","2023-12-05T09:21:02",{"id":166,"version":167,"summary_zh":168,"released_at":169},99262,"v0.6.0","Captum v0.6.0 版本引入了一个新特性 `StochasticGates`。该版本还增强了“有影响力样本”功能，并包含一系列其他改进和错误修复。\n\n## 随机门控\n随机门控是一种通过近似 L0 正则化来强制稀疏性的技术，可用于网络剪枝和特征选择。由于直接优化 L0 是一个不可微的组合优化问题，随机门控通过使用某些连续概率分布（例如 Concrete 分布、高斯分布）作为平滑的伯努利分布来对其进行近似。这样，优化问题就可以重新参数化为这些分布的参数。更多细节请参阅以下论文：\n\n- [通过 L0 正则化学习稀疏神经网络](https:\u002F\u002Farxiv.org\u002Fabs\u002F1712.01312)\n- [使用随机门控进行特征选择](https:\u002F\u002Farxiv.org\u002Fabs\u002F1810.04247)\n\nCaptum 提供了两种基于不同分布的随机门控实现，分别作为平滑的伯努利分布：`BinaryConcreteStochasticGates` 和 `GaussianStochasticGates`。它们位于 `captum.module` 中，这是一个新的子包，用于收集对模型理解有用的神经网络构建模块。以下是一个使用示例：\n\n```py\nfrom captum.module import GaussianStochasticGates\n\nn_gates = 5  # 门控的数量\nstg = GaussianStochasticGates(n_gates, reg_weight=0.01)\n\ninputs = torch.randn(3, n_gates)  # 模拟批次大小为 3 的输入\n\ngated_inputs, reg = stg(inputs)  # 对输入进行门控\nloss = model(gated_inputs)  # 在下游网络中使用门控后的输入\n\n# 将稀疏性正则化与模型损失一起优化\nloss += reg \n\n...\n\n# 验证学习到的门控值，以了解模型如何利用这些输入\nprint(stg.get_gate_values()) \n```\n\n## 有影响力样本\n“有影响力样本”是上一版本中新增的功能支柱。本次发布继续聚焦于此，并在现有的 `TracInCP` 系列基础上进行了大量改进。其中一些更改与旧版本不兼容。以下是详细说明：\n\n- `TracInCPFast` 和 `TracInCPFastRandProj` 支持 reduction 为 `mean` 的损失函数（https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum\u002Fpull\u002F913）\n- `TracInCP` 类新增了一个 `show_progress` 参数，可选地显示计算进度条（https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum\u002Fpull\u002F898、https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum\u002Fpull\u002F1046）\n- `TracInCP` 提供了一个新的公共方法 `self_influence`，用于计算给定数据集中各样本之间的自影响得分。`influence` 方法不再支持计算自影响得分，且参数 `inputs` 不能为 `None`（https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum\u002Fpull\u002F994、https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum\u002Fpull\u002F1069、https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum\u002Fpull\u002F1087、https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum\u002Fpull\u002F1072）\n- `TracInCP` 中之前的构造函数参数 `influence_src_dataset` 已更名为 `train_dataset`（https:\u002F\u002Fgithub.com\u002Fpytorch\u002Fcaptum\u002Fpull\u002F994）\n- 为 `Tr`","2022-12-28T01:14:50",{"id":171,"version":172,"summary_zh":173,"released_at":174},99263,"v0.5.0","Captum v0.5.0 版本引入了一个新的功能模块——“有影响力样本”，并进行了一些代码改进和错误修复。\n\n## 有影响力样本\n\n“有影响力样本”实现了 [TracInCP](https:\u002F\u002Farxiv.org\u002Fabs\u002F2002.08484) 方法。它计算给定训练样本对给定测试样本的影响得分，从而近似回答这样一个问题：“如果从训练数据中移除该训练样本，模型的损失会变化多少？” TracInCP 可用于：\n- 识别 **支持者\u002F反对者**，即对给定测试样本具有最大正向\u002F负向影响的训练样本；\n- 识别标注错误的数据。\n\n目前，Captum 提供了以下几种 TracInCP 的具体实现：\n* `TracInCP` - 使用所有指定层的梯度计算影响得分。可用于识别支持者\u002F反对者，以及标注错误的数据。这两种计算的时间复杂度均与训练数据规模呈线性关系。\n* `TracInCPFast` - 类似于 TracInCP，但仅使用最后一个全连接层的梯度来计算影响得分，并通过一种计算技巧加速处理。\n* `TracInCPFastRandProj` - 是 TracInCPFast 的一个变体，专门用于计算支持者\u002F反对者。通过预处理，可以在常数时间内完成支持者\u002F反对者的计算。其代价是需要线性时间及内存来进行预处理。可以使用随机投影来降低内存消耗。该类不应用于识别标注错误的数据。\n\n我们提供了一个教程来演示其用法：https:\u002F\u002Fcaptum.ai\u002Ftutorials\u002FTracInCP_Tutorial\n\u003Cimg width=\"768\" alt=\"influential example\" src=\"https:\u002F\u002Fuser-images.githubusercontent.com\u002F5113450\u002F156647765-7b3c72a8-ea76-4d99-b735-4e73ba44efb5.png\">\n\n## 主要变更\n\n* 最低支持的 PyTorch 版本提升至 **v1.6.0** (#876)\n* 在 `TCAV` 中启用 `model_id` 参数，并从公共概念模块中移除 `AV`（PR #811）\n* 在 `TCAV` 中新增可配置参数 `attribute_to_layer_input`，用于同时设置层激活值和归因计算（#864）\n* 将可视化工具 `VisualizationDataRecord` 中的参数 `raw_input` 重命名为 `raw_input_ids`（PR #804）\n* 支持在 `DeepLift` 中配置 `eps` 参数（PR #835）\n* Captum 现在利用 PyTorch v1.8.0 引入的 `register_full_backward_hook`。`NeuronDeepLift`、`NeuronGuidedBackprop` 和 `NeuronDeconvolution` 中针对神经元输出的归因功能已被弃用，将在下一个主要版本 v0.6.0 中移除（PR #837）\n* 修复了 Lime 和 KernelShap 无法处理空张量输入（如 `tensor([[],[],[]])`）的问题（PR #812）\n* 修复了 Captum Insight 中 `ImageFeature` 的 `visualization_transform` 未被应用的 bug（PR #871）","2022-03-04T00:37:56",{"id":176,"version":177,"summary_zh":178,"released_at":179},99264,"v0.4.1","Captum v0.4.1 版本包含三个新的教程、一些代码改进以及错误修复。\n\n## 新增教程\n\n鲁棒性教程：\n\n* 将鲁棒性攻击和评估指标应用于 CIFAR 模型及数据集\n\n概念相关教程：\n\n* 用于 GoogLeNet 图像分类模型的 TCAV\n* 用于 NLP 情感分析模型的 TCAV\n\n## 改进\n\n* 在代码库中减少了对 `Numpy` 的不必要依赖，尽可能用 `PyTorch` 的等效实现替代（PR #714、#755、#760）\n* 改进了 LRP 中缺失模块规则的错误提示信息（PR #727）\n* 将代码格式化工具从之前的 `black` + `isort` 切换为 `ufmt`，并相应地重新格式化了代码（PR #739）\n* 对 TCAV 中用于计算平均值的 `captum._utils.av` 实现进行了通用化改造，并重构了 TCAV 代码，以简化用于训练概念模型的数据集创建过程（PR #747）\n\n## 错误修复\n\n* 修复了在 CUDA 上使用 TCAV 时出现的设备错误（Issue #719、#720、#721，PR #725）\n* Captum Insight 现在会缓存数据集中的一部分批次，以便重复使用，从而解决遍历完所有批次后无法显示数据的问题（PR #728）\n* 修正了“Interpreting Bert Part 1”教程中参考词嵌入加载的错误（PR #743）\n* 将工具函数 `save_div` 的参数 `default_value` 重命名为 `default_denom`，并统一了其在不同分母类型下的行为（Issue #654，PR #751）","2021-11-02T21:47:58",{"id":181,"version":182,"summary_zh":183,"released_at":184},99265,"v0.4.0","Captum 0.4.0 版本新增了基于概念的可解释性功能、模型鲁棒性评估工具、包括逐层相关性传播（LRP）在内的新型归因方法，以及对现有归因方法的改进。\n\n## 基于概念的可解释性\n\nCaptum 0.4.0 在 Captum 中加入了 TCAV（使用概念激活向量进行测试）功能，使用户能够识别自定义概念对模型预测的重要性。TCAV 以通用方式实现，允许用户为任何模态（包括视觉和文本）定义自定义概念，并提供示例输入。\n\n## 鲁棒性\n\nCaptum 0.4.0 还包含用于理解模型鲁棒性的新工具，包括对抗攻击的实现（快速梯度符号法和投影梯度下降法），以及用于评估不同攻击或扰动对模型影响的鲁棒性指标。本次发布的鲁棒性指标包括：\n\n* 攻击比较器——允许用户量化任意输入扰动（如 torchvision 变换、文本增强等）或对抗攻击对模型的影响，并比较不同攻击的效果。\n* 最小扰动——识别导致模型将扰动后的输入错误分类所需的最小扰动量。\n\n这些鲁棒性工具使模型开发者能够更好地理解潜在的模型漏洞，并分析反事实示例，从而更深入地了解模型的决策边界。\n\u003Cimg width=\"572\" alt=\"Screen Shot 2021-07-06 at 11 11 54 PM\" src=\"https:\u002F\u002Fuser-images.githubusercontent.com\u002F11067177\u002F124703465-9d062200-deaf-11eb-8338-6e62191d662d.png\">\n\n## 逐层相关性传播（LRP）\n\n在 0.4.0 版本中，我们还向 Captum 新增了一种归因方法——LRP（逐层相关性传播），以及其变体“层级 LRP”。逐层相关性传播基于一种反向传播机制，该机制按顺序应用于模型的所有层。模型输出分数代表初始相关性，随后被分解为底层各神经元的相关值。感谢 @nanohanno 贡献了这一方法，也感谢 @rGure 提供的反馈！\n\n## 新教程\n\n我们新增了若干教程，演示如何结合 BERT 使用 Captum、LIME 的用法，以及 DLRM 推荐模型的使用。这些教程包括：\n\n* 解释 BERT 模型（第 2 部分）\n* 用于图像与文本分类的 LIME\n* 使用 Captum 解释深度学习推荐模型（DLRMs）（https:\u002F\u002Fgithub.com\u002Ffacebookresearch\u002Fdlrm）\n\n此外，我们还对现有教程进行了以下修复和更新：\n\n* IMDB 教程已更新为使用新模型（采用更大规模的嵌入并更新了依赖项），以提高可复现性。\n* 解释 BERT 模型（第 1 部分）现已更新，支持同时使用多层的 LayerIntegratedGradients 方法获取归因结果。\n\n## 归因方法改进\n\nCaptum 0.4.0 新增了","2021-07-07T05:16:49",{"id":186,"version":187,"summary_zh":188,"released_at":189},99266,"v0.3.1","Captum v0.3.1 在 v0.3.0 增加的功能基础上，进一步进行了多项改进和小修复。\n\n\n# 改进\n\nCaptum v0.3.1 对现有归因方法进行了优化，包括：\n\n* LayerIntegratedGradients 现在支持同时计算多个层的归因值。（PR #532）\n* NoiseTunnel 现在支持设置内部批大小，将加噪后的输入拆分为多个批次并正确聚合结果。（PR #555）\n* visualize_text 新增了 return_html 选项，可将可视化结果导出为 HTML 代码。（PR #548）\n* 添加了一个实用的封装器，用于同时计算中间层和输入的归因值。（PR #534）\n\n## Captum Insights\n\n* 在 Captum Insights 中可以比较多个模型的归因结果。（PR #551）\n* 对 Captum Insights 进行了多项优化，以减小包体积。（PR #556 和 #562）\n\n![image](https:\u002F\u002Fuser-images.githubusercontent.com\u002F11067177\u002F105610180-5cd93a00-5d7c-11eb-868c-1254e9436a74.png)\n\n\n# 错误修复\n\n* 为避免在将 Noise Tunnel 或指标与归因方法结合使用时出现命名冲突，对 NoiseTunnel、Kernel Shap 和 Lime 中的部分参数名称进行了重命名。已弃用的参数现在会发出警告，并将在 0.4.0 版本中被移除。（PR #558）\n* Feature Ablation 现在支持输出位于不同设备上的情况，这在模型并行设置中可能会出现。（#528）\n* 修复了 Lime（以及 KernelShap）对 int 或 long 类型输入的处理问题。（#570）","2021-01-23T18:11:12",{"id":191,"version":192,"summary_zh":193,"released_at":194},99267,"v0.3.0","Captum 的第三个版本 v0.3.0 新增了多项功能，包括 Lime 和 KernelSHAP 等新的归因算法、用于评估归因结果的不忠实度和敏感性等指标，以及对现有归因方法的改进。\n\n## 指标（敏感性和不忠实度）\n\nCaptum 0.3.0 新增了用于评估模型解释可信度的指标。目前可用的指标包括 Sensitivity-Max 和 Infidelity。\n\n不忠实度衡量的是，在输入扰动的不同幅度下，模型归因与预测函数对这些扰动的实际响应之间的均方误差。而敏感性则通过基于蒙特卡洛采样的近似方法，来度量解释对细微输入扰动的变化程度。这些指标可在 captum.metrics 中找到，相关文档请参阅 [这里](https:\u002F\u002Fcaptum.ai\u002Fapi\u002Fmetrics.html)。\n\n## Lime 和 KernelSHAP\n\n在 Captum 0.3.0 中，我们还新增了基于代理模型的可解释性方法，包括 [Lime](https:\u002F\u002Fcaptum.ai\u002Fapi\u002Flime.html) 和 [KernelSHAP](https:\u002F\u002Fcaptum.ai\u002Fapi\u002Fkernel_shap.html)。Lime 是一种可解释性方法，它通过在指定输入示例周围采样点，并利用这些点上的模型预测结果来训练一个更简单的可解释“代理”模型，例如线性模型。\n\n我们提供了该方法的两种实现变体：LimeBase 和 Lime。LimeBase 提供了一个通用框架，用于训练可解释的代理模型；而 Lime 则是在 LimeBase 的基础上进行了更具体的实现，以便与其他基于扰动的算法保持一致的 API 接口。KernelSHAP 是一种利用 Lime 框架来计算 Shapley 值的方法。\n\n## 新教程\n\n我们新增了一些教程，用于演示如何在计算机视觉任务（如分割）以及分布式环境中使用 Captum。这些教程包括：\n\n* 使用 Captum 与 torch.distributed\n* 解释语义分割模型\n\n\u003Cimg width=\"1050\" alt=\"Screen Shot 2020-11-10 at 12 31 31 AM\" src=\"https:\u002F\u002Fuser-images.githubusercontent.com\u002F11067177\u002F99131417-167b9800-25e1-11eb-8761-de7a5bbceb75.png\">\n\n## 归因方法的改进\n\nCaptum 0.3.0 对现有归因方法进行了多项改进，主要包括：\n\n* LayerActivation 和 LayerGradientXActivation 现在支持同时计算多个层的归因。（PR #456）\n* 神经元归因方法现在支持提供一个可调用对象，用于选择或聚合多个神经元进行归因，同时也支持通过切片来选择一定范围内的神经元。（PR #490、#495）参数名 neuron_index 已被弃用，取而代之的是 neuron_selector，它既可接受索引，也可接受可调用对象。\n* 特征消融和特征置换现在允许同时针对多个批次聚合标量（例如损失）进行归因。（PR #425）\n* 大多数归因方法现在都支持 multiply_by_inputs 参数。对于那些包含输入或输入减去基线乘数的归因方法，这…","2020-11-13T23:52:08",{"id":196,"version":197,"summary_zh":198,"released_at":199},99268,"v0.2.0","Captum 的第二个版本 v0.2.0 新增了多种新的归因算法，并提供了额外的教程、类型提示以及对 Captum Insights 的 Google Colab 支持。\n\n### 新的归因算法\n\n以下是一些新增的归因算法，它们可以应用于任何类型的 PyTorch 模型，包括 DataParallel 模型。虽然第一个版本主要关注基于梯度的归因方法，例如集成梯度法，但新算法中包含了基于扰动的方法，这些方法在下方用 ^ 标示。此外，我们还增加了专为卷积网络设计的新归因方法，这些方法在下方用 * 标示。所有归因方法都采用一致的 API 结构，便于用户在不同方法之间切换。\n\n**针对输入特征的模型输出归因：**\n\n1. 引导反向传播 *  \n2. 反卷积 *  \n3. 引导 GradCAM *  \n4. 特征消融 ^  \n5. 特征置换 ^  \n6. 屏蔽 ^  \n7. 夏普利值采样 ^  \n\n**针对模型各层的模型输出归因：**\n\n1. 层级 GradCAM  \n2. 层级集成梯度  \n3. 层级 DeepLIFT  \n4. 层级 DeepLIFT SHAP  \n5. 层级梯度 SHAP  \n6. 层级特征消融 ^  \n\n**针对神经元的输入特征归因：**\n\n1. 神经元 DeepLIFT  \n2. 神经元 DeepLIFT SHAP  \n3. 神经元梯度 SHAP  \n4. 神经元引导向后传播 *  \n5. 神经元反卷积 *  \n6. 神经元特征消融 ^  \n\n^ 表示基于扰动的算法。这些方法通过评估模型在输入扰动版本上的表现来计算归因，而不是使用梯度信息。  \n\\* 表示主要为卷积网络设计的归因方法。\n\n### 新教程\n\n我们新增了多个教程，用于演示如何在 BERT 模型、回归场景以及基于扰动的方法中使用 Captum。这些教程包括：\n\n* 使用 BERT 解释问答任务  \n* 使用波士顿房价数据集解释回归模型  \n* 图像上的特征消融  \n\n![屏幕截图 2020-03-04 下午 3:35:25](https:\u002F\u002Fuser-images.githubusercontent.com\u002F11067177\u002F75950339-b6333480-5e5d-11ea-8161-ee05c743331c.png)\n\n### 类型提示\n\nCaptum 的代码库现已完全使用 Python 类型提示进行标注，并通过 mypy 进行类型检查。用户现在可以对使用 Captum 的代码进行准确的类型检查。\n\n### 错误修复与次要功能\n\n* 所有 Captum 方法现在都支持就地模块和操作。（问题 #156）  \n* 修正了收敛误差的计算，使其在 CUDA 设备上能够正常工作。（问题 #163）  \n* 为层级 GradCAM 添加了一个 ReLU 标志，以便可选地对返回的归因结果应用 ReLU 操作。（问题 #179）  \n* 所有层级和神经元归因方法现在都支持根据 `attribute_to_layer_input` 和 `attribute_to_neuron_input` 标志，分别针对模块的输入或输出进行归因。  \n* 所有层级归因方法现在都支持具有多个输出的模块。\n\n**Captum Insight**","2020-03-06T23:43:53",{"id":201,"version":202,"summary_zh":203,"released_at":204},99269,"v0.1.0","我们刚刚发布了用于模型可解释性的 PyTorch Captum 库的第一个版本！\r\n\r\n## 亮点\r\n\r\n本次发布的 v0.1.0 版本支持多种基于梯度的归因算法，以及 Captum Insights——一款用于模型调试与理解的可视化工具。\n\n### 归因算法\n\n提供了以下通用的基于梯度的归因算法。这些算法可以应用于任何类型的 PyTorch 模型和输入特征，包括图像、文本以及多模态数据。\n\n1. 针对输入特征的模型输出归因\n    1. **Saliency**\n    2. **InputXGradient**\n    3. **IntegratedGradient**\n    4. **DeepLift**\n    5. **DeepLiftShap**\n    6. **GradientShap**\n\n1. 针对模型各层的模型输出归因\n    1. **LayerActivation**\n    2. **LayerGradientXActivation**\n    3. **LayerConductance**\n    4. **InternalInfluence**\n\n1. 针对神经元的输入特征归因\n    1. **NeuronGradient**\n    2. **NeuronIntegratedGradients**\n    3. **NeuronConductance**\n\n2. 归因算法 + 噪声采样\n    1. **NoiseTunnel**\n        NoiseTunnel 通过使用 SmoothGrad、SmoothGrad_SQ 和 VarGrad 等不同的噪声隧道技术，帮助降低归因算法所分配的归因结果中的噪声。\n\n### 批量与数据并行优化\n\n由于一些算法（如 Integrated Gradients）会在内部扩展输入张量，因此我们需要确保能够高效地扩展这些张量，并优化前向和反向传播计算。为此，我们开发了一项功能：将张量在内部切分为 `internal_batch_size` 个块，该参数可通过 `attribute` 方法传入。这样一来，库会分别对每个张量批次执行前向和反向传播，并在计算完梯度后将其合并。\n\n支持批量优化的算法包括：\n\n1. IntegratedGradients\n2. LayerConductance\n3. InternalInfluence\n4. NeuronConductance\n\n此外，Captum 的所有算法均支持 PyTorch 数据并行模型，使用户在应用可解释性算法时能够充分利用多 GPU 资源。\n\n有关这些算法的更多详细信息，请访问我们的官网 [captum.ai\u002Fdocs\u002Falgorithms](https:\u002F\u002Fwww.captum.ai\u002Fdocs\u002Falgorithms)。\n\n### Captum Insights\n\nCaptum Insights 将上述算法集成到一个基于 Jupyter Notebook 的交互式工具中，用于模型调试与理解。它可以嵌入到 Notebook 中使用，也可以作为独立应用程序运行。\n\n**功能：**\n\n1. 可视化分类模型在采样数据上的归因结果\n2. 支持多模态输入，将文本、图像及通用特征整合到单个模型中\n3. 对特定类别及误分类样本进行过滤与调试\n4. 支持 Jupyter Notebook，便于用户轻松修改模型和数据集\n\nInsights 使用标准的 Web 技术构建，包…","2019-10-10T00:02:49"]