dgl.add_nodes
- dgl.add_nodes(g, num, data=None, ntype=None)[source]
向图中添加给定数量的节点并返回一个新图。
新节点的ID将从
g.num_nodes(ntype)开始。- Parameters:
- Returns:
添加了新节点的图表。
- Return type:
注释
For features in
gbut not indata, DGL assigns zero features for the newly added nodes.For feature in
databut 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.
示例
以下示例使用PyTorch后端。
>>> import dgl >>> import torch
同构图
>>> 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
如果图具有一些节点特征,并且添加了没有特征的新节点,它们的特征将被填充为零。
>>> g.ndata['h'] = torch.ones(5, 1) >>> g = dgl.add_nodes(g, 1) >>> g.ndata['h'] tensor([[1.], [1.], [1.], [1.], [1.], [0.]])
为新节点分配特征。
>>> 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.]])
由于
data包含新的特征字段,现有节点的特征将被填充为零。>>> g.ndata['w'] tensor([[0.], [0.], [0.], [0.], [0.], [0.], [1.]])
异构图
>>> 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
另请参阅