Graph Network Notes

dgl:

G = dgl.DGLGraph()
G.add_nodes(10)  # 10 isolated nodes are added
G.add_edge(0, 1)

G.add_edges([1, 2, 3], [3, 4, 5])  # three edges: 1->3, 2->4, 3->5
G.add_edges(4, [7, 8, 9])  # three edges: 4->7, 4->8, 4->9
G.add_edges([2, 6, 8], 5)  # three edges: 2->5, 6->5, 8->5

import torch as th
G.add_edges(th.tensor([3, 4, 5]), 1)  # three edges: 3->1, 4->1, 5->1

## 节点特征设置
G = dgl.DGLGraph()
G.add_nodes(3)
G.ndata['x'] = th.zeros((3, 5))  # init 3 nodes with zero vector(len=5)
"""
G.ndata
{'x' : tensor([[0., 0., 0., 0., 0.],
               [0., 0., 0., 0., 0.],
               [0., 0., 0., 0., 0.]])}
"""
G.nodes[[0, 2]].data['x'] = th.ones((2, 5))
G.ndata

"""
{'x' : tensor([[1., 1., 1., 1., 1.],
               [0., 0., 0., 0., 0.],
               [1., 1., 1., 1., 1.]])}
"""

G.add_edges([0, 1], 2)  # 0->2, 1->2
G.edata['y'] = th.zeros((2, 4))  # init 2 edges with zero vector(len=4)
""""
G.edata
{'y' : tensor([[0., 0., 0., 0.],
               [0., 0., 0., 0.]])}
"""
G.edges[1, 2].data['y'] = th.ones((1, 4))  ## 设置指定边1->2的特征
"""
G.edata
{'y' : tensor([[0., 0., 0., 0.],
               [1., 1., 1., 1.]])}
"""

## Message Passing:
>>> # Define the function for sending messages.
>>> def send_source(edges): return {'m': edges.src['x'] + 1}   # 定义消息传递的函数
>>> # Set the function defined to be the default message function.
>>> G.register_message_func(send_source)     # 把消息函数设置给图G
>>> # Send messages through all edges.
>>> G.send(G.edges())                 

>>> # Define a function for summing messages received and replacing the original feature.
>>> def simple_reduce(nodes): return {'x': nodes.mailbox['m'].sum(1)}
>>> # Set the function defined to be the default message reduce function.
>>> G.register_reduce_func(simple_reduce)
>>> # All existing edges have node 2 as the destination.
>>> # Receive the messages for node 2 and update its feature.
>>> G.recv(v=2)
>>> G.ndata
{'x': tensor([[1., 1., 1., 1., 1.],
              [0., 0., 0., 0., 0.],
              [3., 3., 3., 3., 3.]])} # 3 = (1 + 1) + (0 + 1)
posted @ 2020-08-03 16:16  机器狗mo  阅读(106)  评论(0编辑  收藏  举报