dgl.DGLHeteroGraph.ndata

property DGLHeteroGraph.ndata

Return a node data view for setting/getting node features

Let g be a DGLGraph. If g is a graph of a single node type, g.ndata[feat] returns the node feature associated with the name feat. One can also set a node feature associated with the name feat by setting g.ndata[feat] to a tensor.

If g is a graph of multiple node types, g.ndata[feat] returns a dict[str, Tensor] mapping node types to the node features associated with the name feat for the corresponding type. One can also set a node feature associated with the name feat for some node type(s) by setting g.ndata[feat] to a dictionary as described.

Notes

For setting features, the device of the features must be the same as the device of the graph.

Examples

The following example uses PyTorch backend.

>>> import dgl
>>> import torch

Set and get feature ‘h’ for a graph of a single node type.

>>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2])))
>>> g.ndata['h'] = torch.ones(3, 1)
>>> g.ndata['h']
tensor([[1.],
        [1.],
        [1.]])

Set and get feature ‘h’ for a graph of multiple node types.

>>> g = dgl.heterograph({
...     ('user', 'follows', 'user'): (torch.tensor([1, 2]), torch.tensor([3, 4])),
...     ('player', 'plays', 'game'): (torch.tensor([2, 2]), torch.tensor([1, 1]))
... })
>>> g.ndata['h'] = {'game': torch.zeros(2, 1), 'player': torch.ones(3, 1)}
>>> g.ndata['h']
{'game': tensor([[0.], [0.]]),
 'player': tensor([[1.], [1.], [1.]])}
>>> g.ndata['h'] = {'game': torch.ones(2, 1)}
>>> g.ndata['h']
{'game': tensor([[1.], [1.]]),
 'player': tensor([[1.], [1.], [1.]])}

See also

nodes