rozyang
rozyang

Reputation: 619

How to get sparse graph Laplacian matrix in python?

I have a sparse matrix A in csr_matrix format. A is the weighted adjacency matrix of an undirected graph and thus symmetric and nonnegative. I want to calculate its graph Lapalican.

I used to work with MATLAB, where the code is pretty simple:

L = diag(sum(A,2)) - A   % or L=diag(sum(A))-A because A is symmetric

But how can we do it in Python? I am new to sparse matrices in Python. I can only come up with a quite ugly solution:

import numpy as np
import scipy.sparse as sps
L = sps.diags(np.reshape(np.array(A.sum(axis=1)), A.shape[0])) - A

Does anyone know a more elegant solution?

Upvotes: 2

Views: 2755

Answers (1)

Johannes Wachs
Johannes Wachs

Reputation: 1310

This is how the networkX library does it for a sparse matrix A - very similar to your method with small improvements (keeping everything sparse):

n,m = A.shape
diags = A.sum(axis=1)
D = sps.spdiags(diags.flatten(), [0], m, n, format='csr')
D - A

Upvotes: 2

Related Questions