dgl.add_edges

dgl.add_edges(g, u, v, data=None, etype=None)[source]

将边添加到图中并返回一个新图。

第i条新边将从u[i]指向v[i]。新边的ID将从g.num_edges(etype)开始。

Parameters:
  • u (int, Tensoriterable[int]) – 源节点ID,u[i] 给出第i条新边的源节点。

  • v (int, Tensoriterable[int]) – 目标节点ID,v[i] 给出第i条新边的目标节点。

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

  • etype (str or (str, str, str), optional) –

    The type names of the edges. The allowed type name formats are:

    • (str, str, str) for source node type, edge type and destination node type.

    • or one str edge type name if the name can uniquely identify a triplet format in the graph.

    Can be omitted if the graph has only one type of edges.

Returns:

添加了新边的图表。

Return type:

DGLGraph

注释

  • 如果给定边的终端节点在g中不存在, dgl.add_nodes()将被调用来添加这些节点。 新节点的节点特征将用零填充。

  • 对于在g中但不在data中的特征,DGL为新添加的节点分配零特征。

  • 对于在data中但不在g中的特征,DGL会为图中的现有节点分配零特征。

  • This function discards the batch information. Please use dgl.DGLGraph.set_batch_num_nodes() and dgl.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_edges()
2
>>> g = dgl.add_edges(g, torch.tensor([1, 3]), torch.tensor([0, 1]))
>>> g.num_edges()
4

由于 uv 包含一个不存在的节点 ID,节点被隐式添加。

>>> g.num_nodes()
4

如果图具有一些边特征,并且添加了没有特征的新边,则它们特征将被填充为零。

>>> g.edata['h'] = torch.ones(4, 1)
>>> g = dgl.add_edges(g, torch.tensor([1]), torch.tensor([1]))
>>> g.edata['h']
tensor([[1.], [1.], [1.], [1.], [0.]])

在添加新边时,您还可以为新边分配特征。

>>> g = dgl.add_edges(g, torch.tensor([0, 0]), torch.tensor([2, 2]),
...                   {'h': torch.tensor([[1.], [2.]]), 'w': torch.ones(2, 1)})
>>> g.edata['h']
tensor([[1.], [1.], [1.], [1.], [0.], [1.], [2.]])

由于data包含新的特征字段,旧边的特征将被填充为零。

>>> g.edata['w']
tensor([[0.], [0.], [0.], [0.], [0.], [1.], [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_edges('plays')
4
>>> g = dgl.add_edges(g, torch.tensor([3]), torch.tensor([3]), etype='plays')
>>> g.num_edges('plays')
5