dgl.add_nodes

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

向图中添加给定数量的节点并返回一个新图。

新节点的ID将从g.num_nodes(ntype)开始。

Parameters:
  • num (int) – 要添加的节点数量。

  • data (dict[str, Tensor], optional) – 添加节点的特征数据。键是特征名称,而值是特征数据。

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

Returns:

添加了新节点的图表。

Return type:

DGLGraph

注释

示例

以下示例使用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