PyTorch Geometric GNN 可解释性实战指南:基于 examples/explain 从 GNNExplainer 到 MGNAN
PyTorch Geometric GNN 可解释性实战指南基于 examples/explain 从 GNNExplainer 到 MGNAN【免费下载链接】pytorch_geometricGraph Neural Network Library for PyTorch项目地址: https://gitcode.com/GitHub_Trending/py/pytorch_geometricPyTorch GeometricPyG的torch_geometric.explain包为图神经网络GNN提供了统一的解释工具链既可以对模型的预测结果给出归因模型为什么这么预测也可以挖掘数据集本身的底层现象什么结构模式驱动了标签。本文以 examples/explain 目录下的 7 个官方示例为骨架逐一拆解节点分类、链接预测、异构图链接预测、图分类等任务上的解释器配置与调用方式并结合torch_geometric.explain的源码实现explainer.py、config.py讲解Explainer的构造参数、ModelConfig/ThresholdConfig的取值语义以及解释结果如何可视化。读完本文你将能够独立地为自己的 GNN 模型接入解释能力并正确解读节点/边/特征掩码的含义。一、examples/explain 目录总览该目录是 PyG 官方提供的可解释性示例集合每个脚本对应一种解释算法或一种任务场景。目录下的 README.md 用一张表格概括了全部示例示例文件说明gnn_explainer.pyGNNExplainer用于节点分类gnn_explainer_link_pred.pyGNNExplainer用于链接预测gnn_explainer_ba_shapes.pyGNNExplainer应用于BAShapes合成数据集captum_explainer.py基于 Captum 的解释器用于节点分类captum_explainer_hetero_link.py基于 Captum 的解释器用于异构图链接预测graphmask_explainer.pyGraphMaskExplainer用于节点分类mgnan_graph_mutagenicity.pytorch_geometric.contrib.nn.models.MGNANGNAN 到多元形状函数的扩展用于图分类自带节点重要性分数从目录结构看除mgnan_graph_mutagenicity.py直接使用torch_geometric.contrib.nn.models.MGNAN之外其余 6 个脚本均以统一的Explainer门面类为入口仅通过替换algorithm参数来切换解释算法。这正是torch_geometric.explain包的设计哲学解释算法可插拔任务与模型配置统一描述。二、理解解释框架的核心抽象Explainer、Explanation 与三类配置在进入示例之前先理解 torch_geometric/explain 包暴露的公共 API。从init.py 可以看到包的核心导出为Explainer统一解释入口负责把模型、算法与配置组装起来Explanation/HeteroExplanation解释结果对象携带节点/边/特征掩码并支持可视化ExplainerConfig/ModelConfig/ThresholdConfig三类配置algorithm子包algorithm包含GNNExplainer、CaptumExplainer、GraphMaskExplainer、AttentionExplainer、PGExplainer、DummyExplainer等实现metric子包提供解释质量评估指标。Explainer的构造函数见 explainer.py签名如下Explainer( model, # 待解释的 GNN 模型 algorithm, # 解释算法实例如 GNNExplainer(epochs200) explanation_type, # model 或 phenomenon model_config, # ModelConfig 或等价 dict node_mask_typeNone, # 是否/如何生成节点掩码 edge_mask_typeNone, # 是否/如何生成边掩码 threshold_configNone, # 掩码阈值化配置 )构造时内部会生成ExplainerConfig与ModelConfig并调用algorithm.connect(explainer_config, model_config)让算法感知配置。explainer()被调用后返回Explanation对象其node_mask、edge_mask、node_feat_mask即特征掩码分别对应不同类型的归因available_explanations属性会列出实际生成了解释的类型。2.1 explanation_type解释模型还是解释现象ExplainerConfig见 config.py中的explanation_type取值决定解释目标model解释模型的预测结果解释算法的损失函数基于模型输出计算回答模型为什么给出这个预测phenomenon解释模型试图预测的现象本身损失函数基于**目标输出标签**计算回答数据集中什么结构模式驱动了标签。此时调用解释器需要额外传入target参数。gnn_explainer_link_pred.py与gnn_explainer_ba_shapes.py均同时演示了这两种模式是理解二者差异的最佳样本详见下文。2.2 ModelConfig描述模型的任务形态ModelConfig见 config.py的三个核心字段用于告知解释器模型的输出形态modebinary_classification、multiclass_classification或regressiontask_levelnode、edge或graphreturn_typelog_probs、probs或raw表示模型 forward 的输出类型解释器据此正确构造损失例如log_probs下使用 NLL 语义raw下使用交叉熵或 MSE 语义。示例中既可以直接传dict如gnn_explainer.py中的model_configdict(modemulticlass_classification, task_levelnode, return_typelog_probs)也可以构造ModelConfig对象如gnn_explainer_link_pred.py中的ModelConfig(modebinary_classification, task_leveledge, return_typeraw)二者等价ModelConfig.cast会自动完成转换。2.3 ThresholdConfig掩码的稀疏化与二值化原始解释掩码通常是稠密的软掩码需要阈值化后才便于可视化与统计。ThresholdConfig见 config.py支持threshold_typeNone不应用阈值hard硬阈值掩码值低于value的置 0其余置 1topk软阈值仅保留每类掩码中值最大的value个元素其余置 0。captum_explainer.py中的threshold_configdict(threshold_typetopk, value200)即表示对节点/边/特征掩码各自保留 Top-200 的归因元素。三、GNNExplainer节点分类与链接预测GNNExplainer通过优化一个可学习的掩码来最大化目标模型输出或标签的条件似然找到对预测最关键的子图与特征。三个示例分别覆盖了同质图节点分类、链接预测与合成数据集验证。3.1 节点分类gnn_explainer.pygnn_explainer.py 是入门样本流程分四步数据准备从Planetoid加载 Cora 数据集dataset[0]取出单图模型训练定义两层GCNConv的 GCN用F.nll_loss在train_mask上训练 200 轮Adamlr0.01weight_decay5e-4构造解释器explainer Explainer( modelmodel, algorithmGNNExplainer(epochs200), explanation_typemodel, node_mask_typeattributes, # 生成特征级掩码 node_feat_mask edge_mask_typeobject, # 生成边级掩码 edge_mask model_configdict( modemulticlass_classification, task_levelnode, return_typelog_probs, ), )生成并可视化解释node_index 10 explanation explainer(data.x, data.edge_index, indexnode_index) print(fGenerated explanations in {explanation.available_explanations}) explanation.visualize_feature_importance(feature_importance.png, top_k10) explanation.visualize_graph(subgraph.pdf)其中index指定被解释的节点visualize_feature_importance(path, top_k10)输出 Top-10 特征重要性柱状图PNGvisualize_graph(path)输出以该节点为中心的解释子图PDF边按edge_mask着色。node_mask_typeattributes表示生成的是特征掩码而非节点掩码edge_mask_typeobject表示直接为每条边生成掩码对象。3.2 链接预测gnn_explainer_link_pred.pygnn_explainer_link_pred.py 把场景切换到边级任务展示了两个关键点数据侧用T.RandomLinkSplit(num_val0.05, num_test0.1, is_undirectedTrue)做链接级划分得到train_data, val_data, test_data模型采用 Encoder-Decoder 结构两层 GCNConv 编码 (z[src] * z[dst]).sum(dim-1)点积解码训练损失为binary_cross_entropy_with_logits并用roc_auc_score评估解释侧ModelConfig显式声明task_leveledge、return_typeraw调用解释器时传入edge_label_index指定要解释的目标边取val_data.edge_label_index[:, 0]即验证集第一条边model_config ModelConfig( modebinary_classification, task_leveledge, return_typeraw, ) explainer Explainer( modelmodel, explanation_typemodel, algorithmGNNExplainer(epochs200), node_mask_typeattributes, edge_mask_typeobject, model_configmodel_config, ) explanation explainer( xtrain_data.x, edge_indextrain_data.edge_index, edge_label_indexedge_label_index, )该脚本还演示了explanation_typephenomenon的用法此时需要额外传入target目标边标签val_data.edge_label[0].unsqueeze(dim0).long()解释器将解释这条边为什么被标注为这个标签而非模型为什么这样打分。3.3 合成数据验证与量化评估gnn_explainer_ba_shapes.pygnn_explainer_ba_shapes.py 是目前唯一带解释质量量化评估的示例。它构造了带 ground-truth 解释的ExplainerDatasetdataset ExplainerDataset( graph_generatorBAGraph(num_nodes300, num_edges5), # BA 随机图主干 motif_generatorhouse, # 嵌入 house 结构基序 num_motifs80, # 共 80 个基序 transformT.Constant(), # 常量节点特征 )基序motif节点被标注为与主干不同的类别因此哪些边属于基序就是已知的真实解释保存在data.edge_mask。模型为 3 层GCN训练 2000 轮后用tqdm显示进度。评估逻辑非常值得借鉴对测试节点逐一生解释再用k_hop_subgraph(node_index, num_hops3, edge_indexdata.edge_index)截取 3 跳邻域内的边掩码最后把 ground-truthdata.edge_mask与预测的explanation.edge_mask对齐后计算ROC AUCfor explanation_type in [phenomenon, model]: explainer Explainer( modelmodel, algorithmGNNExplainer(epochs300), explanation_typeexplanation_type, node_mask_typeattributes, edge_mask_typeobject, model_configdict( modemulticlass_classification, task_levelnode, return_typeraw, ), ) # ... 对每个测试节点生成解释 ... targets.append(data.edge_mask[hard_edge_mask].cpu()) preds.append(explanation.edge_mask[hard_edge_mask].cpu()) auc roc_auc_score(torch.cat(targets), torch.cat(preds)) print(fMean ROC AUC (explanation type {explanation_type:10}): {auc:.4f})脚本同时对phenomenon与model两种解释类型分别评估phenomenon模式传targetdata.ymodel模式传targetNone可以直接对比两种解释口径在合成数据上的 AUC 差异——这是把解释器从玩具变成可度量的工程组件的关键做法。四、CaptumExplainer梯度类解释与异构支持CaptumExplainer把 Captum 的归因算法如 IntegratedGradients、Saliency、DeepLift 等适配到图数据上通过CaptumExplainer(IntegratedGradients)这类字符串指定算法名。它不需要像 GNNExplainer 那样做掩码优化而是直接对输入求梯度类归因因此通常更轻量。4.1 节点分类captum_explainer.pycaptum_explainer.py 与gnn_explainer.py结构几乎一致Cora 两层 GCN 200 轮训练仅两处差异算法换成CaptumExplainer(IntegratedGradients)并额外配置了threshold_configexplainer Explainer( modelmodel, algorithmCaptumExplainer(IntegratedGradients), explanation_typemodel, model_configdict( modemulticlass_classification, task_levelnode, return_typelog_probs, ), node_mask_typeattributes, edge_mask_typeobject, threshold_configdict( threshold_typetopk, value200, ), )随后同样对node_index 10生成解释输出available_explanations并保存特征重要性图与解释子图。注意这里的threshold_config先对掩码做 Top-200 稀疏化visualize_graph渲染的子图会更聚焦。4.2 异构图链接预测captum_explainer_hetero_link.pycaptum_explainer_hetero_link.py 是全部示例中最复杂的一个演示了异构图 边级 回归三种特性的组合技术点密集数据MovieLens(path, model_nameall-MiniLM-L6-v2)为user节点构造 one-hot 特征torch.eye用T.ToUndirected()添加反向边类型(movie, rev_rates, user)把(user, rates, movie)的edge_label转成 float 作为评分回归目标最后用T.RandomLinkSplit(num_val0.1, num_test0.1, neg_sampling_ratio0.0, edge_types[(user, rates, movie)], rev_edge_types[(movie, rev_rates, user)])做链接划分模型GNNEncoder两层SAGEConv((-1, -1), hidden)经to_hetero(self.encoder, data.metadata(), aggrsum)转换为异构图编码器配合 MLP 式EdgeDecoder训练损失为F.mse_loss回归任务共 9 轮解释explainer Explainer( modelmodel, algorithmCaptumExplainer(IntegratedGradients), explanation_typemodel, model_configdict( moderegression, task_leveledge, return_typeraw, ), node_mask_typeattributes, edge_mask_typeobject, threshold_configdict( threshold_typetopk, value200, ), ) index torch.tensor([2, 10]) # 同时解释索引为 2 和 10 的两条边 explanation explainer( data.x_dict, # 异构特征字典 data.edge_index_dict, # 异构边索引字典 indexindex, edge_label_indexdata[user, movie].edge_label_index, )关键差异异构图上输入从x/edge_index变为x_dict/edge_index_dict按边类型组织且通过edge_label_index与index组合指定被解释的目标边ModelConfig的moderegression与 MSE 训练损失严格对应。解释结果Explanation相应支持异构掩码可视化特征重要性同样调用visualize_feature_importance(path, top_k10)。五、GraphMaskExplainer逐层剪枝式解释graphmask_explainer.py 演示了GraphMaskExplainer——它学习对 GNN 每一层消息传递进行掩码这条消息是否被保留从而定位对预测起决定性作用的传播路径。脚本在一个文件里跑了 GCN 与 GAT 两套模型差异仅在algorithm参数explainer Explainer( modelmodel, algorithmGraphMaskExplainer(2, epochs5), # (num_layers, epochs) explanation_typemodel, node_mask_typeattributes, edge_mask_typeobject, model_configdict( modemulticlass_classification, task_levelnode, return_typelog_probs, ), )其中GraphMaskExplainer(2, epochs5)的第一个参数是要解释的层数对应两层 GCN/GAT第二个参数是掩码训练轮数。GAT 分支还展示了批量解释多个节点node_index torch.tensor([10, 20])一次传入两个索引解释器会为每个节点分别生成解释。六、MGNAN自带节点重要性的图分类模型最后一个示例 mgnan_graph_mutagenicity.py 不走Explainer门面而是直接训练torch_geometric.contrib.nn.models.MGNAN——GNANBechler-Speicher 等人, 2024的多元形状函数扩展模型自带节点重要性分数属于可解释模型路线。脚本结构预处理自定义PreprocessDistancestransform用networkx的all_pairs_shortest_path_length为每个图预计算稠密最短路距离矩阵node_distances与归一化矩阵normalization_matrix不可达对记inf归一化值置 1 避免除零Mutagenicity 图约 30 个节点稠密矩阵内存开销可接受自定义 collateMGNANCollater先把每个样本的距离/归一化矩阵拆出Batch.from_data_list组装常规字段后再用torch.block_diag拼成块对角矩阵挂回batch供模型按 batch 消费训练与解释MGNAN(in_channels..., out_channels1, n_layers3, hidden_channels64, dropout0.3, normalize_rhoFalse, feature_groups...)Adam(lr1e-4, weight_decay5e-5)ReduceLROnPlateau调度每个 epoch 结束后对一张测试样本图调用model.node_importance(sample_graph)打印逐节点的归因分数直观呈现模型认为哪些原子/键更关键。该脚本同时也示范了 PyG 生态可解释模型与事后解释器两种范式如何并存前者把可解释性内建进模型架构后者通过Explainer对任意黑盒模型做事后归因。七、从示例到实战解释器选型建议结合以上 7 个示例与 algorithm 子包中可用的算法AttentionExplainer、PGExplainer、DummyExplainer等可以从任务与目标两个维度做选型任务形态节点分类参考 gnn_explainer.py 与 graphmask_explainer.py链接预测参考 gnn_explainer_link_pred.py异构图边级任务参考 captum_explainer_hetero_link.py图分类且希望模型自带可解释性参考 mgnan_graph_mutagenicity.py。解释口径想解释模型为什么这样预测用explanation_typemodel想解释数据中什么现象驱动标签用phenomenon需传target可用 gnn_explainer_ba_shapes.py 的 ROC AUC 流程做量化对比。算法开销需要逐层传播路径归因选GraphMaskExplainer追求快速梯度归因且已安装 Captum 选CaptumExplainer算法名如IntegratedGradients追求经典子图/特征掩码优化选GNNExplainer。运行任意示例只需在仓库根目录执行对应的python examples/explain/script.py数据会自动下载到examples/data或脚本指定的本地路径Explainer、ModelConfig、ThresholdConfig的完整参数语义可进一步查阅 config.py 与 explainer.py 源码。掌握Explainer(model, algorithm, explanation_type, model_config, node_mask_type, edge_mask_type, threshold_config)这一套统一接口你就拥有了为任意 PyG 模型快速接入解释能力、并输出可视化证据的完整工具箱。【免费下载链接】pytorch_geometricGraph Neural Network Library for PyTorch项目地址: https://gitcode.com/GitHub_Trending/py/pytorch_geometric创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考