dgl.DGLGraph.adj_external

DGLGraph.adj_external(transpose=False, ctx=device(type='cpu'), scipy_fmt=None, etype=None)[source]

返回外部格式的邻接矩阵,例如Scipy或后端相关的稀疏张量。

默认情况下,返回的邻接矩阵的一行代表边的源,列代表边的目的地。

当transpose为True时,一行代表目标,一列代表源。

Parameters:
  • transpose (bool, optional) – 一个标志,用于转置返回的邻接矩阵。(默认值:False)

  • ctx (context, optional) – 返回的邻接矩阵的上下文。(默认值:cpu)

  • scipy_fmt (str, 可选) – 如果指定,则返回给定格式的scipy稀疏矩阵。 否则,返回后端依赖的稀疏张量。(默认值:None)

  • etype (str or (str, str, str), optional) –

    The type names of the edges. The allowed type name formats are:

    • (str, str, str) for source node type, edge type and destination node type.

    • or one str edge type name if the name can uniquely identify a triplet format in the graph.

    Can be omitted if the graph has only one type of edges.

Returns:

邻接矩阵。

Return type:

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>