如何使用Networkx在Python中计算图中每个节点的聚类系数 [英] How to calculate clustering coefficient of each node in the graph in Python using Networkx

查看:793
本文介绍了如何使用Networkx在Python中计算图中每个节点的聚类系数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用python和Networkx函数计算图中每个节点的聚类系数.我知道可能为此目的有一个内置函数,但是我想自己计算,但是我的代码无法正常工作.有人可以指出错误吗?

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?

我尝试测试和调试代码.每个节点的邻居数,即计算n_neighbors似乎还可以,但是下一个代码不知何故没有运行或出现了一些我无法检测到的错误.

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)

推荐答案

您应注意,邻居是一个迭代器.这意味着在第一次迭代之后,您将不再有要迭代的项目.在邻居中为node1输入行时:邻居为空,您永远也不会到达循环的内部.请参阅功能文档此处

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

此外,请注意, n_links/+ 2 不会更改n_links的值.它应该是 n_links/= 2 .

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)应该适用于图.

关于逻辑-您应该将线除以2.您应该在计算完邻居之间的所有连接之后进行计算,或者在每次找到边时加0.5.

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)

这篇关于如何使用Networkx在Python中计算图中每个节点的聚类系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆