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:
JavaScript
x
15
15
1
import tensorflow as tf
2
import numpy as np
3
from spektral.datasets import citation
4
5
cora_dataset = spektral.datasets.citation.Citation(name='cora')
6
test_mask = cora_dataset.mask_te
7
train_mask = cora_dataset.mask_tr
8
val_mask = cora_dataset.mask_va
9
graph = cora_dataset.graphs[0]
10
features = graph.x
11
adj = graph.a
12
labels = graph.y
13
14
features = features.todense()
15
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.
Advertisement
Answer
You can use tf.sparse.to_dense to convert sparse matrix to dense matrix.
Here is the example:
JavaScript
1
35
35
1
indices = [
2
[0, 1],
3
[0, 2],
4
[0, 4],
5
[1, 0],
6
[1, 2],
7
[1, 3],
8
[1, 5],
9
[2, 0],
10
[2, 1],
11
[2, 3],
12
[2, 4],
13
[3, 1],
14
[3, 2],
15
[3, 7],
16
[4, 0],
17
[4, 2],
18
[4, 5],
19
[4, 6],
20
[5, 1],
21
[5, 4],
22
[5, 6],
23
[6, 4],
24
[6, 5],
25
[6, 7],
26
[7, 3],
27
[7, 6]]
28
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.]
29
dense_shape = [8,8]
30
adjacency_matrix = tf.sparse.SparseTensor(
31
indices, values, dense_shape
32
)
33
dense_matrix = tf.sparse.to_dense(adjacency_matrix)
34
35
I hope that helps.