dgl.DGLGraph.adj_external
- DGLGraph.adj_external(transpose=False, ctx=device(type='cpu'), scipy_fmt=None, etype=None)[source]
返回外部格式的邻接矩阵,例如 Scipy 或依赖于后端的稀疏张量。
默认情况下,返回的邻接矩阵的行代表边的源节点,列代表目标节点。
当 transpose 为 True 时,行代表目标节点,列代表源节点。
- 参数:
transpose (bool, 可选) – 一个标志,用于转置返回的邻接矩阵。(默认值:False)
ctx (context, 可选) – 返回的邻接矩阵的上下文(例如,CPU 或 GPU)。(默认值:cpu)
scipy_fmt (str, 可选) – 如果指定,则以给定格式返回 scipy 稀疏矩阵。否则,返回一个依赖于后端的稀疏张量。(默认值:None)
etype (str 或 (str, str, str), 可选) –
边的类型名称。允许的类型名称格式为
(str, str, str)
分别表示源节点类型、边类型和目标节点类型。或一个
str
边类型名称,如果该名称可以唯一标识图中的一个三元组格式。
如果图只有一种边类型,则可以省略。
- 返回:
邻接矩阵。
- 返回类型:
SparseTensor 或 scipy.sparse.spmatrix
示例
以下示例使用 PyTorch 后端。
>>> import dgl >>> import torch
实例化一个异构图。
>>> g = dgl.heterograph({ ... ('user', 'follows', 'user'): ([0, 1], [0, 1]), ... ('developer', 'develops', 'game'): ([0, 1], [0, 2]) ... })
获取依赖于后端的稀疏张量。这里以 PyTorch 为例。
>>> g.adj_external(etype='develops') tensor(indices=tensor([[0, 1], [0, 2]]), values=tensor([1., 1.]), size=(2, 3), nnz=2, layout=torch.sparse_coo)
获取 scipy coo 稀疏矩阵。
>>> g.adj_external(scipy_fmt='coo', etype='develops') <2x3 sparse matrix of type '<class 'numpy.int64'>' with 2 stored elements in COOrdinate format>