dgl.sum_nodes¶
-
dgl.
sum_nodes
(graph, input, weight=None)[source]¶ Sums all the values of node field
input
ingraph
, optionally multiplies the field by a scalar node fieldweight
.Parameters: - graph (DGLGraph or BatchedDGLGraph) – The graph
- input (str) – The input field
- weight (str, optional) – The weight field. If None, no weighting will be performed,
otherwise, weight each node feature with field
input
. for summation. The weight feature associated in thegraph
should be a tensor of shape[graph.number_of_nodes(), 1]
.
Returns: The summed 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 the corresponding example in the batch. If an example has no nodes, 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 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.]])
Sum over node attribute
h
without weighting for each graph in a batched graph.>>> bg = dgl.batch([g1, g2], node_attrs='h') >>> dgl.sum_nodes(bg, 'h') tensor([[3.], # 1 + 2 [6.]]) # 1 + 2 + 3
Sum node attribute
h
with weight from node attributew
for a single graph.>>> dgl.sum_nodes(g1, 'h', 'w') tensor([15.]) # 1 * 3 + 2 * 6
See also