dgl.out_subgraph

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

返回由给定节点的所有边类型的出边诱导的子图。

出边子图等效于使用给定节点的出边创建一个新图。除了抽取子图,DGL 还会将抽取出的节点和边的特征复制到结果图中。复制是惰性的,只有在需要时才会发生数据移动。

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

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

  • nodes (节点dict[str, 节点]) –

    用于构建子图的节点,不能包含重复值。否则结果将是未定义的。允许的节点格式有

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

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

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

  • relabel_nodes (bool, 可选) – 如果为 True,将移除孤立节点并对抽取出的子图中剩余的节点重新编号。

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

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

返回:

子图。

返回类型:

DGLGraph

备注

此函数会丢弃批处理信息。请在变换后的图上使用 dgl.DGLGraph.set_batch_num_nodes()dgl.DGLGraph.set_batch_num_edges() 来保持信息。

示例

以下示例使用 PyTorch 后端。

>>> import dgl
>>> import torch

从同构图抽取子图。

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

抽取带有节点编号的子图。

>>> sg = dgl.out_subgraph(g, [2, 0], relabel_nodes=True)
>>> sg
Graph(num_nodes=4, num_edges=2,
      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([2, 0]), tensor([3, 1]))
>>> sg.edata[dgl.EID]  # original edge IDs
tensor([2, 0])
>>> sg.ndata[dgl.NID]  # original node IDs
tensor([0, 1, 2, 3])

从异构图抽取子图。

>>> g = dgl.heterograph({
...     ('user', 'plays', 'game'): ([0, 1, 1, 2], [0, 0, 2, 1]),
...     ('user', 'follows', 'user'): ([0, 1, 1], [1, 2, 2])})
>>> sub_g = g.out_subgraph({'user': [1]})
>>> sub_g
Graph(num_nodes={'game': 3, 'user': 3},
      num_edges={('user', 'plays', 'game'): 2, ('user', 'follows', 'user'): 2},
      metagraph=[('user', 'game', 'plays'), ('user', 'user', 'follows')])

另请参阅

in_subgraph