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为真,DGL将忽略这些边。

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

  • readonly (bool, 默认为 True) – 已弃用。readonly 和非 readonly 之间将没有区别

  • copy_ndata (bool, optional) –

    If True, the node features of the new graph are copied from the original graph. If False, the new graph will not have any node features.

    (Default: True)

  • copy_edata (bool, 可选) –

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

    如果为False,新图将不会有任何边特征。

    (默认: False)

  • ignore_bipartite (bool, optional) – 如果为True,则忽略单向二分图并且 不会引发错误。如果为False,当输入异质图的边类型为单向二分图时, 将引发错误。

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

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.

示例

同构图

>>> 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])