dgl.DGLGraph.remove_nodes

DGLGraph.remove_nodes(nids, ntype=None, store_ids=False)[source]

移除具有指定节点类型的多个节点

连接到节点的边也将被移除。移除节点和边后,剩余的节点和边将使用从0开始的连续整数重新索引,并保持它们的相对顺序。

被移除的节点/边的特征将相应地被移除。

Parameters:
  • nids (int, tensor, numpy.ndarray, list) – 要移除的节点。

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

  • store_ids (bool, optional) – If True, it will store the raw IDs of the extracted nodes and edges in the ndata and edata of the resulting graph under name dgl.NID and dgl.EID, respectively.

注释

此函数保留批次信息。

示例

>>> import dgl
>>> import torch

同构图或具有单一节点类型的异构图

>>> g = dgl.graph((torch.tensor([0, 0, 2]), torch.tensor([0, 1, 2])))
>>> g.ndata['hv'] = torch.arange(3).float().reshape(-1, 1)
>>> g.edata['he'] = torch.arange(3).float().reshape(-1, 1)
>>> g.remove_nodes(torch.tensor([0, 1]))
>>> g
Graph(num_nodes=1, num_edges=1,
    ndata_schemes={'hv': Scheme(shape=(1,), dtype=torch.float32)}
    edata_schemes={'he': Scheme(shape=(1,), dtype=torch.float32)})
>>> g.ndata['hv']
tensor([[2.]])
>>> g.edata['he']
tensor([[2.]])

从批处理图中移除节点会保留批处理信息。

>>> g = dgl.graph((torch.tensor([0, 0, 2]), torch.tensor([0, 1, 2])))
>>> g2 = dgl.graph((torch.tensor([1, 2, 3]), torch.tensor([1, 3, 4])))
>>> bg = dgl.batch([g, g2])
>>> bg.batch_num_nodes()
tensor([3, 5])
>>> bg.remove_nodes([1, 4])
>>> bg.batch_num_nodes()
tensor([2, 4])
>>> bg.batch_num_edges()
tensor([2, 2])

具有多种节点类型的异构图

>>> 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.remove_nodes(torch.tensor([0, 1]))
DGLError: Node type name must be specified
if there are more than one node types.
>>> g.remove_nodes(torch.tensor([0, 1]), ntype='game')
>>> g.num_nodes('user')
3
>>> g.num_nodes('game')
0
>>> g.num_edges('plays')
0