dgl.add_nodesΒΆ

dgl.add_nodes(g, num, data=None, ntype=None)[source]ΒΆ

Add the given number of nodes to the graph and return a new graph.

The new nodes will have IDs starting from g.num_nodes(ntype).

Parameters
  • num (int) – The number of nodes to add.

  • data (dict[str, Tensor], optional) – Feature data of the added nodes. The keys are feature names while the values are feature data.

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

Returns

The graph with newly added nodes.

Return type

DGLGraph

Notes

Examples

The following example uses PyTorch backend.

>>> import dgl
>>> import torch

Homogeneous Graphs

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

If the graph has some node features and new nodes are added without features, their features will be filled with zeros.

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

Assign features for the new nodes.

>>> g = dgl.add_nodes(g, 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 existing nodes will be filled with zeros.

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

Heterogeneous Graphs

>>> 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.num_nodes('user')
3
>>> g = dgl.add_nodes(g, 2, ntype='user')
>>> g.num_nodes('user')
5