dgl.edge_subgraph
- dgl.edge_subgraph(graph, edges, *, relabel_nodes=True, store_ids=True, output_device=None)[源代码]
返回由给定边导出的子图。
边诱导子图等效于使用给定边创建新图。除了提取子图之外,DGL 还会将提取的节点和边的特征复制到结果图中。复制是*惰性*的,只有在需要时才会导致数据移动。
如果图是异构的,DGL 将针对每种关系提取一个子图,并将它们组合成结果图。因此,结果图与输入图具有相同的关系集合。
- 参数:
graph (DGLGraph) – 用于提取子图的图。
edges (edges 或 dict[(str, str, str), edges]) –
构成子图的边。允许的边格式包括:
Int Tensor: 每个元素都是一个边 ID。该张量必须具有与图相同的设备类型和 ID 数据类型。
iterable[int]: 每个元素都是一个边 ID。
Bool Tensor: 第 \(i\) 个元素是一个布尔标志,指示边 \(i\) 是否在子图中。
如果图是同构的,可以直接传递上述格式。否则,参数必须是一个字典,其中键是边类型,值是上述格式的边 ID。
relabel_nodes (bool, 可选) – 如果为 True,它将移除孤立节点并重新标记提取的子图中的关联节点。
store_ids (bool, 可选) – 如果为 True,它将在结果图的
edata
中以名称dgl.EID
存储提取边的原始 ID;如果relabel_nodes
为True
,它还将在结果图的ndata
中以名称dgl.NID
存储关联节点的原始 ID。output_device (框架特定的设备上下文对象, 可选) – 输出设备。默认为与输入图相同。
- 返回:
G – 子图。
- 返回类型:
注意
此函数丢弃批处理信息。请使用
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 >>> sg = dgl.edge_subgraph(g, [0, 4]) >>> sg Graph(num_nodes=3, num_edges=2, ndata_schemes={'_ID': Scheme(shape=(), dtype=torch.int64)} edata_schemes={'_ID': Scheme(shape=(), dtype=torch.int64)}) >>> sg.edges() (tensor([0, 1]), tensor([2, 0])) >>> sg.ndata[dgl.NID] # original node IDs tensor([0, 4, 1]) >>> sg.edata[dgl.EID] # original edge IDs tensor([0, 4])
在不重新标记节点的情况下提取子图。
>>> sg = dgl.edge_subgraph(g, [0, 4], relabel_nodes=False) >>> sg Graph(num_nodes=5, num_edges=2, ndata_schemes={} edata_schemes={'_ID': Scheme(shape=(), dtype=torch.int64)}) >>> sg.edges() (tensor([0, 4]), tensor([1, 0]))
使用布尔掩码指定边。
>>> nodes = torch.tensor([True, False, False, False, True]) # choose edges [0, 4] >>> dgl.edge_subgraph(g, nodes) Graph(num_nodes=3, num_edges=2, ndata_schemes={'_ID': Scheme(shape=(), dtype=torch.int64)} edata_schemes={'_ID': Scheme(shape=(), dtype=torch.int64)})
结果子图也复制了父图的特征。
>>> g.ndata['x'] = torch.arange(10).view(5, 2) >>> sg = dgl.edge_subgraph(g, [0, 4]) >>> sg Graph(num_nodes=3, num_edges=2, ndata_schemes={'x': Scheme(shape=(2,), dtype=torch.int64), '_ID': Scheme(shape=(), dtype=torch.int64)} edata_schemes={'_ID': Scheme(shape=(), dtype=torch.int64)}) >>> sg.ndata[dgl.NID] tensor([0, 4, 1]) >>> sg.ndata['x'] tensor([[0, 1], [8, 9], [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 = dgl.edge_subgraph(g, {('user', 'follows', 'user'): [1, 2], ... ('user', 'plays', 'game'): [2]}) >>> print(sub_g) Graph(num_nodes={'game': 1, user': 2}, num_edges={('user', 'follows', 'user'): 2, ('user', 'plays', 'game'): 1}, metagraph=[('user', 'user', 'follows'), ('user', 'game', 'plays')])
另请参阅