dgl.bipartite_from_scipy

dgl.bipartite_from_scipy(sp_mat, utype, etype, vtype, eweight_name=None, idtype=None, device=None)[source]

从SciPy稀疏矩阵创建一个单向二分图并返回。

创建的图将有两种类型的节点 utypevtype,以及一种边类型 etype,其边从 utype 指向 vtype

Parameters:
  • sp_mat (scipy.sparse.spmatrix) – 图的邻接矩阵。每个非零条目 sp_mat[i, j] 表示从类型为 utype 的节点 i 到类型为 vtype 的节点 j 的边。 设矩阵的形状为 (N, M)。在生成的图中将有 N 个类型为 utype 的节点和 M 个类型为 vtype 的节点。

  • utype (str, optional) – 源节点类型的名称。

  • etype (str, optional) – 边的类型的名称。

  • vtype (str, optional) – 目标节点类型的名称。

  • eweight_name (str, optional) – 用于存储sp_mat非零值的edata名称。 如果提供,DGL将把sp_mat的非零值存储在返回图的edata[eweight_name]中。

  • idtype (int32int64, 可选) – 用于存储结构相关图形信息(如节点和边ID)的数据类型。它应该是框架特定的数据类型对象(例如,torch.int32)。默认情况下,DGL使用int64。

  • device (设备上下文, 可选) – 结果图的设备。它应该是一个框架特定的设备对象 (例如,torch.device)。默认情况下,DGL将图存储在CPU上。

Returns:

创建的图表。

Return type:

DGLGraph

注释

  1. 该函数支持所有类型的SciPy稀疏矩阵类(例如, scipy.sparse.csr.csr_matrix)。它在创建DGLGraph之前,使用scipy.sparse.spmatrix.tocoo()将输入矩阵转换为COOrdinate格式。 因此,从scipy.sparse.coo.coo_matrix创建是最有效的方式。

  2. DGL internally maintains multiple copies of the graph structure in different sparse formats and chooses the most efficient one depending on the computation invoked. If memory usage becomes an issue in the case of large graphs, use dgl.DGLGraph.formats() to restrict the allowed 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')