torch_geometric.contrib
torch_geometric.contrib 是一个用于早期实验代码的暂存区。未来这些模块可能会被移到主库中。
警告
该模块包含实验性代码,不能保证其稳定性。
Convolutional Layers
模型
来自大规模图神经网络的鲁棒性论文的投影随机块坐标下降(PRBCD)对抗攻击。 |
|
来自大规模图神经网络鲁棒性论文的贪婪随机块坐标下降(GRBCD)对抗攻击。 |
- class PRBCDAttack(model: Module, block_size: int, epochs: int = 125, epochs_resampling: int = 100, loss: Optional[Union[str, Callable[[Tensor, Tensor, Optional[Tensor]], Tensor]]] = 'prob_margin', metric: Optional[Union[str, Callable[[Tensor, Tensor, Optional[Tensor]], Tensor]]] = None, lr: float = 1000, is_undirected: bool = True, log: bool = True, **kwargs)[source]
来自大规模图神经网络的鲁棒性论文的投影随机块坐标下降(PRBCD)对抗攻击。
这种攻击使用了一种基于梯度的高效方法,在攻击过程中将邻接矩阵中的离散条目\(\{0, 1\}\)放宽到\([0, 1]\),并且仅扰动邻接矩阵(不扰动特征)。因此,这种攻击支持所有能够处理加权图并且对这些边权重可微分的模型,例如,
GCNConv或GraphConv。对于不可微分的模型,您可能需要进行修改,例如,参见GATConv的示例。内存开销主要由额外的边驱动(最多为
block_size)。出于可扩展性的原因,块是带替换绘制的,然后使索引唯一。因此,实际块大小通常略小于指定的值。这种攻击可以用于全局和局部攻击,以及测试时攻击(规避)和训练时攻击(投毒)。请参阅提供的示例。
这种攻击的设计重点是节点或图分类,然而,要适应其他任务,您很可能只需要提供一个适当的损失和模型。然而,我们目前不支持开箱即用的批处理(需要调整采样)。
注意
有关使用PRBCD攻击的示例,请参见 examples/contrib/rbcd_attack.py 以了解测试时间攻击(规避)或 examples/contrib/rbcd_attack_poisoning.py 以了解训练时间(投毒)攻击。
- Parameters:
model (torch.nn.Module) – 要评估的GNN模块。
block_size (int) – 在邻接矩阵中随机选择的元素数量。
epochs (int, optional) – 训练轮数(如果
mode='greedy'且预算满足,则提前终止)(默认值:125)epochs_resampling (int, optional) – 重新采样随机块的轮次数。(默认值: obj:100)
loss (str 或 callable, 可选) – 用于量化攻击“强度”的损失函数。请注意,此函数必须与
model的输出格式匹配。默认情况下,假设任务是分类任务,并且模型返回原始预测(即,没有输出激活)或使用logsoftmax。此外,预测的数量应与传递给attack的标签数量匹配。可以传递一个可调用对象或以下之一:'masked','margin','prob_margin','tanh_margin'。(默认值:'prob_margin')metric (callable, optional) – 用于监控或提前停止的第二个(可能不可微的)损失(如果
mode='greedy')。 (默认值: 与loss相同)lr (float, 可选) – 用于更新边权重的学习率。 此外,它还会根据
block_size、预算(参见attack)和图大小进行启发式修正。(默认值:1_000)is_undirected (bool, optional) – 如果为
True,则假定图是无向的。(默认值:True)
- coeffs = {'eps': 1e-07, 'max_final_samples': 20, 'max_trials_sampling': 20, 'with_early_stopping': True}
- attack(x: Tensor, edge_index: Tensor, labels: Tensor, budget: int, idx_attack: Optional[Tensor] = None, **kwargs) Tuple[Tensor, Tensor][source]
攻击提供的模型和图表的预测。
可以使用
idx_attack指定预测的子集。攻击允许翻转(即添加或删除)budget条边,并将返回它能找到的最强扰动。它返回扰动后的edge_index以及扰动本身。- Parameters:
x (torch.Tensor) – The node feature matrix.
edge_index (torch.Tensor) – The edge indices.
labels (torch.Tensor) – 标签。
预算 (int) – 允许的扰动次数(即最多翻转的边数)。
idx_attack (torch.Tensor, optional) – 用于筛选预测/标签的过滤器。 形状和类型必须匹配,以便它可以索引
labels和模型的预测。**kwargs (可选) – 传递给GNN模块的额外参数。
- Return type:
- class GRBCDAttack(model: Module, block_size: int, epochs: int = 125, loss: Optional[Union[str, Callable[[Tensor, Tensor, Optional[Tensor]], Tensor]]] = 'masked', is_undirected: bool = True, log: bool = True, **kwargs)[source]
来自大规模图神经网络鲁棒性论文的贪婪随机块坐标下降(GRBCD)对抗攻击。
GRBCD 与
PRBCDAttack共享大部分属性和要求。它也使用了一种基于梯度的高效方法。然而,它基于对邻接矩阵的梯度贪婪地翻转边。注意
有关使用GRBCD攻击的示例,请参见 examples/contrib/rbcd_attack.py 以了解测试时间攻击(规避)的示例。
- Parameters:
model (torch.nn.Module) – The GNN module to assess.
block_size (int) – Number of randomly selected elements in the adjacency matrix to consider.
epochs (int, optional) – Number of epochs (aborts early if
mode='greedy'and budget is satisfied) (default:125)loss (str 或 callable, 可选) – 用于量化攻击“强度”的损失函数。请注意,此函数必须与
model的输出格式匹配。默认情况下,假设任务是分类任务,并且模型返回原始预测(即,没有输出激活)或使用logsoftmax。此外,预测的数量应与传递给attack的标签数量匹配。可以传递 Callable 或以下之一:'masked','margin','prob_margin','tanh_margin'。(默认值:'masked')is_undirected (bool, optional) – If
Truethe graph is assumed to be undirected. (default:True)log (bool, optional) – If set to
False, will not log any learning progress. (default:True)
- coeffs = {'eps': 1e-07, 'max_trials_sampling': 20}
数据集
转换
Explainer
来自"PGMExplainer: Probabilistic Graphical Model Explanations for Graph Neural Networks"论文的PGMExplainer模型。 |
- class PGMExplainer(feature_index: Optional[List] = None, perturbation_mode: str = 'randint', perturbations_is_positive_only: bool = False, is_perturbation_scaled: bool = False, num_samples: int = 100, max_subgraph_size: Optional[int] = None, significance_threshold: float = 0.05, pred_threshold: float = 0.1)[source]
PGMExplainer模型来自“PGMExplainer: Probabilistic Graphical Model Explanations for Graph Neural Networks”论文。
生成的
Explanation提供了一个node_mask和一个pgm_stats张量,该张量存储了 \(p\)-值,这些值是通过卡方检验计算得出的每个节点的值。- Parameters:
feature_index (列表) – 被扰动特征的索引。如果设置为
None,则所有特征都会被扰动。(默认值:None)perturb_mode (str, optional) – 生成特征变化的方法。可选值为
"randint","mean","zero","max"或"uniform"。(默认值:"randint")perturbations_is_positive_only (bool, optional) – 如果设置为
True, 限制扰动值为正数。(默认值:False)is_perturbation_scaled (bool, optional) – 如果设置为
True,将 归一化扰动特征的范围。 (默认:False)num_samples (int, optional) – 用于测试节点对预测显著性的扰动样本数量。 (默认:
100)significance_threshold (float, optional) – 统计阈值 (\(p\)-值),用于判断一个节点是否对预测有影响。(默认值:
0.05)pred_threshold (float, optional) – 用于考虑扰动数据的输出与原始数据不同的缓冲值(范围在
[0, 1])。(默认值:0.1)
- forward(model: Module, x: Tensor, edge_index: Tensor, *, target: Tensor, index: Optional[Union[int, Tensor]] = None, **kwargs) Explanation[source]
计算解释。
- Parameters:
model (torch.nn.Module) – The model to explain.
x (Union[torch.Tensor, Dict[NodeType, torch.Tensor]]) – The input node features of a homogeneous or heterogeneous graph.
edge_index (Union[torch.Tensor, Dict[NodeType, torch.Tensor]]) – The input edge indices of a homogeneous or heterogeneous graph.
target (torch.Tensor) – The target of the model.
index (Union[int, Tensor], optional) – The index of the model output to explain. Can be a single index or a tensor of indices. (default:
None)**kwargs (optional) – Additional keyword arguments passed to
model.
- Return type: