dgl.reverse

dgl.reverse(g, copy_ndata=True, copy_edata=False, *, share_ndata=None, share_edata=None)[source]

返回一个新图,其中每条边都是输入图中边的反向。

图的逆(也称为逆图、转置图)是指将类型为 (U, E, V) 的边 \((i_1, j_1), (i_2, j_2), \cdots\) 转换为类型为 (V, E, U) 的边 \((j_1, i_1), (j_2, i_2), \cdots\) 的新图。

返回的图与原始图共享数据结构,即dgl.reverse不会为反转图创建额外的存储空间。

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

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

  • copy_edata (bool, optional) – 如果为True,则反转图的边特征将从原始图中复制。如果为False,则反转图将没有任何边特征。 (默认值: False)

Returns:

反转后的图。

Return type:

DGLGraph

注释

如果 copy_ndatacopy_edata 为 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.

示例

同构图

创建一个要反转的图形。

>>> import dgl
>>> import torch as th
>>> g = dgl.graph((th.tensor([0, 1, 2]), th.tensor([1, 2, 0])))
>>> g.ndata['h'] = th.tensor([[0.], [1.], [2.]])
>>> g.edata['h'] = th.tensor([[3.], [4.], [5.]])

反转图形。

>>> rg = dgl.reverse(g, copy_edata=True)
>>> rg.ndata['h']
tensor([[0.],
        [1.],
        [2.]])

反转图中的第i条边对应于原始图中的第i条边。当copy_edata为True时,它们具有相同的特征。

>>> rg.edges()
(tensor([1, 2, 0]), tensor([0, 1, 2]))
>>> rg.edata['h']
tensor([[3.],
        [4.],
        [5.]])

异构图

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

生成的图将具有边类型 ('user', 'follows', 'user)('game', 'plays', 'user')

>>> rg = dgl.reverse(g, copy_ndata=True)
>>> rg
Graph(num_nodes={'game': 3, 'user': 3},
      num_edges={('user', 'follows', 'user'): 2, ('game', 'plays', 'user'): 3},
      metagraph=[('user', 'user'), ('game', 'user')])
>>> rg.edges(etype='follows')
(tensor([1, 2]), tensor([0, 2]))
>>> rg.edges(etype='plays')
(tensor([2, 1, 1]), tensor([1, 2, 1]))
>>> rg.nodes['game'].data['hv']
tensor([[1.],
        [1.],
        [1.]])
>>> rg.edges['plays'].data
{}