1.3 节点和边特征

(中文版)

DGLGraph 的节点和边可以有几个用户自定义的命名特征,用于存储节点和边的图特定属性。这些特征可以通过 ndataedata 接口访问。例如,以下代码创建了两个节点特征(在第 8 行和第 15 行命名为 'x''y')和一个边特征(在第 9 行命名为 'x')。

 1>>> import dgl
 2>>> import torch as th
 3>>> g = dgl.graph(([0, 0, 1, 5], [1, 2, 2, 0])) # 6 nodes, 4 edges
 4>>> g
 5Graph(num_nodes=6, num_edges=4,
 6      ndata_schemes={}
 7      edata_schemes={})
 8>>> g.ndata['x'] = th.ones(g.num_nodes(), 3)               # node feature of length 3
 9>>> g.edata['x'] = th.ones(g.num_edges(), dtype=th.int32)  # scalar integer feature
10>>> g
11Graph(num_nodes=6, num_edges=4,
12      ndata_schemes={'x' : Scheme(shape=(3,), dtype=torch.float32)}
13      edata_schemes={'x' : Scheme(shape=(,), dtype=torch.int32)})
14>>> # different names can have different shapes
15>>> g.ndata['y'] = th.randn(g.num_nodes(), 5)
16>>> g.ndata['x'][1]                  # get node 1's feature
17tensor([1., 1., 1.])
18>>> g.edata['x'][th.tensor([0, 3])]  # get features of edge 0 and 3
19    tensor([1, 1], dtype=torch.int32)

关于 ndata/edata 接口的重要事项

  • 只允许数值类型的特征(例如,float、double 和 int)。它们可以是标量、向量或多维张量。

  • 每个节点特征都有一个唯一的名称,每个边特征也有一个唯一的名称。节点和边的特征可以有相同的名称。(例如,上面例子中的“x”)。

  • 通过张量赋值创建特征,将特征赋给图中的每个节点/边。该张量的首要维度必须等于图中的节点/边数量。您不能将特征赋给图中的节点/边子集。

  • 同名特征必须具有相同的维度和数据类型。

  • 特征张量采用行主布局——每个行切片存储一个节点或边的特征(例如,参见上面示例中的第 16 行和第 18 行)。

对于加权图,可以将权重作为边特征存储,如下所示。

>>> # edges 0->1, 0->2, 0->3, 1->3
>>> edges = th.tensor([0, 0, 0, 1]), th.tensor([1, 2, 3, 3])
>>> weights = th.tensor([0.1, 0.6, 0.9, 0.7])  # weight of each edge
>>> g = dgl.graph(edges)
>>> g.edata['w'] = weights  # give it a name 'w'
>>> g
Graph(num_nodes=4, num_edges=4,
      ndata_schemes={}
      edata_schemes={'w' : Scheme(shape=(,), dtype=torch.float32)})

参见 API:ndata, edata