dgl.DGLGraph.set_n_initializer¶
-
DGLGraph.
set_n_initializer
(initializer, field=None, ntype=None)¶ Set the initializer for node features.
When only part of the nodes have a feature (e.g. new nodes are added, features are set for a subset of nodes), the initializer initializes features for the rest nodes.
- Parameters
initializer (callable) –
A function of signature
func(shape, dtype, ctx, id_range) -> Tensor
. The tensor will be the initialized features. The arguments are:shape
: The shape of the tensor to return, which is a tuple of int. The first dimension is the number of nodes for feature initialization.dtype
: The data type of the tensor to return, which is a framework-specific data type object.ctx
: The device of the tensor to return, which is a framework-specific device object.id_range
: The start and end ID of the nodes for feature initialization, which is a slice.
field (str, optional) – The name of the feature that the initializer applies. If not given, the initializer applies to all features.
ntype (str, optional) – The type name of the nodes. Can be omitted if the graph has only one type of nodes.
Notes
Without setting a node feature initializer, zero tensors are generated for nodes without a feature.
Examples
The following example uses PyTorch backend.
>>> import dgl >>> import torch
Define a function for initializer.
>>> def init_feats(shape, dtype, device, id_range): ... return torch.ones(shape, dtype=dtype, device=device)
An example for a homogeneous graph.
>>> g = dgl.graph((torch.tensor([0]), torch.tensor([1]))) >>> g.ndata['h1'] = torch.zeros(2, 2) >>> g.ndata['h2'] = torch.ones(2, 1) >>> # Apply the initializer to feature 'h2' only. >>> g.set_n_initializer(init_feats, field='h2') >>> g.add_nodes(1) >>> print(g.ndata['h1']) tensor([[0., 0.], [0., 0.], [0., 0.]]) >>> print(g.ndata['h2']) tensor([[1.], [1.], [1.]])
An example for a heterogeneous graph of multiple node types.
>>> g = dgl.heterograph({ ... ('user', 'plays', 'game'): (torch.tensor([0, 1, 1, 2]), ... torch.tensor([0, 0, 1, 1])), ... ('developer', 'develops', 'game'): (torch.tensor([0, 1]), ... torch.tensor([0, 1])) ... }) >>> g.nodes['user'].data['h'] = torch.zeros(3, 2) >>> g.nodes['game'].data['w'] = torch.ones(2, 2) >>> g.set_n_initializer(init_feats, ntype='game') >>> g.add_nodes(1, ntype='user') >>> # Initializer not set for 'user', use zero tensors by default >>> g.nodes['user'].data['h'] tensor([[0., 0.], [0., 0.], [0., 0.], [0., 0.]]) >>> # Initializer set for 'game' >>> g.add_nodes(1, ntype='game') >>> g.nodes['game'].data['w'] tensor([[1., 1.], [1., 1.], [1., 1.]])