mean_nodes(graph, feat, weight=None)¶
Averages all the values of node field
graph, optionally multiplies the field by a scalar node field
- graph (DGLGraph or BatchedDGLGraph) – The graph.
- feat (str) – The feature field.
- weight (str, optional) – The weight field. If None, no weighting will be performed,
otherwise, weight each node feature with field
feat. for calculating mean. The weight feature associated in the
graphshould be a tensor of shape
The averaged tensor.
If graph is a
BatchedDGLGraphobject, a stacked tensor is returned instead, i.e. having an extra first dimension. Each row of the stacked tensor contains the readout result of corresponding example in the batch. If an example has no nodes, a zero tensor with the same shape is returned at the corresponding row.
>>> import dgl >>> import torch as th
DGLGraphobjects and initialize their node features.
>>> g1 = dgl.DGLGraph() # Graph 1 >>> g1.add_nodes(2) >>> g1.ndata['h'] = th.tensor([[1.], [2.]]) >>> g1.ndata['w'] = th.tensor([[3.], [6.]])
>>> g2 = dgl.DGLGraph() # Graph 2 >>> g2.add_nodes(3) >>> g2.ndata['h'] = th.tensor([[1.], [2.], [3.]])
Average over node attribute
hwithout weighting for each graph in a batched graph.
>>> bg = dgl.batch([g1, g2], node_attrs='h') >>> dgl.mean_nodes(bg, 'h') tensor([[1.5000], # (1 + 2) / 2 [2.0000]]) # (1 + 2 + 3) / 3
Sum node attribute
hwith normalized weight from node attribute
wfor a single graph.
>>> dgl.mean_nodes(g1, 'h', 'w') # h1 * (w1 / (w1 + w2)) + h2 * (w2 / (w1 + w2)) tensor([1.6667]) # 1 * (3 / (3 + 6)) + 2 * (6 / (3 + 6))