dgl.add_self_loop
- dgl.add_self_loop(g, edge_feat_names=None, fill_data=1.0, etype=None)[source]
为图中的每个节点添加自环并返回一个新图。
- Parameters:
g (DGLGraph) – The graph.
edge_feat_names (list[str], optional) – 要应用fill_data的自环特征名称。如果为None,则会将fill_data应用于所有自环特征。默认值:None。
fill_data (int, float or str, optional) –
用于填充自环特征的值。默认值为1。
如果
fill_data
是int
或float
,自环特征将直接由fill_data
给出。如果
fill_data
是str
,自环特征将通过聚合对应节点的入边特征生成。支持的聚合方式有:'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:
带有自环的图。
- Return type:
注释
该函数仅支持同构图或异构图,但由
etype
参数指定的关系图是同构的。该函数会添加自环,无论它们是否已经存在。 如果希望每个节点恰好有一个自环, 在调用
add_self_loop()
之前,请先调用remove_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.
示例
>>> import dgl >>> import torch
同构图
>>> 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.]])
异构图
>>> 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')])