dgl.khop_out_subgraph

dgl.khop_out_subgraph(graph, nodes, k, *, relabel_nodes=True, store_ids=True, output_device=None)[source]

返回由指定节点的k跳出邻域诱导的子图。

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

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

Parameters:
  • (DGLGraph) – 输入的图。

  • nodes (nodesdict[str, nodes]) –

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

    • Int: 单个节点的ID。

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

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

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

  • k (int) – 跳数。

  • relabel_nodes (bool, optional) – 如果为True,它将移除孤立的节点并重新标记提取的子图中的其余节点。

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

  • output_device (Framework-specific device context object, optional) – The output device. Default is the same as the input graph.

Returns:

  • DGLGraph – 子图。

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

注释

当k为1时,结果子图与通过dgl.out_subgraph()获得的子图不同。1跳出子图还包括邻居之间的边。

示例

以下示例使用PyTorch后端。

>>> import dgl
>>> import torch

从同质图中提取一个两跳子图。

>>> g = dgl.graph(([0, 2, 0, 4, 2], [1, 1, 2, 3, 4]))
>>> g.edata['w'] = torch.arange(10).view(5, 2)
>>> sg, inverse_indices = dgl.khop_out_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([0, 0, 2, 2]), tensor([1, 2, 1, 3]))
>>> sg.edata[dgl.EID]  # original edge IDs
tensor([0, 2, 1, 4])
>>> sg.edata['w']  # also extract the features
tensor([[0, 1],
        [4, 5],
        [2, 3],
        [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, 3])})
>>> sg, inverse_indices = dgl.khop_out_subgraph(g, {'user': 0}, k=2)
>>> sg
Graph(num_nodes={'game': 2, 'user': 3},
      num_edges={('user', 'follows', 'user'): 2, ('user', 'plays', 'game'): 2},
      metagraph=[('user', 'user', 'follows'), ('user', 'game', 'plays')])
>>> inverse_indices
{'user': tensor([0])}

另请参阅

khop_in_subgraph