dgl.to_homogeneous

dgl.to_homogeneous(G, ndata=None, edata=None)[source]

Convert a heterogeneous graph to a homogeneous graph and return.

Node and edge types of the input graph are stored as the dgl.NTYPE and dgl.ETYPE features in the returned graph. Each feature is an integer representing the type id, determined by the DGLGraph.get_ntype_id() and DGLGraph.get_etype_id() methods.

The function also stores the original node/edge IDs as the dgl.NID and dgl.EID features in the returned graph.

Parameters
  • G (DGLGraph) – The heterogeneous graph.

  • ndata (list[str], optional) – The node features to combine across all node types. For each feature feat in ndata, it concatenates G.nodes[T].data[feat] across all node types T. As a result, the feature feat of all node types should have the same shape and data type. By default, the returned graph will not have any node features.

  • edata (list[str], optional) – The edge features to combine across all edge types. For each feature feat in edata, it concatenates G.edges[T].data[feat] across all edge types T. As a result, the feature feat of all edge types should have the same shape and data type. By default, the returned graph will not have any edge features.

Returns

A homogeneous graph.

Return type

DGLGraph

Examples

The following example uses PyTorch backend.

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

Combine feature ‘h’ across all node types in the conversion.

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