dgl.DGLGraph.local_scope
- DGLGraph.local_scope()[源码]
进入图的本地作用域上下文。
通过进入本地作用域,任何对特征数据的非原地修改都不会反映到原始图上,从而使其更容易在函数作用域中使用(例如模型的正向计算)。
如果设置,本地作用域将对节点特征和边特征使用相同的初始化器。
注意事项
原地操作确实会反映到原始图上。当图中特征张量数量较少时,此函数开销也很小。
示例
以下示例使用 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