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:
- Returns:
The graph with newly added nodes.
- Return type:
Notes
For features in
g
but not indata
, DGL assigns zero features for the newly added nodes.For feature in
data
but not ing
, DGL assigns zero features for the existing nodes in the graph.This function discards the batch information. Please use
dgl.DGLGraph.set_batch_num_nodes()
anddgl.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
>>> 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
See also