taishan1994 / DGL_Chinese_Manual

DGL中文文档。This is the Chinese manual of the graph neural network library DGL, currently contains the User Guide.
72 stars 14 forks source link

请问DGL在创建异质图的时候能不能先创建空图,然后再慢慢添加边和节点呢 ? #1

Open Kitten-Rec opened 3 years ago

Kitten-Rec commented 3 years ago

例如

g = dgl.heterograph({ ('user', 'follows', 'user'): ([0, 1], [1, 1]), ('game', 'attracts', 'user'): ([0], [1]) })

有没有类似下面的这种写法?

g = dgl.heterograph() g.add({('user', 'follows', 'user'): ([0, 1], [1, 1])}) g.add({('game', 'attracts', 'user'): ([0], [1])})

taishan1994 commented 3 years ago

应该是没有下面这种写法的。刚去搜了下,正好看到一篇csdn下有你的留言,哈哈。那篇其实也指出了:

u, v = torch.tensor([0,0,0,1,2]), torch.tensor([1,2,3,3,1])
g = dgl.graph((u,v))
g.ndata['n_fe'] = torch.ones((g.num_nodes(), 3))
g.ndata['n_fe_matrix'] = torch.rand((g.num_nodes(), 3, 2))
g.edata['e_fe'] = torch.zeros(g.num_edges(), 5)

这种应该就和你说的差不多。

例如

g = dgl.heterograph({ ('user', 'follows', 'user'): ([0, 1], [1, 1]), ('game', 'attracts', 'user'): ([0], [1]) })

有没有类似下面的这种写法?

g = dgl.heterograph() g.add({('user', 'follows', 'user'): ([0, 1], [1, 1])}) g.add({('game', 'attracts', 'user'): ([0], [1])})

taishan1994 commented 3 years ago

又去查了下,或许你可以借助这种方式:

# 使用科学矩阵创建图形。
import scipy.sparse as sp
plus1 = sp.coo_matrix(([1, 1, 1], ([0, 0, 1], [0, 1, 0])), shape=(3, 2))
minus1 = sp.coo_matrix(([1], ([2], [1])), shape=(3, 2))
ratings = dgl.heterograph(
    {('user', '+1', 'movie') : plus1,
     ('user', '-1', 'movie') : minus1})
print(plus1)
print()
print(minus1)

#使用networkx 图创建图形。
import networkx as nx
plus1 = nx.DiGraph()
plus1.add_nodes_from(['u0', 'u1', 'u2'], bipartite=0)
plus1.add_nodes_from(['m0', 'm1'], bipartite=1)
plus1.add_edges_from([('u0', 'm0'), ('u0', 'm1'), ('u1', 'm0')])
# 为了简化示例,重调用minus1对象。
# 这也意味着您可以为不同的关系使用不同的图形数据源。
ratings = dgl.heterograph(
    {('user', '+1', 'movie') : plus1,
     ('user', '-1', 'movie') : minus1})

# 从边缘索引创建
ratings = dgl.heterograph(
    {('user', '+1', 'movie') : ([0, 0, 1], [0, 1, 0]),
     ('user', '-1', 'movie') : ([2], [1])})
Kitten-Rec commented 3 years ago

好的,谢谢您的回答~