Search code examples
pythonnumpytensorflowmatrixgraph-neural-network

Changing graph dataset matrices from sparse format to dense


I am trying to use the CoRA dataset to train a graph neural network on tensorflow for the first time. The features and adjacency matrices provided by the dataset comes in a sparse representation but I don't need it here. Thus, I want to use numpy's todense() but it turns out it doesn't exist. For your reference, here is the relevant code:

import tensorflow as tf
import numpy as np
from spektral.datasets import citation

cora_dataset = spektral.datasets.citation.Citation(name='cora')
test_mask = cora_dataset.mask_te
train_mask = cora_dataset.mask_tr
val_mask = cora_dataset.mask_va
graph = cora_dataset.graphs[0]
features = graph.x
adj = graph.a
labels = graph.y

features = features.todense()

and the error is: "AttributeError: 'numpy.ndarray' object has no attribute 'todense'"

I would like to know if there has been a replacement for todense() or any other ways to convert sparse representations to dense.


Solution

  • You can use tf.sparse.to_dense to convert sparse matrix to dense matrix.

    Here is the example:

    indices = [
     [0, 1],
     [0, 2],
     [0, 4],
     [1, 0],
     [1, 2],
     [1, 3],
     [1, 5],
     [2, 0],
     [2, 1],
     [2, 3],
     [2, 4],
     [3, 1],
     [3, 2],
     [3, 7],
     [4, 0],
     [4, 2],
     [4, 5],
     [4, 6],
     [5, 1],
     [5, 4],
     [5, 6],
     [6, 4],
     [6, 5],
     [6, 7],
     [7, 3],
     [7, 6]]
    values = [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]
    dense_shape = [8,8]
    adjacency_matrix = tf.sparse.SparseTensor(
        indices, values, dense_shape
    )
    dense_matrix = tf.sparse.to_dense(adjacency_matrix)
    
    

    I hope that helps.