dgl.to_homogeneous

dgl.to_homogeneous(G, ndata=None, edata=None, store_type=True, return_count=False)[source]

将异构图转换为同构图并返回。

默认情况下,函数将输入图的节点和边类型存储为返回图中的dgl.NTYPEdgl.ETYPE特征。每个特征是一个表示类型ID的整数,由DGLGraph.get_ntype_id()DGLGraph.get_etype_id()方法确定。可以通过指定store_type=False来省略它。

结果图将相同类型的节点和边分配在连续的ID范围内(即,第一种类型的节点具有ID 0 ~ G.num_nodes(G.ntypes[0]);第二种类型的节点紧随其后;依此类推)。因此,一种更节省内存的类型信息格式是整数列表;第i个元素对应于第i种类型的节点/边的数量。可以通过指定return_count=True来选择此格式。

Parameters:
  • G (DGLGraph) – 异构图。

  • ndata (list[str], optional) – 要跨所有节点类型组合的节点特征。对于ndata中的每个特征feat,它会跨所有节点类型T连接G.nodes[T].data[feat]。因此,所有节点类型的特征feat应具有相同的形状和数据类型。默认情况下,返回的图将没有任何节点特征。

  • edata (list[str], optional) – 要跨所有边类型组合的边特征。对于edata中的每个特征feat,它会跨所有边类型T连接G.edges[T].data[feat]。因此,所有边类型的特征feat应具有相同的形状和数据类型。默认情况下,返回的图将没有任何边特征。

  • store_type (bool, 可选) – 如果为True,将类型信息存储为返回图中的dgl.NTYPEdgl.ETYPE特征。

  • return_count (bool, 可选) – 如果为True,返回类型信息作为整数列表;第i个元素对应于第i种类型的节点/边的数量。

Returns:

  • DGLGraph – 一个同构图。

  • ntype_count (list[int], optional) – 每种类型的节点数量。当 return_count 为 True 时返回。

  • etype_count (list[int], optional) – 每种类型的边数量。当 return_count 为 True 时返回。

注释

  • 计算类型信息可能会引入显著的成本。如果不需要类型信息,将store_typereturn_count都设置为False可以避免这种成本。否则,DGL建议使用store_type=Falsereturn_count=True,因为它在内存效率上更优。

  • ntype_countetype_count 列表可以帮助加速某些操作。 参见 RelGraphConv 以查看一个示例。

  • 调用 to_homogeneous() 然后再调用 to_heterogeneous() 会得到相同的结果。

示例

以下示例使用PyTorch后端。

>>> import dgl
>>> import torch
>>> hg = dgl.heterograph({
...     ('user', 'follows', 'user'): ([0, 1], [1, 2]),
...     ('developer', 'develops', 'game'): ([0, 1], [0, 1])
...     })
>>> hg.nodes['user'].data['h'] = torch.ones(3, 1)
>>> hg.nodes['developer'].data['h'] = torch.zeros(2, 1)
>>> hg.nodes['game'].data['h'] = torch.ones(2, 1)
>>> g = dgl.to_homogeneous(hg)
>>> # The first three nodes are for 'user', the next two are for 'developer',
>>> # and the last two are for 'game'
>>> g.ndata
{'_TYPE': tensor([0, 0, 0, 1, 1, 2, 2]), '_ID': tensor([0, 1, 2, 0, 1, 0, 1])}
>>> # The first two edges are for 'follows', and the next two are for 'develops' edges.
>>> g.edata
{'_TYPE': tensor([0, 0, 1, 1]), '_ID': tensor([0, 1, 0, 1])}

在转换过程中,组合所有节点类型的特征‘h’。

>>> g = dgl.to_homogeneous(hg, ndata=['h'])
>>> g.ndata['h']
tensor([[1.], [1.], [1.], [0.], [0.], [1.], [1.]])

另请参阅

to_heterogeneous