dgl.mean_edges

dgl.mean_edges(graph, feat, weight=None)[source]

Averages all the values of edge field feat in graph, optionally multiplies the field by a scalar edge field weight.

Parameters:
  • graph (DGLGraph) – The graph.
  • feat (str) – The feature field.
  • weight (optional, str) – The weight field. If None, no weighting will be performed, otherwise, weight each edge feature with field feat. for calculating mean. The weight feature associated in the graph should be a tensor of shape [graph.number_of_edges(), 1].
Returns:

The averaged tensor.

Return type:

tensor

Notes

If graph is a BatchedDGLGraph object, 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 edges, a zero tensor with the same shape is returned at the corresponding row.

Examples

>>> import dgl
>>> import torch as th

Create two DGLGraph objects and initialize their edge features.

>>> g1 = dgl.DGLGraph()                           # Graph 1
>>> g1.add_nodes(2)
>>> g1.add_edges([0, 1], [1, 0])
>>> g1.edata['h'] = th.tensor([[1.], [2.]])
>>> g1.edata['w'] = th.tensor([[3.], [6.]])
>>> g2 = dgl.DGLGraph()                           # Graph 2
>>> g2.add_nodes(3)
>>> g2.add_edges([0, 1, 2], [1, 2, 0])
>>> g2.edata['h'] = th.tensor([[1.], [2.], [3.]])

Average over edge attribute h without weighting for each graph in a batched graph.

>>> bg = dgl.batch([g1, g2], edge_attrs='h')
>>> dgl.mean_edges(bg, 'h')
tensor([[1.5000],    # (1 + 2) / 2
        [2.0000]])   # (1 + 2 + 3) / 3

Sum edge attribute h with normalized weight from edge attribute w for a single graph.

>>> dgl.mean_edges(g1, 'h', 'w') # h1 * (w1 / (w1 + w2)) + h2 * (w2 / (w1 + w2))
tensor([1.6667])                 # 1 * (3 / (3 + 6)) + 2 * (6 / (3 + 6))