dgl.DGLHeteroGraph.node_type_subgraph

DGLHeteroGraph.node_type_subgraph(ntypes)[source]

Return the subgraph induced on given node types.

The metagraph of the returned subgraph is the subgraph of the original metagraph induced from the node types.

Features are shared with the original graph.

Parameters:ntypes (list[str]) – The node types
Returns:G – 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.

>>> sub_g = g.node_type_subgraph(['user'])
>>> print(sub_g)
Graph(num_nodes=3, num_edges=3,
      ndata_schemes={'h': Scheme(shape=(1,), dtype=torch.float32)}
      edata_schemes={})

Get the shared node features.

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