dgl.DGLGraph.add_nodes

DGLGraph.add_nodes(num, data=None, ntype=None)[source]

Add new nodes of the same node type

Parameters:
  • num (int) – Number of nodes to add.

  • data (dict, optional) – Feature data of the added nodes.

  • ntype (str, optional) – The type of the new nodes. Can be omitted if there is only one node type in the graph.

Notes

  • Inplace update is applied to the current graph.

  • If the key of data does not contain some existing feature fields, those features for the new nodes will be created by initializers defined with set_n_initializer() (default initializer fills zeros).

  • If the key of data contains new feature fields, those features for the old nodes will be created by initializers defined with set_n_initializer() (default initializer fills zeros).

  • 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.

Examples

The following example uses PyTorch backend.

>>> import dgl
>>> import torch

Homogeneous Graphs or Heterogeneous Graphs with A Single Node Type

>>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
>>> g.num_nodes()
3
>>> g.add_nodes(2)
>>> g.num_nodes()
5

If the graph has some node features and new nodes are added without features, their features will be created by initializers defined with set_n_initializer().

>>> g.ndata['h'] = torch.ones(5, 1)
>>> g.add_nodes(1)
>>> g.ndata['h']
tensor([[1.], [1.], [1.], [1.], [1.], [0.]])

We can also assign features for the new nodes in adding new nodes.

>>> g.add_nodes(1, {'h': torch.ones(1, 1), 'w': torch.ones(1, 1)})
>>> g.ndata['h']
tensor([[1.], [1.], [1.], [1.], [1.], [0.], [1.]])

Since data contains new feature fields, the features for old nodes will be created by initializers defined with set_n_initializer().

>>> g.ndata['w']
tensor([[0.], [0.], [0.], [0.], [0.], [0.], [1.]])

Heterogeneous Graphs with Multiple Node Types

>>> g = dgl.heterograph({
...     ('user', 'plays', 'game'): (torch.tensor([0, 1, 1, 2]),
...                                 torch.tensor([0, 0, 1, 1])),
...     ('developer', 'develops', 'game'): (torch.tensor([0, 1]),
...                                         torch.tensor([0, 1]))
...     })
>>> g.add_nodes(2)
DGLError: Node type name must be specified
if there are more than one node types.
>>> g.num_nodes('user')
3
>>> g.add_nodes(2, ntype='user')
>>> g.num_nodes('user')
5