dgl.DGLGraph.adj

DGLGraph.adj(transpose=False, ctx=device(type='cpu'), scipy_fmt=None, etype=None)

Return the adjacency matrix of edges of the given edge type.

By default, a row of returned adjacency matrix represents the source of an edge and the column represents the destination.

When transpose is True, a row represents the destination and a column represents the source.

Parameters
  • transpose (bool, optional) – A flag to transpose the returned adjacency matrix. (Default: False)

  • ctx (context, optional) – The context of returned adjacency matrix. (Default: cpu)

  • scipy_fmt (str, optional) – If specified, return a scipy sparse matrix in the given format. Otherwise, return a backend dependent sparse tensor. (Default: 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

Adjacency matrix.

Return type

SparseTensor or scipy.sparse.spmatrix

Examples

The following example uses PyTorch backend.

>>> import dgl
>>> import torch

Instantiate a heterogeneous graph.

>>> g = dgl.heterograph({
...     ('user', 'follows', 'user'): ([0, 1], [0, 1]),
...     ('developer', 'develops', 'game'): ([0, 1], [0, 2])
... })

Get a backend dependent sparse tensor. Here we use PyTorch for example.

>>> g.adj(etype='develops')
tensor(indices=tensor([[0, 1],
                       [0, 2]]),
       values=tensor([1., 1.]),
       size=(2, 3), nnz=2, layout=torch.sparse_coo)

Get a scipy coo sparse matrix.

>>> g.adj(scipy_fmt='coo', etype='develops')
<2x3 sparse matrix of type '<class 'numpy.int64'>'
   with 2 stored elements in COOrdinate format>