Much of the time we're working with graphs with sparse adjacency matrices, so networkx returns a SciPy Compressed Sparse Row matrix rather than a numpy.ndarray
or numpy.matrix
. The former representation uses more efficient data structures and algorithms for representing and processing sparse matrices. In particular the __repr__
representation of the matrix differs from that of a vanilla (dense) NumPy matrix. It will look something like
<11x11 sparse matrix of type '<class 'numpy.int64'>'
with 28 stored elements in Compressed Sparse Row format>
This makes sense because if the representation of a CSR matrix were the same as what we see with a dense matrix, a simple print statement or logging message could have serious performance impacts if the matrix were very large.
Compare the above output with the __repr__
output of a vanilla (dense) NumPy matrix:
matrix([[0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1],
[0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0]])
which allows us to inspect the matrix elements visually (I am guessing that this is what was meant with "visualize the adj_matrix").
To convert a sparse CSR matrix to a dense NumPy matrix, simply do sparse_matrix.todense()
. Note that this representation of a sparse matrix will require substantially more memory, so be mindful of that when working with larger graphs.