Generate a node feature equal to the graph-level feature :attr:`graph_feat`. The operation is similar to ``numpy.repeat`` (or ``torch.repeat_interleave``). It is commonly used to normalize node features by a global vector. For example, to normalize node features across graph to range :m
(graph, graph_feat, *, ntype=None)
| 372 | |
| 373 | |
| 374 | def broadcast_nodes(graph, graph_feat, *, ntype=None): |
| 375 | """Generate a node feature equal to the graph-level feature :attr:`graph_feat`. |
| 376 | |
| 377 | The operation is similar to ``numpy.repeat`` (or ``torch.repeat_interleave``). |
| 378 | It is commonly used to normalize node features by a global vector. For example, |
| 379 | to normalize node features across graph to range :math:`[0~1)`: |
| 380 | |
| 381 | >>> g = dgl.batch([...]) # batch multiple graphs |
| 382 | >>> g.ndata['h'] = ... # some node features |
| 383 | >>> h_sum = dgl.broadcast_nodes(g, dgl.sum_nodes(g, 'h')) |
| 384 | >>> g.ndata['h'] /= h_sum # normalize by summation |
| 385 | |
| 386 | Parameters |
| 387 | ---------- |
| 388 | graph : DGLGraph |
| 389 | The graph. |
| 390 | graph_feat : tensor |
| 391 | The feature to broadcast. Tensor shape is :math:`(B, *)` for batched graph, |
| 392 | where :math:`B` is the batch size. |
| 393 | |
| 394 | ntype : str, optional |
| 395 | Node type. Can be omitted if there is only one node type. |
| 396 | |
| 397 | Returns |
| 398 | ------- |
| 399 | Tensor |
| 400 | The node features tensor with shape :math:`(N, *)`, where :math:`N` is the |
| 401 | number of nodes. |
| 402 | |
| 403 | Examples |
| 404 | -------- |
| 405 | |
| 406 | >>> import dgl |
| 407 | >>> import torch as th |
| 408 | |
| 409 | Create two :class:`~dgl.DGLGraph` objects and initialize their |
| 410 | node features. |
| 411 | |
| 412 | >>> g1 = dgl.graph(([0], [1])) # Graph 1 |
| 413 | >>> g2 = dgl.graph(([0, 1], [1, 2])) # Graph 2 |
| 414 | >>> bg = dgl.batch([g1, g2]) |
| 415 | >>> feat = th.rand(2, 5) |
| 416 | >>> feat |
| 417 | tensor([[0.4325, 0.7710, 0.5541, 0.0544, 0.9368], |
| 418 | [0.2721, 0.4629, 0.7269, 0.0724, 0.1014]]) |
| 419 | |
| 420 | Broadcast feature to all nodes in the batched graph, feat[i] is broadcast to nodes |
| 421 | in the i-th example in the batch. |
| 422 | |
| 423 | >>> dgl.broadcast_nodes(bg, feat) |
| 424 | tensor([[0.4325, 0.7710, 0.5541, 0.0544, 0.9368], |
| 425 | [0.4325, 0.7710, 0.5541, 0.0544, 0.9368], |
| 426 | [0.2721, 0.4629, 0.7269, 0.0724, 0.1014], |
| 427 | [0.2721, 0.4629, 0.7269, 0.0724, 0.1014], |
| 428 | [0.2721, 0.4629, 0.7269, 0.0724, 0.1014]]) |
| 429 | |
| 430 | Broadcast feature to all nodes in the single graph (the feature tensor shape |
| 431 | to broadcast should be :math:`(1, *)`). |