dgl.out_subgraph

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

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

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

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

Parameters:
  • graph (DGLGraph) – The input graph.

  • nodes (nodesdict[str, nodes]) –

    用于形成子图的节点,不能有任何重复值。否则结果将是未定义的。允许的节点格式有:

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

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

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

  • relabel_nodes (bool, optional) – If True, it will remove the isolated nodes and relabel the rest nodes in the extracted subgraph.

  • store_ids (bool, optional) – If True, it will store the raw IDs of the extracted edges in the edata of the resulting graph under name dgl.EID; if relabel_nodes is True, it will also store the raw IDs of the extracted nodes in the ndata of the resulting graph under name dgl.NID.

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

Returns:

子图。

Return type:

DGLGraph

注释

This function discards the batch information. Please use dgl.DGLGraph.set_batch_num_nodes() and dgl.DGLGraph.set_batch_num_edges() on the transformed graph to maintain the information.

示例

以下示例使用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