pytorchdgl

How to evaluate a pyTorch/DGL tensor


From a DGL graph I want to see the adjacency matrix with

adjM = g.adjacency_matrix()
adjM

and I get the following which is fine:

tensor(indices=tensor([[0, 0, 0, 1],
                       [1, 2, 3, 3]]),
       values=tensor([1., 1., 1., 1.]),
       size=(4, 4), nnz=4, layout=torch.sparse_coo)

Now I want to have the adjacency matrix and the node values each by itself. I imagine something of this kind:

adjMatrix = adjM.indices   # or
adjMatrix = adjM[0]
nodeValues = adjM.values   # or
nodeValues = adjM[1]

But this form is not estimated by pyTorch/DGL. My beginner's question:


Solution

  • Click here! You will find the usage of dgl.adj(). As the doc said, the return is an adjacency matrix, and the return type is the SparseTensor.

    I noticed that the output that you post is a SparseTensor.

    You can try it as follows then you can get the entire adj_matrix

    I create a dgl graph g, get the adjacency matrix as adj

    g = dgl.graph(([0, 1, 2], [1, 2, 3]))
    adj = g.adj()
    adj
    

    output is:

    tensor(indices=tensor([[0, 1, 2],
                           [1, 2, 3]]),
           values=tensor([1., 1., 1.]),
           size=(4, 4), nnz=3, layout=torch.sparse_coo)
    

    We can find that adj is the presence of sparse, and the sparse type is coo, we can use the following code to verify if adj is a SparseTensor

    adj.is_sparse
    

    output :

    True
    

    so we can use to_dense() get the original adj matrix

    adj.to_dense()
    

    the result is:

    tensor([[0., 1., 0., 0.],
            [0., 0., 1., 0.],
            [0., 0., 0., 1.],
            [0., 0., 0., 0.]])
    

    When you have a problem with DGL you can check the Deep Graph Library Tutorials and Documentation.