ENH : about scipy.sparse.csgraph.laplacian
See original GitHub issueIn this issue and associated PR it is said that the function scipy.sparse.csgraph.laplacian
with normalization is the symmetric normalized laplacian L_sym = D^-1/2 L D^-1/2
, where D
is the degree matrix, L
is the unnormalized lapalcian (D - A
, A
being the adjacency matrix).
However, from the toy example below, it doesn’t seem to be the case.While networkx’s output matches with the L_sym
formula’s, scipy’s output is quite different.
It looks like in the source code of scipy’s normalized laplacian there’s some extra processing probably to deal with inversion of possible zeros in the diagonal, but it doesn’t seem to make the result right. Following the formula, I modified the source code a bit and it can produce output mostly consistent with networkx’s (my ver part below), though it definitely needs extra handling to make it robust.
Reproducing code example:
from scipy.sparse import csgraph
import numpy as np
import networkx as nx
graph = np.array([[10, 8, 5], [8, 10, 3], [5, 3, 10]]).astype(np.float32)
print("-------------graph-----------\n", graph)
# scipy
L = csgraph.laplacian(graph, normed=True)
print("\n-------------scipy------------\n", L)
# networkx
L_nx = nx.normalized_laplacian_matrix(nx.from_numpy_array(graph)).todense()
print("\n-------------networkx:-------------\n", L_nx)
# ------------ scipy my ver
A = graph.copy()
w = A.sum(axis=0)
w = np.sqrt(w)
n, m = A.shape
diags = A.sum(axis=1).flatten()
A /= w
A /= w[:, np.newaxis]
I = np.identity(3)
my_lap = I - A
print("\n-----------my ver-------------\n", my_lap)
Output of the code above
-------------graph-----------
[[10. 8. 5.]
[ 8. 10. 3.]
[ 5. 3. 10.]]
-------------scipy------------
[[ 1. -0.6689936 -0.49029034]
[-0.6689936 1. -0.3198011 ]
[-0.49029034 -0.31980106 1. ]]
-------------networkx:-------------
[[ 0.56521739 -0.3640126 -0.24573659]
[-0.3640126 0.52380952 -0.15430335]
[-0.24573659 -0.15430335 0.44444444]]
-----------my ver-------------
[[ 0.56521744 -0.36401257 -0.2457366 ]
[-0.3640126 0.52380958 -0.15430336]
[-0.2457366 -0.15430336 0.44444436]]
Scipy/Numpy/Python version information:
scipy: 1.7.0
numpy: 1.19.1
networkx: 2.5
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (4 by maintainers)
I am able to reproduce your issue on development versions of
scipy
andnetwrokx
with numpy as1.21.1
. IMO, for similar APIs, the results fromscipy
andnetworkx
should match. Though there might be reasons to use a different implementation inscipy
as opposed tonetworkx
.cc @rgommers @fuglede
Thanks, changed.