bethehessianmatrix.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """Bethe Hessian or deformed Laplacian matrix of graphs."""
  2. import networkx as nx
  3. from networkx.utils import not_implemented_for
  4. __all__ = ["bethe_hessian_matrix"]
  5. @not_implemented_for("directed")
  6. @not_implemented_for("multigraph")
  7. @nx._dispatchable
  8. def bethe_hessian_matrix(G, r=None, nodelist=None):
  9. r"""Returns the Bethe Hessian matrix of G.
  10. The Bethe Hessian is a family of matrices parametrized by r, defined as
  11. H(r) = (r^2 - 1) I - r A + D where A is the adjacency matrix, D is the
  12. diagonal matrix of node degrees, and I is the identify matrix. It is equal
  13. to the graph laplacian when the regularizer r = 1.
  14. The default choice of regularizer should be the ratio [2]_
  15. .. math::
  16. r_m = \left(\sum k_i \right)^{-1}\left(\sum k_i^2 \right) - 1
  17. Parameters
  18. ----------
  19. G : Graph
  20. A NetworkX graph
  21. r : float
  22. Regularizer parameter
  23. nodelist : list, optional
  24. The rows and columns are ordered according to the nodes in nodelist.
  25. If nodelist is None, then the ordering is produced by ``G.nodes()``.
  26. Returns
  27. -------
  28. H : scipy.sparse.csr_array
  29. The Bethe Hessian matrix of `G`, with parameter `r`.
  30. Examples
  31. --------
  32. >>> k = [3, 2, 2, 1, 0]
  33. >>> G = nx.havel_hakimi_graph(k)
  34. >>> H = nx.bethe_hessian_matrix(G)
  35. >>> H.toarray()
  36. array([[ 3.5625, -1.25 , -1.25 , -1.25 , 0. ],
  37. [-1.25 , 2.5625, -1.25 , 0. , 0. ],
  38. [-1.25 , -1.25 , 2.5625, 0. , 0. ],
  39. [-1.25 , 0. , 0. , 1.5625, 0. ],
  40. [ 0. , 0. , 0. , 0. , 0.5625]])
  41. See Also
  42. --------
  43. bethe_hessian_spectrum
  44. adjacency_matrix
  45. laplacian_matrix
  46. References
  47. ----------
  48. .. [1] A. Saade, F. Krzakala and L. Zdeborová
  49. "Spectral Clustering of Graphs with the Bethe Hessian",
  50. Advances in Neural Information Processing Systems, 2014.
  51. .. [2] C. M. Le, E. Levina
  52. "Estimating the number of communities in networks by spectral methods"
  53. arXiv:1507.00827, 2015.
  54. """
  55. import scipy as sp
  56. if nodelist is None:
  57. nodelist = list(G)
  58. if r is None:
  59. r = sum(d**2 for v, d in nx.degree(G)) / sum(d for v, d in nx.degree(G)) - 1
  60. A = nx.to_scipy_sparse_array(G, nodelist=nodelist, format="csr")
  61. n, m = A.shape
  62. D = sp.sparse.dia_array((A.sum(axis=1), 0), shape=(m, n)).tocsr()
  63. I = sp.sparse.eye_array(m, n, format="csr")
  64. return (r**2 - 1) * I - r * A + D