dgl.DGLGraph.ndataΒΆ
-
property
DGLGraph.
ndata
ΒΆ Return a node data view for setting/getting node features
Let
g
be a DGLGraph. Ifg
is a graph of a single node type,g.ndata[feat]
returns the node feature associated with the namefeat
. One can also set a node feature associated with the namefeat
by settingg.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 namefeat
for the corresponding type. One can also set a node feature associated with the namefeat
for some node type(s) by settingg.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