DGL库之创建heterogeneous graph(异构图)
dgl.heterograph语法格式
dgl.heterograph(data_dict, num_nodes_dict=None, idtype=None, device=None)
其参数解释如下:
- data_dict:类型为dict,一个字典。键是边的类型(如 (‘user’, ‘follow’, ‘user’)),值是一个包含边的源节点和目标节点的元组。每个元组是 (src, dst),其中 src 和 dst
是包含边的起始节点和结束节点的数组或张量。 - num_nodes_dict(可选):类型为dict 或 None。定义每种类型节点的数量。如果提供,键是节点类型(如 ‘user’),值是节点的数量。如果为 None,DGL 会根据 data_dict 自动推断节点数量。
- idtype (可选):类型: dgl.backend.dtype。节点和边 ID 的数据类型,通常为 int32 或 int64。如果未提供,DGL 将根据数据类型自动选择。
- device (可选):类型为str 或 torch.device。指定设备类型(如 cpu 或 cuda)。如果未提供,默认使用 CPU。
创建异构图
仅使用data_dict
import dgl
import torch as th
data_dict = {
('drug', 'interacts', 'drug'): (th.tensor([0, 1]), th.tensor([1, 2])),
('drug', 'interacts', 'gene'): (th.tensor([0, 1]), th.tensor([2, 3])),
('drug', 'treats', 'disease'): (th.tensor([1]), th.tensor([2]))
}
g = dgl.heterograph(data_dict)
print(f'异构图为:\n{g}')
print('----------------------------')
print(f'节点类型为:{g.ntypes}')
print('----------------------------')
print(f'边类型为:{g.etypes}')
print('----------------------------')
print(f'边类型为:{g.canonical_etypes}')
结果如下:

具体理解如下:
| drug节点类型 | A | B | C |
|---|---|---|---|
| drug代码节点标号 | 0 | 1 | 2 |
| gene节点类型 | a | b | c | d |
|---|---|---|---|---|
| gene代码节点标号 | 0 | 1 | 2 | 3 |
| diease节点类型 | p | m | n |
|---|---|---|---|
| diease代码节点标号 | 0 | 1 | 2 |
最终如下图所示:

使用num_nodes_dict
import dgl
import torch as th
data_dict = {
('drug', 'interacts', 'drug'): (th.tensor([0, 1]), th.tensor([1, 2])),
('drug', 'interacts', 'gene'): (th.tensor([0, 1]), th.tensor([2, 3])),
('drug', 'treats', 'disease'): (th.tensor([1]), th.tensor([2]))
}
num_nodes_dict = {'drug': 5, 'gene': 5, 'disease': 5}
g = dgl.heterograph(data_dict, num_nodes_dict=num_nodes_dict)
print(f'异构图为:\n{g}')
print('----------------------------')
print(f'节点类型为:{g.ntypes}')
print('----------------------------')
print(f'边类型为:{g.etypes}')
print('----------------------------')
print(f'边类型为:{g.canonical_etypes}')
结果如下:

使用idtype和device
g = dgl.heterograph(data_dict, idtype=torch.int32, device='cuda:0')

3405

被折叠的 条评论
为什么被折叠?



