dgl.DGLGraph.send_and_recv
- DGLGraph.send_and_recv(edges, message_func, reduce_func, apply_node_func=None, etype=None)[source]
沿着指定的边发送消息,并在目标节点上减少它们以更新它们的特征。
- Parameters:
edges (edges) –
用于发送和接收消息的边。允许的输入格式有:
int
: 单个边ID。Int Tensor: 每个元素都是一个边ID。张量必须具有与图相同的设备类型和ID数据类型。
iterable[int]: 每个元素都是一个边ID。
(Tensor, Tensor): 节点张量格式,其中两个张量的第i个元素指定一条边。
(iterable[int], iterable[int]): 类似于节点张量格式,但将边端点存储在python可迭代对象中。
message_func (dgl.function.BuiltinFunction or callable) – The message function to generate messages along the edges. It must be either a DGL Built-in Function or a User-defined Functions.
reduce_func (dgl.function.BuiltinFunction or callable) – The reduce function to aggregate the messages. It must be either a DGL Built-in Function or a User-defined Functions.
apply_node_func (callable, optional) – An optional apply function to further update the node features after the message reduction. It must be a User-defined Functions.
etype (str or (str, str, str), optional) –
The type name 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.
注释
DGL 建议使用 DGL 的内置函数来处理
message_func
和reduce_func
参数, 因为在这种情况下,DGL 会调用高效的内核,避免将节点特征复制到 边特征。示例
>>> import dgl >>> import dgl.function as fn >>> import torch
同构图
>>> g = dgl.graph(([0, 1, 2, 3], [1, 2, 3, 4])) >>> g.ndata['x'] = torch.ones(5, 2) >>> # Specify edges using (Tensor, Tensor). >>> g.send_and_recv(([1, 2], [2, 3]), fn.copy_u('x', 'm'), fn.sum('m', 'h')) >>> g.ndata['h'] tensor([[0., 0.], [0., 0.], [1., 1.], [1., 1.], [0., 0.]]) >>> # Specify edges using IDs. >>> g.send_and_recv([0, 2, 3], fn.copy_u('x', 'm'), fn.sum('m', 'h')) >>> g.ndata['h'] tensor([[0., 0.], [1., 1.], [0., 0.], [1., 1.], [1., 1.]])
异构图
>>> g = dgl.heterograph({ ... ('user', 'follows', 'user'): ([0, 1], [1, 2]), ... ('user', 'plays', 'game'): ([0, 1, 1, 2], [0, 0, 1, 1]) ... }) >>> g.nodes['user'].data['h'] = torch.tensor([[0.], [1.], [2.]]) >>> g.send_and_recv(g['follows'].edges(), fn.copy_u('h', 'm'), ... fn.sum('m', 'h'), etype='follows') >>> g.nodes['user'].data['h'] tensor([[0.], [0.], [1.]])
使用用户定义函数的``send_and_recv``
>>> import torch as th >>> g = dgl.graph(([0, 1], [1, 2])) >>> g.ndata['x'] = th.tensor([[1.], [2.], [3.]])
>>> # Define the function for sending node features as messages. >>> def send_source(edges): ... return {'m': edges.src['x']} >>> # Sum the messages received and use this to replace the original node feature. >>> def simple_reduce(nodes): ... return {'x': nodes.mailbox['m'].sum(1)}
发送和接收消息。
>>> g.send_and_recv(g.edges()) >>> g.ndata['x'] tensor([[1.], [1.], [2.]])
请注意,节点0的特征保持不变,因为它没有传入边。