dgl.add_self_loop¶
-
dgl.
add_self_loop
(g, edge_feat_names=None, fill_data=1.0, etype=None)[source]¶ Add self-loops for each node in the graph and return a new graph.
- Parameters
g (DGLGraph) – The graph.
edge_feat_names (list[str], optional) – The names of the self-loop features to apply fill_data. If None, it will apply fill_data to all self-loop features. Default: None.
fill_data (int, float or str, optional) –
The value to fill the self-loop features. Default: 1.
If
fill_data
isint
orfloat
, self-loop features will be directly given byfill_data
.if
fill_data
isstr
, self-loop features will be generated by aggregating the features of the incoming edges of the corresponding nodes. The supported aggregation are:'mean'
,'sum'
,'max'
,'min'
.
etype (str or (str, str, str), optional) –
The type names of the edges. The allowed type name formats are:
(str, str, str)
for source node type, edge type and destination node type.or one
str
edge type name if the name can uniquely identify a triplet format in the graph.
Can be omitted if the graph has only one type of edges.
- Returns
The graph with self-loops.
- Return type
Notes
The function only supports homogeneous graphs or heterogeneous graphs but the relation graph specified by the
etype
argument is homogeneous.The function adds self-loops regardless of whether they already exist or not. If one wishes to have exactly one self-loop for every node, call
remove_self_loop()
before invokingadd_self_loop()
.This function discards the batch information. Please use
dgl.DGLGraph.set_batch_num_nodes()
anddgl.DGLGraph.set_batch_num_edges()
on the transformed graph to maintain the information.
Examples
>>> import dgl >>> import torch
Homogeneous Graphs
>>> g = dgl.graph((torch.tensor([0, 0, 2]), torch.tensor([2, 1, 0]))) >>> g.ndata['hv'] = torch.arange(3).float().reshape(-1, 1) >>> g.edata['he'] = torch.arange(3).float().reshape(-1, 1) >>> g = dgl.add_self_loop(g, fill_data='sum') >>> g Graph(num_nodes=3, num_edges=6, ndata_schemes={'hv': Scheme(shape=(1,), dtype=torch.float32)} edata_schemes={'he': Scheme(shape=(1,), dtype=torch.float32)}) >>> g.edata['he'] tensor([[0.], [1.], [2.], [2.], [1.], [0.]])
Heterogeneous Graphs
>>> g = dgl.heterograph({ ... ('user', 'follows', 'user'): (torch.tensor([1, 2]), ... torch.tensor([0, 1])), ... ('user', 'plays', 'game'): (torch.tensor([0, 1]), ... torch.tensor([0, 1]))}) >>> g = dgl.add_self_loop(g, etype='follows') >>> g Graph(num_nodes={'user': 3, 'game': 2}, num_edges={('user', 'plays', 'game'): 2, ('user', 'follows', 'user'): 5}, metagraph=[('user', 'user'), ('user', 'game')])