[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"tool-PAIR-code--saliency":3,"similar-PAIR-code--saliency":95},{"id":4,"github_repo":5,"name":6,"description_en":7,"description_zh":8,"ai_summary_zh":9,"readme_en":10,"readme_zh":11,"quickstart_zh":12,"use_case_zh":13,"hero_image_url":14,"owner_login":15,"owner_name":16,"owner_avatar_url":17,"owner_bio":18,"owner_company":19,"owner_location":19,"owner_email":19,"owner_twitter":19,"owner_website":20,"owner_url":21,"languages":22,"stars":35,"forks":36,"last_commit_at":37,"license":38,"difficulty_score":39,"env_os":40,"env_gpu":40,"env_ram":40,"env_deps":41,"category_tags":46,"github_topics":49,"view_count":60,"oss_zip_url":19,"oss_zip_packed_at":19,"status":61,"created_at":62,"updated_at":63,"faqs":64,"releases":94},6272,"PAIR-code\u002Fsaliency","saliency","Framework-agnostic implementation for state-of-the-art saliency methods (XRAI, BlurIG, SmoothGrad, and more).","saliency 是一个专注于深度学习模型可解释性的开源库，由谷歌 PAIR 团队开发。它集成了多种前沿的显著性分析方法，如 XRAI、BlurIG、SmoothGrad、Guided Integrated Gradients 以及经典的 Grad-CAM 等，旨在帮助开发者直观地理解神经网络是如何做出决策的——即识别出输入图像中对模型预测结果影响最大的区域。\n\n该工具核心解决了不同深度学习框架间的兼容难题。作为框架无关（framework-agnostic）的实现，saliency 不再局限于单一生态，而是通过通用的回调函数机制，灵活支持 TensorFlow、PyTorch 等各类主流框架，极大降低了跨平台应用的门槛。此外，它还引入了性能信息曲线（PIC）这一自动化评估指标，让用户无需依赖人工标注即可客观量化不同显著性方法的质量。\n\nsaliency 非常适合 AI 研究人员、算法工程师及数据科学家使用。无论是需要调试模型偏差、验证特征提取的有效性，还是希望向非技术人员展示模型关注点，都能从中获益。其提供的可视化模块能轻松将复杂的三维梯度数据转化为清晰的灰度或发散色热力图，让“黑盒","saliency 是一个专注于深度学习模型可解释性的开源库，由谷歌 PAIR 团队开发。它集成了多种前沿的显著性分析方法，如 XRAI、BlurIG、SmoothGrad、Guided Integrated Gradients 以及经典的 Grad-CAM 等，旨在帮助开发者直观地理解神经网络是如何做出决策的——即识别出输入图像中对模型预测结果影响最大的区域。\n\n该工具核心解决了不同深度学习框架间的兼容难题。作为框架无关（framework-agnostic）的实现，saliency 不再局限于单一生态，而是通过通用的回调函数机制，灵活支持 TensorFlow、PyTorch 等各类主流框架，极大降低了跨平台应用的门槛。此外，它还引入了性能信息曲线（PIC）这一自动化评估指标，让用户无需依赖人工标注即可客观量化不同显著性方法的质量。\n\nsaliency 非常适合 AI 研究人员、算法工程师及数据科学家使用。无论是需要调试模型偏差、验证特征提取的有效性，还是希望向非技术人员展示模型关注点，都能从中获益。其提供的可视化模块能轻松将复杂的三维梯度数据转化为清晰的灰度或发散色热力图，让“黑盒”模型的内部逻辑变得透明可信。","# Saliency Library\n## Updates\n\n&#x1F534;&nbsp;&nbsp; Now framework-agnostic! [(Example core notebook)](Examples_core.ipynb) &nbsp;&#x1F534;\n\n&#x1F517;&nbsp;&nbsp; For further explanation of the methods and more examples of the resulting maps, see our [Github Pages website](https:\u002F\u002Fpair-code.github.io\u002Fsaliency)  &nbsp;&#x1F517;\n\nIf upgrading from an older version, update old imports to `import saliency.tf1 as saliency`. We provide wrappers to make the framework-agnostic version compatible with TF1 models. [(Example TF1 notebook)](Examples_tf1.ipynb)\n\n&#x1F534;&nbsp;&nbsp; Added Performance Information Curve (PIC) - a human\nindependent metric for evaluating the quality of saliency methods.\n([Example notebook](https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fblob\u002Fmaster\u002Fpic_metrics.ipynb)) &nbsp;&#x1F534;\n\n## Saliency Methods\n\nThis repository contains code for the following saliency techniques:\n\n*   Guided Integrated Gradients* ([paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F2106.09788), [poster](https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fblob\u002Fmaster\u002Fdocs\u002FCVPR_Guided_IG_Poster.pdf))\n*   XRAI* ([paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F1906.02825), [poster](https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fblob\u002Fmaster\u002Fdocs\u002FICCV_XRAI_Poster.pdf))\n*   SmoothGrad* ([paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F1706.03825))\n*   Vanilla Gradients\n    ([paper](https:\u002F\u002Fscholar.google.com\u002Fscholar?q=Visualizing+higher-layer+features+of+a+deep+network&btnG=&hl=en&as_sdt=0%2C22),\n    [paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F1312.6034))\n*   Guided Backpropogation ([paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F1412.6806))\n*   Integrated Gradients ([paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F1703.01365))\n*   Occlusion\n*   Grad-CAM ([paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F1610.02391))\n*   Blur IG ([paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F2004.03383))\n\n\\*Developed by PAIR.\n\nThis list is by no means comprehensive. We are accepting pull requests to add\nnew methods!\n\n## Evaluation of Saliency Methods\n\nThe repository provides an implementation of Performance Information Curve (PIC) -\na human independent metric for evaluating the quality of saliency methods\n([paper](https:\u002F\u002Farxiv.org\u002Fabs\u002F1906.02825),\n[poster](https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fblob\u002Fmaster\u002Fdocs\u002FICCV_XRAI_Poster.pdf),\n[code](https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fblob\u002Fmaster\u002Fsaliency\u002Fmetrics\u002Fpic.py),\n[notebook](https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fblob\u002Fmaster\u002Fpic_metrics.ipynb)).\n\n\n## Download\n\n```\n# To install the core subpackage:\npip install saliency\n\n# To install core and tf1 subpackages:\npip install saliency[tf1]\n\n```\n\nor for the development version:\n```\ngit clone https:\u002F\u002Fgithub.com\u002Fpair-code\u002Fsaliency\ncd saliency\n```\n\n\n## Usage\n\nThe saliency library has two subpackages:\n*\t`core` uses a generic `call_model_function` which can be used with any ML \n\tframework.\n*\t`tf1` accepts input\u002Foutput tensors directly, and sets up the necessary \n\tgraph operations for each method.\n\n### Core\n\nEach saliency mask class extends from the `CoreSaliency` base class. This class\ncontains the following methods:\n\n*   `GetMask(x_value, call_model_function, call_model_args=None)`: Returns a mask\n    of\n    the shape of non-batched `x_value` given by the saliency technique.\n*   `GetSmoothedMask(x_value, call_model_function, call_model_args=None, stdev_spread=.15, nsamples=25, magnitude=True)`: \n    Returns a mask smoothed of the shape of non-batched `x_value` with the \n    SmoothGrad technique.\n\n\nThe visualization module contains two methods for saliency visualization:\n\n* ```VisualizeImageGrayscale(image_3d, percentile)```: Marginalizes across the\n  absolute value of each channel to create a 2D single channel image, and clips\n  the image at the given percentile of the distribution. This method returns a\n  2D tensor normalized between 0 to 1.\n* ```VisualizeImageDiverging(image_3d, percentile)```: Marginalizes across the\n  value of each channel to create a 2D single channel image, and clips the\n  image at the given percentile of the distribution. This method returns a\n  2D tensor normalized between -1 to 1 where zero remains unchanged.\n\nIf the sign of the value given by the saliency mask is not important, then use\n```VisualizeImageGrayscale```, otherwise use ```VisualizeImageDiverging```. See\nthe SmoothGrad paper for more details on which visualization method to use.\n\n##### call_model_function\n`call_model_function` is how we pass inputs to a given model and receive the outputs\nnecessary to compute saliency masks. The description of this method and expected \noutput format is in the `CoreSaliency` description, as well as separately for each method.\n\n\n##### Examples\n\n[This example iPython notebook](http:\u002F\u002Fgithub.com\u002Fpair-code\u002Fsaliency\u002Fblob\u002Fmaster\u002FExamples_core.ipynb)\nshowing these techniques is a good starting place.\n\nHere is a condensed example of using IG+SmoothGrad with TensorFlow 2:\n\n```\nimport saliency.core as saliency\nimport tensorflow as tf\n\n...\n\n# call_model_function construction here.\ndef call_model_function(x_value_batched, call_model_args, expected_keys):\n\ttape = tf.GradientTape()\n\tgrads = np.array(tape.gradient(output_layer, images))\n\treturn {saliency.INPUT_OUTPUT_GRADIENTS: grads}\n\n...\n\n# Load data.\nimage = GetImagePNG(...)\n\n# Compute IG+SmoothGrad.\nig_saliency = saliency.IntegratedGradients()\nsmoothgrad_ig = ig_saliency.GetSmoothedMask(image, \n\t\t\t\t\t\t\t\t\t\t\tcall_model_function, \n                                            call_model_args=None)\n\n# Compute a 2D tensor for visualization.\ngrayscale_visualization = saliency.VisualizeImageGrayscale(\n    smoothgrad_ig)\n```\n\n### TF1\n\nEach saliency mask class extends from the `TF1Saliency` base class. This class\ncontains the following methods:\n\n*   `__init__(graph, session, y, x)`: Constructor of the SaliencyMask. This can\n    modify the graph, or sometimes create a new graph. Often this will add nodes\n    to the graph, so this shouldn't be called continuously. `y` is the output\n    tensor to compute saliency masks with respect to, `x` is the input tensor\n    with the outer most dimension being batch size.\n*   `GetMask(x_value, feed_dict)`: Returns a mask of the shape of non-batched\n    `x_value` given by the saliency technique.\n*   `GetSmoothedMask(x_value, feed_dict)`: Returns a mask smoothed of the shape\n    of non-batched `x_value` with the SmoothGrad technique.\n\nThe visualization module contains two visualization methods:\n\n* ```VisualizeImageGrayscale(image_3d, percentile)```: Marginalizes across the\n  absolute value of each channel to create a 2D single channel image, and clips\n  the image at the given percentile of the distribution. This method returns a\n  2D tensor normalized between 0 to 1.\n* ```VisualizeImageDiverging(image_3d, percentile)```: Marginalizes across the\n  value of each channel to create a 2D single channel image, and clips the\n  image at the given percentile of the distribution. This method returns a\n  2D tensor normalized between -1 to 1 where zero remains unchanged.\n\nIf the sign of the value given by the saliency mask is not important, then use\n```VisualizeImageGrayscale```, otherwise use ```VisualizeImageDiverging```. See\nthe SmoothGrad paper for more details on which visualization method to use.\n\n##### Examples\n\n[This example iPython notebook](http:\u002F\u002Fgithub.com\u002Fpair-code\u002Fsaliency\u002Fblob\u002Fmaster\u002FExamples_tf1.ipynb) shows\nthese techniques is a good starting place.\n\nAnother example of using GuidedBackprop with SmoothGrad from TensorFlow:\n\n```\nfrom saliency.tf1 import GuidedBackprop\nfrom saliency.tf1 import VisualizeImageGrayscale\nimport tensorflow.compat.v1 as tf\n\n...\n# Tensorflow graph construction here.\ny = logits[5]\nx = tf.placeholder(...)\n...\n\n# Compute guided backprop.\n# NOTE: This creates another graph that gets cached, try to avoid creating many\n# of these.\nguided_backprop_saliency = GuidedBackprop(graph, session, y, x)\n\n...\n# Load data.\nimage = GetImagePNG(...)\n...\n\nsmoothgrad_guided_backprop =\n    guided_backprop_saliency.GetMask(image, feed_dict={...})\n\n# Compute a 2D tensor for visualization.\ngrayscale_visualization = visualization.VisualizeImageGrayscale(\n    smoothgrad_guided_backprop)\n```\n\n## Conclusion\u002FDisclaimer\n\nIf you have any questions or suggestions for improvements to this library,\nplease contact the owners of the `PAIR-code\u002Fsaliency` repository.\n\nThis is not an official Google product.","# 显著性库\n## 更新\n\n&#x1F534;&nbsp;&nbsp; 现在与框架无关！[(核心示例笔记本)](Examples_core.ipynb) &nbsp;&#x1F534;\n\n&#x1F517;&nbsp;&nbsp; 如需进一步了解这些方法以及更多结果图示例，请参阅我们的 [Github Pages 网站](https:\u002F\u002Fpair-code.github.io\u002Fsaliency)  &nbsp;&#x1F517;\n\n如果您是从旧版本升级，请将旧的导入语句更新为 `import saliency.tf1 as saliency`。我们提供了封装器，使与框架无关的版本能够兼容 TensorFlow 1 模型。[(TensorFlow 1 示例笔记本)](Examples_tf1.ipynb)\n\n&#x1F534;&nbsp;&nbsp; 新增性能信息曲线（PIC）——一种不依赖人工评估的指标，用于评价显著性方法的质量。\n([示例笔记本](https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fblob\u002Fmaster\u002Fpic_metrics.ipynb)) &nbsp;&#x1F534;\n\n## 显著性方法\n\n本仓库包含以下显著性技术的代码实现：\n\n*   引导式积分梯度*（[论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F2106.09788)，[海报](https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fblob\u002Fmaster\u002Fdocs\u002FCVPR_Guided_IG_Poster.pdf))\n*   XRAI*（[论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F1906.02825)，[海报](https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fblob\u002Fmaster\u002Fdocs\u002FICCV_XRAI_Poster.pdf))\n*   平滑梯度*（[论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F1706.03825)）\n*   原始梯度\n    （[论文](https:\u002F\u002Fscholar.google.com\u002Fscholar?q=Visualizing+higher-layer+features+of+a+deep+network&btnG=&hl=en&as_sdt=0%2C22),\n    [论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F1312.6034)）\n*   引导式反向传播（[论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F1412.6806)）\n*   积分梯度（[论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F1703.01365)）\n*   屏蔽法\n*   Grad-CAM（[论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F1610.02391)）\n*   模糊积分梯度（[论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F2004.03383)）\n\n\\*由 PAIR 团队开发。\n\n此列表绝非完整。我们欢迎通过 Pull Request 添加新方法！\n\n## 显著性方法的评估\n\n该仓库提供性能信息曲线（PIC）的实现——一种不依赖人工评估的指标，用于评价显著性方法的质量\n（[论文](https:\u002F\u002Farxiv.org\u002Fabs\u002F1906.02825),\n[海报](https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fblob\u002Fmaster\u002Fdocs\u002FICCV_XRAI_Poster.pdf),\n[代码](https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fblob\u002Fmaster\u002Fsaliency\u002Fmetrics\u002Fpic.py),\n[笔记本](https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fblob\u002Fmaster\u002Fpic_metrics.ipynb)).\n\n\n## 下载\n\n```\n# 安装核心子包：\npip install saliency\n\n# 安装核心和 tf1 子包：\npip install saliency[tf1]\n\n```\n\n或获取开发版本：\n```\ngit clone https:\u002F\u002Fgithub.com\u002Fpair-code\u002Fsaliency\ncd saliency\n```\n\n\n## 使用\n\n显著性库包含两个子包：\n*\t`core` 使用通用的 `call_model_function`，可与任何机器学习框架配合使用。\n*\t`tf1` 直接接受输入输出张量，并为每种方法设置必要的计算图操作。\n\n### Core\n\n每个显著性掩码类都继承自 `CoreSaliency` 基类。该类包含以下方法：\n\n*   `GetMask(x_value, call_model_function, call_model_args=None)`: 根据显著性技术，返回与非批量输入 `x_value` 形状相同的掩码。\n*   `GetSmoothedMask(x_value, call_model_function, call_model_args=None, stdev_spread=.15, nsamples=25, magnitude=True)`: \n    使用平滑梯度技术，返回与非批量输入 `x_value` 形状相同的平滑化掩码。\n\n\n可视化模块包含两种显著性可视化方法：\n\n* ```VisualizeImageGrayscale(image_3d, percentile)```: 对各通道的绝对值进行降维，生成一个单通道的 2D 图像，并按给定百分位数截断图像。该方法返回一个归一化到 0 到 1 的 2D 张量。\n* ```VisualizeImageDiverging(image_3d, percentile)```: 对各通道的值进行降维，生成一个单通道的 2D 图像，并按给定百分位数截断图像。该方法返回一个归一化到 -1 到 1 的 2D 张量，其中零值保持不变。\n\n如果显著性掩码中数值的正负号并不重要，则使用 ```VisualizeImageGrayscale```；否则使用 ```VisualizeImageDiverging```。有关应使用哪种可视化方法的更多细节，请参阅平滑梯度论文。\n\n##### call_model_function\n`call_model_function` 是我们将输入传递给模型并获取计算显著性掩码所需输出的方式。该方法的描述及预期输出格式已在 `CoreSaliency` 类说明中给出，并针对每种方法单独列出。\n\n\n##### 示例\n\n[这个 iPython 笔记本示例](http:\u002F\u002Fgithub.com\u002Fpair-code\u002Fsaliency\u002Fblob\u002Fmaster\u002FExamples_core.ipynb) 展示了这些技术，是一个不错的起点。\n\n以下是使用 TensorFlow 2 进行 IG+平滑梯度的简要示例：\n\n```\nimport saliency.core as saliency\nimport tensorflow as tf\n\n...\n\n# 在此处构建 call_model_function。\ndef call_model_function(x_value_batched, call_model_args, expected_keys):\n\ttape = tf.GradientTape()\n\tgrads = np.array(tape.gradient(output_layer, images))\n\treturn {saliency.INPUT_OUTPUT_GRADIENTS: grads}\n\n...\n\n# 加载数据。\nimage = GetImagePNG(...)\n\n# 计算 IG+平滑梯度。\nig_saliency = saliency.IntegratedGradients()\nsmoothgrad_ig = ig_saliency.GetSmoothedMask(image, \n\t\t\t\t\t\t\t\t\t\t\tcall_model_function, \n                                            call_model_args=None)\n\n# 计算用于可视化的 2D 张量。\ngrayscale_visualization = saliency.VisualizeImageGrayscale(\n    smoothgrad_ig)\n```\n\n### TF1\n\n每个显著性掩码类都继承自 `TF1Saliency` 基类。该类包含以下方法：\n\n*   `__init__(graph, session, y, x)`: 显著性掩码的构造函数。此方法可能会修改图结构，有时还会创建一个新的计算图。通常，它会在图中添加节点，因此不应频繁调用。`y` 是用于计算显著性掩码的输出张量，`x` 是输入张量，其最外层维度表示批次大小。\n*   `GetMask(x_value, feed_dict)`: 根据显著性技术，返回与非批处理形式的 `x_value` 形状相同的掩码。\n*   `GetSmoothedMask(x_value, feed_dict)`: 使用 SmoothGrad 技术，返回对非批处理形式的 `x_value` 进行平滑处理后的掩码。\n\n可视化模块包含两种可视化方法：\n\n* ```VisualizeImageGrayscale(image_3d, percentile)```: 对每个通道的绝对值进行降维，生成一个二维单通道图像，并按给定百分位数裁剪图像。该方法返回一个归一化到 0 到 1 范围内的二维张量。\n* ```VisualizeImageDiverging(image_3d, percentile)```: 对每个通道的值进行降维，生成一个二维单通道图像，并按给定百分位数裁剪图像。该方法返回一个归一化到 -1 到 1 范围内的二维张量，其中零值保持不变。\n\n如果显著性掩码中的值的符号不重要，则使用 ```VisualizeImageGrayscale```；否则使用 ```VisualizeImageDiverging```。有关应使用哪种可视化方法的更多详细信息，请参阅 SmoothGrad 论文。\n\n##### 示例\n\n[这个示例 iPython 笔记本](http:\u002F\u002Fgithub.com\u002Fpair-code\u002Fsaliency\u002Fblob\u002Fmaster\u002FExamples_tf1.ipynb) 展示了这些技术，是一个不错的起点。\n\n另一个使用 TensorFlow 中的 Guided Backprop 和 SmoothGrad 的示例：\n\n```\nfrom saliency.tf1 import GuidedBackprop\nfrom saliency.tf1 import VisualizeImageGrayscale\nimport tensorflow.compat.v1 as tf\n\n...\n# 在此处构建 TensorFlow 计算图。\ny = logits[5]\nx = tf.placeholder(...)\n...\n\n# 计算引导反向传播。\n# 注意：这会创建另一个会被缓存的计算图，应尽量避免多次创建。\nguided_backprop_saliency = GuidedBackprop(graph, session, y, x)\n\n...\n# 加载数据。\nimage = GetImagePNG(...)\n...\n\nsmoothgrad_guided_backprop =\n    guided_backprop_saliency.GetMask(image, feed_dict={...})\n\n# 计算用于可视化的二维张量。\ngrayscale_visualization = visualization.VisualizeImageGrayscale(\n    smoothgrad_guided_backprop)\n```\n\n## 结论\u002F免责声明\n\n如果您对该库有任何疑问或改进建议，请联系 `PAIR-code\u002Fsaliency` 仓库的所有者。\n\n本项目并非 Google 官方产品。","# Saliency 快速上手指南\n\nSaliency 是一个由 Google PAIR 团队开发的框架无关（Framework-agnostic）库，用于生成和可视化深度学习模型的显著性图（Saliency Maps），帮助理解模型关注的图像区域。支持 TensorFlow 1、TensorFlow 2 及其他通过回调函数适配的框架。\n\n## 环境准备\n\n*   **操作系统**：Linux, macOS, Windows\n*   **Python 版本**：建议 Python 3.7+\n*   **前置依赖**：\n    *   基础版：仅需 `numpy` 等基础科学计算库。\n    *   TensorFlow 用户：需预先安装 `tensorflow` (TF1 或 TF2)。\n    *   其他框架：无需特定框架依赖，只需实现标准的 `call_model_function` 接口。\n\n## 安装步骤\n\n### 方式一：通过 Pip 安装（推荐）\n\n**安装核心包（适用于所有框架，包括 TF2）：**\n```bash\npip install saliency\n```\n\n**安装核心包 + TensorFlow 1 支持包：**\n```bash\npip install saliency[tf1]\n```\n\n> **国内加速提示**：如果下载速度较慢，可使用清华或阿里镜像源：\n> ```bash\n> pip install -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple saliency\n> # 或\n> pip install -i https:\u002F\u002Fmirrors.aliyun.com\u002Fpypi\u002Fsimple\u002F saliency[tf1]\n> ```\n\n### 方式二：源码安装（开发版）\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fpair-code\u002Fsaliency\ncd saliency\npip install -e .\n```\n\n## 基本使用\n\nSaliency 提供两种使用模式：\n1.  **Core 模式**：框架无关，通过 `call_model_function` 适配任意模型（推荐 TF2 及非 TF 用户）。\n2.  **TF1 模式**：专为 TensorFlow 1 设计，直接操作 Graph 和 Session。\n\n以下展示最常用的 **Core 模式** 结合 **TensorFlow 2** 的使用示例（计算 Integrated Gradients + SmoothGrad）：\n\n### 代码示例\n\n```python\nimport saliency.core as saliency\nimport tensorflow as tf\nimport numpy as np\n\n# 1. 定义模型调用函数\n# 该函数接收输入并返回计算显著性所需的梯度信息\ndef call_model_function(x_value_batched, call_model_args, expected_keys):\n    # x_value_batched: 批量化的输入数据\n    # 需要确保模型是可微分的\n    with tf.GradientTape() as tape:\n        tape.watch(x_value_batched)\n        # 假设 model 是你的预处理好的 TF2 模型\n        predictions = model(x_value_batched) \n        # 选择需要解释的输出类别索引，例如第 0 类\n        output_layer = predictions[:, 0] \n    \n    # 计算输入相对于输出的梯度\n    grads = tape.gradient(output_layer, x_value_batched)\n    \n    # 返回格式必须符合库的要求\n    return {saliency.INPUT_OUTPUT_GRADIENTS: grads.numpy()}\n\n# 2. 加载数据 (假设已有一个归一化后的单张图片数组，形状不含 batch 维)\n# image = GetImagePNG(...) \n# 此处仅为示意，实际需替换为你的图片加载逻辑\nimage = np.random.rand(224, 224, 3).astype(np.float32) \n\n# 3. 初始化显著性方法并计算掩码\n# 使用 Integrated Gradients (IG)\nig_saliency = saliency.IntegratedGradients()\n\n# 计算平滑后的掩码 (IG + SmoothGrad)\n# stdev_spread: 噪声标准差，nsamples: 采样次数\nsmoothgrad_ig = ig_saliency.GetSmoothedMask(\n    image, \n    call_model_function, \n    call_model_args=None,\n    stdev_spread=0.15,\n    nsamples=25\n)\n\n# 4. 可视化处理\n# 将 3D 掩码转换为 2D 灰度图用于显示 (值域 0-1)\ngrayscale_visualization = saliency.VisualizeImageGrayscale(\n    smoothgrad_ig, \n    percentile=99 # 截断分布以增强对比度\n)\n\n# grayscale_visualization 即为最终可用于 matplotlib 显示的 2D 数组\n```\n\n### 关键方法说明\n\n*   **`GetMask`**: 获取基础显著性掩码。\n*   **`GetSmoothedMask`**: 自动应用 SmoothGrad 技术，通过添加噪声并多次采样来平滑结果，通常视觉效果更佳。\n*   **`VisualizeImageGrayscale`**: 适用于不关心梯度正负号的场景，输出归一化到 [0, 1]。\n*   **`VisualizeImageDiverging`**: 适用于关心梯度方向（正\u002F负影响）的场景，输出归一化到 [-1, 1]。\n\n更多详细用法及针对 TF1 的示例，请参考官方仓库中的 `Examples_core.ipynb` 和 `Examples_tf1.ipynb`。","某医疗 AI 团队正在开发肺炎 X 光片辅助诊断系统，急需向医生解释模型为何将某张片子判定为“重症”。\n\n### 没有 saliency 时\n- 模型仅输出“重症”结论，医生无法知晓是肺部阴影还是无关的肋骨纹理触发了判断，信任度极低。\n- 团队尝试手动遮挡图像测试重要性，过程繁琐且只能得到粗糙的区域推测，缺乏像素级的精确归因。\n- 面对监管审查，无法提供符合医学逻辑的可视化证据，导致算法难以通过伦理与安全评估。\n- 不同可解释性方法（如 Grad-CAM 与积分梯度）代码框架不统一，切换对比时需重写大量适配代码，研发效率低下。\n\n### 使用 saliency 后\n- 利用 XRAI 和 Guided Integrated Gradients 生成高亮热力图，精准定位到病灶区域，让医生直观看到模型“关注点”与临床特征一致。\n- 调用 `GetMask` 接口即可在几行代码内切换多种前沿算法，无需关心底层是 TensorFlow 还是 PyTorch，快速验证哪种解释最符合医学常识。\n- 引入 PIC 指标量化评估热力图质量，用客观数据证明解释方法的可靠性，顺利通过了医疗器械软件的合规审查。\n- 通过 `VisualizeImageDiverging` 将正负贡献区分展示，不仅解释了“为何是重症”，还排除了背景噪声干扰，大幅提升了报告的可读性。\n\nsaliency 通过统一且先进的归因算法，将黑盒模型的决策逻辑转化为医生可信的视觉证据，加速了 AI 在关键领域的落地应用。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FPAIR-code_saliency_c4b5e8fc.png","PAIR-code","PAIR code","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002FPAIR-code_8b8800c7.png","Code repositories for projects from the People+AI Research (PAIR) Initiative",null,"https:\u002F\u002Fpair.withgoogle.com","https:\u002F\u002Fgithub.com\u002FPAIR-code",[23,27,31],{"name":24,"color":25,"percentage":26},"Jupyter Notebook","#DA5B0B",97.6,{"name":28,"color":29,"percentage":30},"Python","#3572A5",2.4,{"name":32,"color":33,"percentage":34},"Shell","#89e051",0,995,196,"2026-04-04T13:08:23","Apache-2.0",1,"未说明",{"notes":42,"python":40,"dependencies":43},"该库现已框架无关（framework-agnostic），核心子包 (core) 可通过自定义 call_model_function 适配任意机器学习框架；若需使用 TensorFlow 1.x 模型，需安装 tf1 子包 (pip install saliency[tf1])。代码示例基于 TensorFlow 2 (GradientTape) 和 TensorFlow 1 (Session\u002FGraph)。",[44,45],"tensorflow (TF1 或 TF2)","numpy",[47,48],"图像","开发框架",[50,51,52,53,54,55,56,57,58,59,6],"machine-learning","deep-learning","deep-neural-networks","tensorflow","convolutional-neural-networks","saliency-map","object-detection","image-recognition","ig-saliency","smoothgrad",2,"ready","2026-03-27T02:49:30.150509","2026-04-10T22:18:59.967774",[65,70,75,80,85,90],{"id":66,"question_zh":67,"answer_zh":68,"source_url":69},28378,"如何修复 Integrated Gradients 中出现的 'assert x_baseline.shape == x_value.shape' 断言错误？","该错误通常是因为 baseline 初始化方式不正确。不要使用 `baseline = np.array(im.shape)`，这会创建一个包含形状数值的数组。正确的做法是使用 `baseline = np.zeros_like(im)` 创建与输入图像形状相同的零数组，然后填充基准值（例如 -1）：\n\n```python\nbaseline = np.zeros_like(im)\nbaseline.fill(-1)\n```\n\n注意：-1 是因为 Inception 模型将 -1 视为黑色像素，你也可以根据模型需求使用 0 或其他值作为基准。如果未指定 x_baseline，默认会使用 `np.zeros_like(x_value)`。","https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fissues\u002F1",{"id":71,"question_zh":72,"answer_zh":73,"source_url":74},28379,"运行示例代码时出现 'ValueError: Cannot feed value of shape...' 形状不匹配错误怎么办？","该错误通常是因为输入图像的尺寸与模型期望的尺寸（如 299x299）不一致。解决方法是在预处理阶段将图像调整（resize）到模型所需的尺寸。例如，对于 Inception v3 模型，需要将图像调整为 (299, 299) 或 (229, 229)（具体取决于模型配置）。\n\n此外，该库的示例代码已在后续更新（PR #49）中重构。请注意，目前该库主要依赖 TensorFlow 1 的 Session 机制，尚未完全迁移到 TF 2。如果可能，建议在 TF 1 环境下运行，或自行修改代码以分离梯度计算逻辑来适配其他框架。","https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fissues\u002F5",{"id":76,"question_zh":77,"answer_zh":78,"source_url":79},28380,"如何将 Saliency 方法应用于回归任务（Regression Task）而非分类任务？","虽然该库主要针对分类问题设计，但也可以用于回归任务。在回归任务中，输出是多个数值（n 维），你需要决定如何计算梯度：\n1. **求和法**：直接对所有输出维度求和，查看哪些像素对所有输出最敏感（`tf.gradients` 默认会对输出维度求和）。\n2. **加权平均法**：计算每个输出维度的梯度，然后进行加权平均；或者先对输出值进行加权平均得到一个标量 y，再对该标量求梯度。\n\n建议尝试这两种方法，观察哪种更能反映你的模型关注点。如果是自定义模型（如 PyTorch），需要修改 `call_model_function` 以返回回归得分（如年龄预测值），并手动处理梯度计算逻辑。","https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fissues\u002F15",{"id":81,"question_zh":82,"answer_zh":83,"source_url":84},28381,"是否支持批量图像（Batched Images）输入来获取掩码（Mask）？","目前官方的 `GetMask` 和 `GetSmoothedMask` 方法仅支持单张图像输入，维护者暂无计划原生支持多图像的批量处理。\n\n不过，针对基于路径的方法（如 Integrated Gradients），库中已实现了步骤级别的批处理（即一次性计算多个步骤），这解决了主要的性能瓶颈。对于非基于路径的方法（如 Gradients, Occlusion, Grad-CAM），理论上可以添加一个参数来标识输入是否为批量数据，从而一次性返回批量掩码，因为这类方法只调用模型一次。\n\n**变通方案**：\n1. 用户可以参考 PR #49 中的批处理实现思路自行扩展。\n2. 社区用户曾通过在多 GPU 上启动多进程并行运行来实现加速。\n3. 也可以参考社区实现的 GradCAM 代码（部分用户在私有代码库中实现了支持批量的版本）。","https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fissues\u002F10",{"id":86,"question_zh":87,"answer_zh":88,"source_url":89},28382,"为什么调用 GetMask 时会报 'NoneType' 或 'TypeError: Fetch argument ... has invalid type' 错误？","此类错误通常发生在 TensorFlow Session 执行阶段，表明传递给 `session.run` 的 fetch 参数无效（例如为 None）。\n\n常见原因及排查步骤：\n1. **梯度节点未正确构建**：确保在调用 `GetMask` 之前，Saliency 对象已正确初始化，并且内部的 `gradients_node` 已成功创建。\n2. **Feed Dict 问题**：检查传入的 `feed_dict` 是否包含了模型运行所需的所有占位符（Placeholder），特别是 `neuron_selector` 是否正确映射到了预测类别。\n3. **图结构冲突**：如果你在同一图中混合了多个会话或重复构建了图，可能导致节点引用丢失。尝试在干净的 TensorFlow 图中重新实例化模型和 Saliency 对象。\n4. **版本兼容性**：确保 TensorFlow 版本与库兼容（主要支持 TF1），TF2 的默认行为（Eager Execution）可能会导致 Session 相关代码失效，需使用 `tf.compat.v1` 兼容模式。","https:\u002F\u002Fgithub.com\u002FPAIR-code\u002Fsaliency\u002Fissues\u002F12",{"id":91,"question_zh":92,"answer_zh":93,"source_url":79},28383,"如何自定义 call_model_function 以适配我的模型（如获取特定层的输出或回归分数）？","要适配自定义模型，你需要重写或正确实现 `call_model_function`。该函数负责接收图像并返回模型输出及梯度信息。\n\n关键步骤：\n1. **预处理**：在函数内部对输入图像进行必要的预处理（如归一化）。\n2. **前向传播**：运行模型得到输出 tensor。\n3. **选择目标**：\n   - 对于分类：通常选择特定类别的 logits 或概率 `output[:, target_class_idx]`。\n   - 对于回归：可以直接使用输出 tensor，或者根据需求计算损失（如 MAE）后再求导。\n4. **返回梯度**：如果 `expected_keys` 中包含 `INPUT_OUTPUT_GRADIENTS`，需计算输出相对于输入的梯度并返回。\n\n示例逻辑（伪代码）：\n```python\ndef call_model_function(images, call_model_args=None, expected_keys=None):\n    images = preprocess(images)\n    output = model(images)\n    \n    results = {}\n    if saliency.base.INPUT_OUTPUT_GRADIENTS in expected_keys:\n        # 根据任务类型选择目标值（分类选特定类，回归可选总和或加权值）\n        target = output[:, specific_index] # 或 output 的某种聚合\n        grads = compute_gradients(target, images)\n        results[saliency.base.INPUT_OUTPUT_GRADIENTS] = grads\n        \n    return results\n```",[],[96,107,115,124,132,141],{"id":97,"name":98,"github_repo":99,"description_zh":100,"stars":101,"difficulty_score":102,"last_commit_at":103,"category_tags":104,"status":61},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",[105,48,47,106],"Agent","数据工具",{"id":108,"name":109,"github_repo":110,"description_zh":111,"stars":112,"difficulty_score":102,"last_commit_at":113,"category_tags":114,"status":61},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",[48,47,105],{"id":116,"name":117,"github_repo":118,"description_zh":119,"stars":120,"difficulty_score":60,"last_commit_at":121,"category_tags":122,"status":61},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 真正成长为懂上",149489,"2026-04-10T11:32:46",[48,105,123],"语言模型",{"id":125,"name":126,"github_repo":127,"description_zh":128,"stars":129,"difficulty_score":60,"last_commit_at":130,"category_tags":131,"status":61},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",[48,47,105],{"id":133,"name":134,"github_repo":135,"description_zh":136,"stars":137,"difficulty_score":60,"last_commit_at":138,"category_tags":139,"status":61},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",[140,105,47,48],"插件",{"id":142,"name":143,"github_repo":144,"description_zh":145,"stars":146,"difficulty_score":60,"last_commit_at":147,"category_tags":148,"status":61},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",[140,48]]