dgl.to_bidirected

dgl.to_bidirected(g, copy_ndata=False, readonly=None)[source]

将图转换为双向简单图并返回。

对于输入图 \(G\),返回一个新图 \(G'\),使得边 \((u, v)\in G'\) 存在当且仅当存在边 \((v, u)\in G\)。结果图 \(G'\) 是一个简单图,意味着没有平行边。

该操作仅适用于两个端点属于相同节点类型的边。 如果输入图是异构图且包含具有不同类型端点的边,DGL将引发错误。

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

  • copy_ndata (bool, optional) – 如果为True,双向图的节点特征将从原始图中复制。如果为False,双向图将不会有任何节点特征。 (默认值: False)

  • 只读 (bool) – 已弃用.

Returns:

双向图

Return type:

DGLGraph

注释

如果 copy_ndata 为 True,生成的图将与输入图共享节点特征张量。因此,用户应尽量避免原地操作,这些操作将对两个图都可见。

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 as th
>>> g = dgl.graph((th.tensor([0, 1, 2]), th.tensor([1, 2, 0])))
>>> bg1 = dgl.to_bidirected(g)
>>> bg1.edges()
(tensor([0, 1, 2, 1, 2, 0]), tensor([1, 2, 0, 0, 1, 2]))

图中已经存在 i->j 和 j->i

>>> g = dgl.graph((th.tensor([0, 1, 2, 0]), th.tensor([1, 2, 0, 2])))
>>> bg1 = dgl.to_bidirected(g)
>>> bg1.edges()
(tensor([0, 1, 2, 1, 2, 0]), tensor([1, 2, 0, 0, 1, 2]))

具有多种边类型的异构图

>>> g = dgl.heterograph({
...     ('user', 'wins', 'user'): (th.tensor([0, 2, 0, 2]), th.tensor([1, 1, 2, 0])),
...     ('user', 'follows', 'user'): (th.tensor([1, 2, 1]), th.tensor([2, 1, 1]))
... })
>>> bg1 = dgl.to_bidirected(g)
>>> bg1.edges(etype='wins')
(tensor([0, 0, 1, 1, 2, 2]), tensor([1, 2, 0, 2, 0, 1]))
>>> bg1.edges(etype='follows')
(tensor([1, 1, 2]), tensor([1, 2, 1]))