dgl.graph
- dgl.graph(data, *, num_nodes=None, idtype=None, device=None, row_sorted=False, col_sorted=False)[source]
创建一个图形并返回。
- Parameters:
data (图数据) –
用于构建图的数据,形式为 \((U, V)\)。 \((U[i], V[i])\) 形成图中 ID 为 \(i\) 的边。 允许的数据格式有:
(Tensor, Tensor)
: 每个张量必须是一个包含节点 ID 的一维张量。 DGL 称这种格式为“节点张量元组”。张量应具有相同的数据类型 int32/int64 和设备上下文(见下文idtype
和device
的描述)。('coo', (Tensor, Tensor))
: 与(Tensor, Tensor)
相同。('csr', (Tensor, Tensor, Tensor))
: 这三个张量构成图的邻接矩阵的 CSR 表示。 第一个是行索引指针。第二个是列索引。第三个是边 ID,可以为空以表示从 0 开始的连续整数 ID。('csc', (Tensor, Tensor, Tensor))
: 这三个张量构成图的邻接矩阵的 CSC 表示。 第一个是列索引指针。第二个是行索引。第三个是边 ID,可以为空以表示从 0 开始的连续整数 ID。
张量可以替换为任何整数可迭代对象(例如列表、元组、numpy.ndarray)。
num_nodes (int, optional) – 图中的节点数量。如果未提供,则将从
data
参数中获取最大的节点ID加1。如果提供了该值且不大于data
参数中的最大节点ID,DGL将抛出错误。idtype (int32 或 int64, 可选) – 用于存储结构相关图形信息(如节点和边ID)的数据类型。它应该是框架特定的数据类型对象(例如,
torch.int32
)。 如果为None
(默认值),DGL 会从data
参数推断 ID 类型。 有关更多详细信息,请参阅“注释”。device (device context, optional) – The device of the returned graph, which should be a framework-specific device object (e.g.,
torch.device
). IfNone
(default), DGL uses the device of the tensors of thedata
argument. Ifdata
is not a tuple of node-tensors, the returned graph is on CPU. If the specifieddevice
differs from that of the provided tensors, it casts the given tensors to the specified device first.row_sorted (bool, 可选) – COO的行是否按升序排列。
col_sorted (bool, optional) – COO的列是否在每行内按升序排列。这仅在
row_sorted
为True时有效。
- Returns:
创建的图表。
- Return type:
注释
If the
idtype
argument is not given then:在节点-张量格式的元组情况下,DGL使用给定ID张量的数据类型。
在序列格式的元组情况下,DGL 使用 int64。
Once the graph has been created, you can change the data type by using
dgl.DGLGraph.long()
ordgl.DGLGraph.int()
.If the specified
idtype
argument differs from the data type of the provided tensors, it casts the given tensors to the specified data type first.The most efficient construction approach is to provide a tuple of node tensors without specifying
idtype
anddevice
. This is because the returned graph shares the storage with the input node-tensors in this case.DGL 内部维护了多个不同稀疏格式的图结构副本,并根据调用的计算选择最有效的格式。如果在大图情况下内存使用成为问题,可以使用
dgl.DGLGraph.formats()
来限制允许的格式。
示例
以下示例使用PyTorch后端。
>>> import dgl >>> import torch
创建一个小的三边图。
>>> # Source nodes for edges (2, 1), (3, 2), (4, 3) >>> src_ids = torch.tensor([2, 3, 4]) >>> # Destination nodes for edges (2, 1), (3, 2), (4, 3) >>> dst_ids = torch.tensor([1, 2, 3]) >>> g = dgl.graph((src_ids, dst_ids))
明确指定图中的节点数量。
>>> g = dgl.graph((src_ids, dst_ids), num_nodes=100)
在第一个GPU上创建一个数据类型为int32的图形。
>>> g = dgl.graph((src_ids, dst_ids), idtype=torch.int32, device='cuda:0')
使用CSR表示法创建图:
>>> g = dgl.graph(('csr', ([0, 0, 0, 1, 2, 3], [1, 2, 3], [])))
使用CSR表示和边ID创建相同的图。
>>> g = dgl.graph(('csr', ([0, 0, 0, 1, 2, 3], [1, 2, 3], [0, 1, 2])))
另请参阅