dgl.add_reverse_edges

dgl.add_reverse_edges(g, readonly=None, copy_ndata=True, copy_edata=False, ignore_bipartite=False, exclude_self=True)[source]

为输入图中的每条边添加一条反向边,并返回一个新图。

对于具有边 \((i_1, j_1), \cdots, (i_n, j_n)\) 的图,此函数创建一个新图,其中包含边 \((i_1, j_1), \cdots, (i_n, j_n), (j_1, i_1), \cdots, (j_n, i_n)\)

返回的图可能包含重复边。要创建没有重复边的双向图,请使用 to_bidirected()

此操作仅适用于其两个端点属于同一节点类型的边。如果输入图是异构图并包含具有不同类型端点的边,DGL 将引发错误。如果 ignore_bipartite 为 True,DGL 将忽略这些边。

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

  • readonly (bool, 默认为 True) – 已废弃。readonly 和 non-readonly 将没有区别

  • copy_ndata (bool, 可选) –

    如果为 True,则新图的节点特征从原始图复制。如果为 False,则新图将不包含任何节点特征。

    (默认值: True)

  • copy_edata (bool, 可选) –

    如果为 True,则反向边的特征将与原始边相同。

    如果为 False,则新图将不包含任何边特征。

    (默认值: False)

  • ignore_bipartite (bool, 可选) – 如果为 True,则忽略单向二分图,不会引发错误。如果为 False,并且输入异构图的某个边类型用于单向二分图,则会引发错误。

  • exclude_self (bool, 可选) – 如果为 True,则不会为自环添加反向边,这在大多数情况下可能是没有意义的。

返回:

添加了反向边的图。

返回类型:

DGLGraph

注意

如果 copy_ndata 为 True,则结果图将与输入图共享节点特征张量。因此,用户应尽量避免会影响两个图的就地(in-place)操作。相反,这两个图不共享相同的边特征存储。

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

示例

同构图

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

异构图

>>> g = dgl.heterograph({
>>>     ('user', 'wins', 'user'): (th.tensor([0, 2, 0, 2, 2]), th.tensor([1, 1, 2, 1, 0])),
>>>     ('user', 'plays', 'game'): (th.tensor([1, 2, 1]), th.tensor([2, 1, 1])),
>>>     ('user', 'follows', 'user'): (th.tensor([1, 2, 1), th.tensor([0, 0, 0]))
>>> })
>>> g.nodes['game'].data['hv'] = th.ones(3, 1)
>>> g.edges['wins'].data['h'] = th.tensor([0, 1, 2, 3, 4])

add_reverse_edges() 操作应用于边类型 ('user', 'wins', 'user') 和边类型 ('user', 'follows', 'user')。忽略边类型 ('user', 'plays', 'game')。节点特征和边特征都共享。

>>> bg = dgl.add_reverse_edges(g, copy_ndata=True,
                           copy_edata=True, ignore_bipartite=True)
>>> bg.edges(('user', 'wins', 'user'))
(tensor([0, 2, 0, 2, 2, 1, 1, 2, 1, 0]), tensor([1, 1, 2, 1, 0, 0, 2, 0, 2, 2]))
>>> bg.edges(('user', 'follows', 'user'))
(tensor([1, 2, 1, 0, 0, 0]), tensor([0, 0, 0, 1, 2, 1]))
>>> bg.edges(('user', 'plays', 'game'))
(th.tensor([1, 2, 1]), th.tensor([2, 1, 1]))
>>> bg.nodes['game'].data['hv']
tensor([0, 0, 0])
>>> bg.edges[('user', 'wins', 'user')].data['h']
th.tensor([0, 1, 2, 3, 4, 0, 1, 2, 3, 4])