Search code examples
python-2.7numpymatrixsparse-matrix

transform symmetric matrix to sparse matrix


I have a numpy symmetric square matrix that i want to turn into a sparse one, so far I have realized the following solution, for simplification purposes I have constructed a matrix using the following command:

import numpy as np
adjacency_matrix = np.full((10, 10), 20.0)

and then processed to turn it into a sparse one like the following:

nbr_lines, nbr_columns = adjacency_matrix.shape
for i in xrange(height):
   for j in xrange(i+1):
       adjacency_matrix[i, j] = 0
adjacency_matrix = sparse.csr_matrix(adjacency_matrix)

is this the best way to do such a transformation?


Solution

  • Method #1

    You can create the sparse matrix in one go upon getting all those upper triangular indices with np.triu_indices, like so -

    r,c = np.triu_indices(height,1)
    out = sparse.csr_matrix((adjacency_matrix[r,c], (r,c)))
    

    Method #2

    Alternatively, we could reset those lower triangular elements (just like you were doing, but in a vectorized manner with masking), like so -

    m = np.arange(height)
    adjacency_matrix[m[:,None] >= m] = 0
    

    Then, create the sparse matrix with sparse.csr_matrix(adjacency_matrix).

    The advantage is that we are avoiding the creation of all row, col upper triangular indices, which could be the bottleneck with large arrays.