dgl.DGLHeteroGraph.subgraph

DGLHeteroGraph.subgraph(nodes)[source]

Return the subgraph induced on given nodes.

The metagraph of the returned subgraph is the same as the parent graph. Features are copied from the original graph.

Parameters:nodes (dict[str->list or iterable]) – A dictionary mapping node types to node ID array for constructing subgraph. All nodes must exist in the graph.
Returns:G – The subgraph.

The nodes and edges in the subgraph are relabeled using consecutive integers from 0.

One can retrieve the mapping from subgraph node/edge ID to parent node/edge ID via dgl.NID and dgl.EID node/edge features of the subgraph.

Return type:DGLHeteroGraph

Examples

The following example uses PyTorch backend.

Instantiate a heterograph.

>>> plays_g = dgl.bipartite([(0, 0), (1, 0), (1, 2), (2, 1)], 'user', 'plays', 'game')
>>> follows_g = dgl.graph([(0, 1), (1, 2), (1, 2)], 'user', 'follows')
>>> g = dgl.hetero_from_relations([plays_g, follows_g])
>>> # Set node features
>>> g.nodes['user'].data['h'] = torch.tensor([[0.], [1.], [2.]])

Get subgraphs.

>>> g.subgraph({'user': [4, 5]})
An error occurs as these nodes do not exist.
>>> sub_g = g.subgraph({'user': [1, 2]})
>>> print(sub_g)
Graph(num_nodes={'user': 2, 'game': 0},
      num_edges={('user', 'plays', 'game'): 0, ('user', 'follows', 'user'): 2},
      metagraph=[('user', 'game'), ('user', 'user')])

Get the original node/edge indices.

>>> sub_g['follows'].ndata[dgl.NID] # Get the node indices in the raw graph
tensor([1, 2])
>>> sub_g['follows'].edata[dgl.EID] # Get the edge indices in the raw graph
tensor([1, 2])

Get the copied node features.

>>> sub_g.nodes['user'].data['h']
tensor([[1.],
        [2.]])
>>> sub_g.nodes['user'].data['h'] += 1
>>> g.nodes['user'].data['h']          # Features are not shared.
tensor([[0.],
        [1.],
        [2.]])

See also

edge_subgraph()