Search code examples
pythonjupyter-notebooknetwork-programmingnetworkxnode-centrality

Katz Centrality Error: PowerIterationFailedConvergence 'power iteration failed to converge within 1000 iterations')


I'm getting an error called PowerIterationFailedConvergence: (PowerIterationFailedConvergence(...), 'power iteration failed to converge within 1000 iterations') when trying to calculate Katz centrality for a weighted graph in NetworkX. I've tried to set the max_iter attribute higher up to 100000 but it still fails to converge. Higher than that causes the program to run for forever. I've also tried changing the tol attribute to 1e-03 compared to its default value of 1e-06, but have had no luck. When I remove the weight attribute, the code runs without an error, but doesn't give me the result I want because then the graph is not counted as weighted.

I've added my code below that's causing an error, and it's weird because my calculations for other centralities including eigenvector work perfectly.

Error Code (Katz Centrality):

#katz centrality
katz_centrality = nx.katz_centrality(G, weight = 'weight')

for x in range(5):
  print(katz_centrality[x])

No Error Code (ex. Eigenvector Centrality):

#eigenvector centrality
eigenvector_centrality = nx.eigenvector_centrality(G, weight= 'weight')

for x in range(5):
  print(eigenvector_centrality[x])

This is the code behind G:

G = nx.from_numpy_matrix(network_matrix)

This is network_matrix

[[0. 5. 5. 5. 9. 3. 3. 3. 2. 3. 0. 0. 2. 0. 0. 0.]
 [5. 0. 7. 9. 4. 2. 2. 2. 1. 0. 1. 0. 0. 0. 0. 0.]
 [5. 7. 0. 7. 4. 1. 1. 1. 0. 0. 1. 0. 0. 0. 0. 0.]
 [5. 9. 7. 0. 4. 2. 2. 2. 1. 0. 1. 0. 0. 0. 0. 0.]
 [9. 4. 4. 4. 0. 2. 2. 2. 1. 4. 0. 0. 2. 0. 0. 0.]
 [3. 2. 1. 2. 2. 0. 5. 2. 3. 1. 0. 0. 0. 0. 0. 0.]
 [3. 2. 1. 2. 2. 5. 0. 2. 3. 1. 0. 0. 0. 0. 0. 0.]
 [3. 2. 1. 2. 2. 2. 2. 0. 2. 1. 0. 0. 0. 0. 0. 0.]
 [2. 1. 0. 1. 1. 3. 3. 2. 0. 1. 0. 0. 0. 0. 0. 0.]
 [3. 0. 0. 0. 4. 1. 1. 1. 1. 0. 1. 0. 3. 1. 1. 0.]
 [0. 1. 1. 1. 0. 0. 0. 0. 0. 1. 0. 0. 1. 3. 2. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [2. 0. 0. 0. 2. 0. 0. 0. 0. 3. 1. 0. 0. 1. 1. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 3. 0. 1. 0. 2. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 2. 0. 1. 2. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]

Solution

  • Use the numpy implementation, it uses a different solver.

    katz_centrality = nx.katz_centrality_numpy(G, weight= 'weight')
    

    Make sure you have scipy >= 1.8 installed.