问题
I want to calculate the clustering coefficient of each node in the graph using python and Networkx functions. I know there might be a built-in function for this purpose but I want to calculate it by myself but my code is not working. Can someone please point out error?
I have tried to test and debug the code. No. of neighbors of each node i.e. n_neighbors are calculated seem to be ok but next code is somehow not running or have some error in it which I'm unable to detect.
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
for node in network.nodes():
neighbours=nx.neighbors(network,node)
count=0
for n in neighbours:
count+=1
n_neighbors=count
n_links=0
if n_neighbors>1:
for node1 in neighbours:
for node2 in neighbours:
if nx.has_edge(node1,node2):
n_links+=1
n_links/+2 #because n_links is calculated twice
clustering_coefficient=n_links/(0.5*n_neighbors*(n_neighbors-1))
print(clustering_coefficient)
else:
print(0)
回答1:
You should note that neighbors is an iterator. This means that after the first iteration you no longer have items to iterate over them. When entering the line for node1 in neighbors:
neighbors is empty and you never reach the inside of the loop. Refer to documentation of the function here
Additionally, note that n_links/+2
doesn't change the value of n_links. It should be n_links/=2
.
nx.has_edge(node1,node2)
should work on a graph.
Regarding the logic - you should move the line where you divide by 2. You should calculate it after you finished calculating all the connections between the neighbors, or just add 0.5 each time you find an edge.
After changing these things you get:
for node in network.nodes():
neighbours=[n for n in nx.neighbors(network,node)]
n_neighbors=len(neighbours)
n_links=0
if n_neighbors>1:
for node1 in neighbours:
for node2 in neighbours:
if network.has_edge(node1,node2):
n_links+=1
n_links/=2 #because n_links is calculated twice
clustering_coefficient=n_links/(0.5*n_neighbors*(n_neighbors-1))
print(clustering_coefficient)
else:
print(0)
来源:https://stackoverflow.com/questions/58044012/how-to-calculate-clustering-coefficient-of-each-node-in-the-graph-in-python-usin