dgl.DGLGraph.local_scope
- DGLGraph.local_scope()[source]
为图表输入一个本地范围上下文。
通过进入局部作用域,对特征数据的任何外部修改都不会反映到原始图中,从而使其在函数作用域中更易于使用(例如,模型的前向计算)。
如果设置,本地作用域将对节点特征和边特征使用相同的初始化器。
注释
原地操作确实会反映到原始图中。当图中的特征张量数量较少时,此函数的开销也很小。
示例
以下示例使用PyTorch后端。
>>> import dgl >>> import torch
创建一个用于图计算的函数。
>>> def foo(g): ... with g.local_scope(): ... g.edata['h'] = torch.ones((g.num_edges(), 3)) ... g.edata['h2'] = torch.ones((g.num_edges(), 3)) ... return g.edata['h']
local_scope
避免在退出函数时改变图形特征。>>> g = dgl.graph((torch.tensor([0, 1, 1]), torch.tensor([0, 0, 2]))) >>> g.edata['h'] = torch.zeros((g.num_edges(), 3)) >>> newh = foo(g) >>> print(g.edata['h']) # still get tensor of all zeros tensor([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]) >>> 'h2' in g.edata # new feature set in the function scope is not found False
原地操作仍将反映到原始图中。
>>> def foo(g): ... with g.local_scope(): ... # in-place operation ... g.edata['h'] += 1 ... return g.edata['h']
>>> g = dgl.graph((torch.tensor([0, 1, 1]), torch.tensor([0, 0, 2]))) >>> g.edata['h'] = torch.zeros((g.num_edges(), 1)) >>> newh = foo(g) >>> print(g.edata['h']) # the result changes tensor([[1.], [1.], [1.]])
另请参阅
local_var