dgl.khop_in_subgraph

dgl.khop_in_subgraph(graph, nodes, k, *, relabel_nodes=True, store_ids=True, output_device=None)[源码]

返回由指定节点(集)的 k 跳入邻域诱导的子图。

我们可以通过包含节点的前驱节点来扩展一个节点集。从一个指定的节点集开始,通过重复 k 次节点集扩展,然后创建一个节点诱导子图,即可获得一个 k 跳入子图。除了提取子图外,DGL 还会将提取的节点和边的特征复制到结果图中。复制是 惰性的,只有在需要时才会发生数据移动。

如果图是异构的,DGL 会为每种关系提取一个子图,并将它们组合成结果图。因此,结果图具有与输入图相同的关系集。

参数:
  • graph (DGLGraph) – 输入图。

  • nodes (nodesdict[str, nodes]) –

    要扩展的起始节点(集),不能有任何重复值。否则结果是未定义的。允许的格式包括

    • Int: 单个节点的 ID。

    • Int Tensor: 每个元素都是一个节点 ID。该张量必须与图具有相同的设备类型和 ID 数据类型。

    • iterable[int]: 每个元素都是一个节点 ID。

    如果图是同构的,可以直接使用上述格式。否则,参数必须是一个字典,其键是节点类型,值是上述格式的节点 ID。

  • k (int) – 跳数。

  • relabel_nodes (bool, 可选) – 如果为 True,则会删除提取子图中的孤立节点并重新标记其余节点。

  • store_ids (bool, 可选) – 如果为 True,它将在结果图的 edata 中以 dgl.EID 为名称存储提取边的原始 ID;如果 relabel_nodesTrue,它还将在结果图的 ndata 中以 dgl.NID 为名称存储提取节点的原始 ID。

  • output_device (框架特定的设备上下文对象, 可选) – 输出设备。默认为与输入图相同。

返回值:

  • DGLGraph – 子图。

  • Tensor 或 dict[str, Tensor], 可选 – 节点重新标记后输入 nodes 的新 ID。仅当 relabel_nodes 为 True 时返回。其形式与 nodes 相同。

注意事项

当 k 为 1 时,结果子图与通过 dgl.in_subgraph() 获得的子图不同。1 跳入子图也包含邻域内部的边。

示例

以下示例使用 PyTorch 后端。

>>> import dgl
>>> import torch

从同构图中提取一个二跳子图。

>>> g = dgl.graph(([1, 1, 2, 3, 4], [0, 2, 0, 4, 2]))
>>> g.edata['w'] = torch.arange(10).view(5, 2)
>>> sg, inverse_indices = dgl.khop_in_subgraph(g, 0, k=2)
>>> sg
Graph(num_nodes=4, num_edges=4,
      ndata_schemes={'_ID': Scheme(shape=(), dtype=torch.int64)}
      edata_schemes={'w': Scheme(shape=(2,), dtype=torch.int64),
                     '_ID': Scheme(shape=(), dtype=torch.int64)})
>>> sg.edges()
(tensor([1, 1, 2, 3]), tensor([0, 2, 0, 2]))
>>> sg.edata[dgl.EID]  # original edge IDs
tensor([0, 1, 2, 4])
>>> sg.edata['w']  # also extract the features
tensor([[0, 1],
        [2, 3],
        [4, 5],
        [8, 9]])
>>> inverse_indices
tensor([0])

从异构图中提取一个子图。

>>> g = dgl.heterograph({
...     ('user', 'plays', 'game'): ([0, 1, 1, 2], [0, 0, 2, 1]),
...     ('user', 'follows', 'user'): ([0, 1, 1], [1, 2, 2])})
>>> sg, inverse_indices = dgl.khop_in_subgraph(g, {'game': 0}, k=2)
>>> sg
Graph(num_nodes={'game': 1, 'user': 2},
      num_edges={('user', 'follows', 'user'): 1, ('user', 'plays', 'game'): 2},
      metagraph=[('user', 'user', 'follows'), ('user', 'game', 'plays')])
>>> inverse_indices
{'game': tensor([0])}

另请参阅

khop_out_subgraph