dgl.bipartite_from_scipy
- dgl.bipartite_from_scipy(sp_mat, utype, etype, vtype, eweight_name=None, idtype=None, device=None)[source]
从 SciPy 稀疏矩阵创建单向二分图并返回。
创建的图将有两种类型的节点
utype
和vtype
,以及一种边类型etype
,其边从utype
指向vtype
。- 参数:
sp_mat (scipy.sparse.spmatrix) – 图的邻接矩阵。每个非零条目
sp_mat[i, j]
表示从类型为utype
的节点i
到类型为vtype
的节点j
的一条边。设矩阵形状为(N, M)
。结果图中将有N
个类型为utype
的节点和M
个类型为vtype
的节点。utype (str, 可选) – 源节点类型的名称。
etype (str, 可选) – 边类型的名称。
vtype (str, 可选) – 目标节点类型的名称。
eweight_name (str, 可选) – 用于存储
sp_mat
非零值的边数据名称。如果给出,DGL 会将sp_mat
的非零值存储在返回图的edata[eweight_name]
中。idtype (int32 或 int64, 可选) – 用于存储与结构相关的图信息(例如节点和边 ID)的数据类型。它应该是一个框架特定的数据类型对象(例如,
torch.int32
)。默认情况下,DGL 使用 int64。device (设备上下文, 可选) – 结果图的设备。它应该是一个框架特定的设备对象(例如,
torch.device
)。默认情况下,DGL 将图存储在 CPU 上。
- 返回:
创建的图。
- 返回类型:
备注
此函数支持各种 SciPy 稀疏矩阵类(例如,
scipy.sparse.csr.csr_matrix
)。它在创建DGLGraph
之前,使用scipy.sparse.spmatrix.tocoo()
将输入矩阵转换为 COOrdinate 格式。因此,从scipy.sparse.coo.coo_matrix
创建是最有效的方式。DGL 内部以不同的稀疏格式维护图结构的多个副本,并根据调用的计算选择最有效的格式。如果对于大型图来说内存使用成为问题,可以使用
dgl.DGLGraph.formats()
来限制允许的格式。
示例
以下示例使用 PyTorch 后端。
>>> import dgl >>> import numpy as np >>> import torch >>> from scipy.sparse import coo_matrix
创建一个小型三边图。
>>> # Source nodes for edges (2, 1), (3, 2), (4, 3) >>> src_ids = np.array([2, 3, 4]) >>> # Destination nodes for edges (2, 1), (3, 2), (4, 3) >>> dst_ids = np.array([1, 2, 3]) >>> # Weight for edges (2, 1), (3, 2), (4, 3) >>> eweight = np.array([0.2, 0.3, 0.5]) >>> sp_mat = coo_matrix((eweight, (src_ids, dst_ids))) >>> g = dgl.bipartite_from_scipy(sp_mat, utype='_U', etype='_E', vtype='_V')
检索边权重。
>>> g = dgl.bipartite_from_scipy(sp_mat, utype='_U', etype='_E', vtype='_V', eweight_name='w') >>> g.edata['w'] tensor([0.2000, 0.3000, 0.5000], dtype=torch.float64)
在第一个 GPU 上创建一个数据类型为 int32 的图。
>>> g = dgl.bipartite_from_scipy(sp_mat, utype='_U', etype='_E', vtype='_V', ... idtype=torch.int32, device='cuda:0')