通过dgl.graph()创建同构图 通过dgl.heterograph()创建异构图 借助dgl.*工具包和其他数据源生成图,如dgl.from_networkx等
1、两个节点数创建图
import dgl
import torch
#基于 tensor 创建
src = torch.tensor([0, 1, 2, 3])
dst = torch.tensor([1, 2, 3, 4])
g = dgl.graph((src, dst))
#基于 numpy 创建
src = np.array([0, 1, 2, 3])
dst = np.array([1, 2, 3, 4])
g = dgl.graph((src, dst))
#基于 ;list 创建
src = [0, 1, 2, 3]
dst = [1, 2, 3, 4]
g = dgl.graph((src, dst))
g
2、从networkx创建图
import dgl
import networkx as nx
# 创建一个 networkx 图
nx_g = nx.karate_club_graph()
# 转换为 DGL 图
g = dgl.from_networkx(nx_g)
import networkx as nx
nx_g = nx.path_graph(5) # 一条链路0-1-2-3-4
dgl.from_networkx(nx_g) # 来自NetworkX
Graph(num_nodes=5, num_edges=8,
ndata_schemes={}
edata_schemes={})
nxg = nx.DiGraph([(2, 1), (1, 2), (2, 3), (0, 0)])
dgl.from_networkx(nxg)
4, num_edges=4, =
ndata_schemes={}
edata_schemes={})
3、使用稀疏矩阵创建图
import dgl
import scipy.sparse as sp
import torch
adj = sp.coo_matrix([
[ ],
[ ],
[ ],
[ ],
[ ]
])
g = dgl.graph((torch.tensor(adj.row), torch.tensor(adj.col)))
spmat = sp.rand(100, 100, density=0.05)
dgl.from_scipy(spmat)
4、从DataFrame创建图
import dgl
import pandas as pd
# 创建一个 dataframe
df = pd.DataFrame({
'source': [0, 1, 2, 3],
'target': [1, 2, 3, 4]
})
# 转换为 DGL 图
g = dgl.graph((df['source'].values, df['target'].values))
g
5、 随机图生成
# 随机生产图
g = dgl.rand_graph(100, 10)
#转换为networkx
nx_g = dgl.to_networkx(g)
#可视化看
fig = plt.figure(figsize=(4,3.5),dpi=1000)
nx.draw(nx_graph,with_labels=True, width=0.2,node_color='skyblue',node_size=800, font_size=13)
plt.show()
import dgl
g = dgl.rand_bipartite('user', 'buys', 'game', 50, 100, 10)
g
Graph(num_nodes={'game': 100, 'user': 50},
num_edges={('user', 'buys', 'game'): 10},
metagraph=[('user', 'game', 'buys')])
g.edges()
(tensor([38, 19, 16, 37, 10, 35, 7, 26, 3, 27]),
tensor([50, 84, 53, 34, 75, 76, 69, 68, 80, 24]))
6、从其他图格式导入
import dgl
import networkx as nx
# 从 GraphML 文件读取图数据
nx_g = nx.read_graphml('path_to_graph_file.graphml')
g = dgl.from_networkx(nx_g)
7、边索引创建异构图
import dgl
data_dict = {
('user', 'follows', 'user'): ([0, 1], [1, 2]),
('user', 'writes', 'post'): ([0, 1], [0, 1]),
('post', 'mentions', 'user'): ([0, 1], [1, 2])
}
hetero_g = dgl.heterograph(data_dict)
8、二分图
# uni-directional bipartite举例
graph_data1 = {
('drug', 'interacts2', 'gene'): (th.tensor([0, 1]), th.tensor([2, 3]))
}
g1 = dgl.heterograph(graph_data1)
# uni-bipartite举例
graph_data2 = {
('drug', 'interacts2', 'gene'): (th.tensor([0, 1]), th.tensor([2, 3])),
('drug', 'treats', 'disease'): (th.tensor([1]), th.tensor([2]))
}
g2 = dgl.heterograph(graph_data2)
9、总 结
往期精彩:
SynchroTrap-基于松散行为相似度的欺诈账户检测算法