資源簡介
利用python編寫的GN算法,可發(fā)現(xiàn)網(wǎng)絡(luò)中的社團(tuán),本算法采用模塊化系數(shù)作為評(píng)價(jià)標(biāo)準(zhǔn),具體可以參考博客的有關(guān)內(nèi)容
代碼片段和文件信息
#coding:utf-8
import?networkx?as?nx
import?math
import?csv
import?random?as?rand
import?sys
import?matplotlib.pyplot?as?plt
def?buildG(G?file_?delimiter_):
????reader?=?csv.reader(open(file_)?delimiter=delimiter_)
????for?line?in?reader:
????????G.add_edge(int(line[0])int(line[1]))
def?CmtyStep(G):
????init_number_comp?=?nx.number_connected_components(G)
????number_comp?=?init_number_comp
????while?number_comp?<=?init_number_comp:
????????bw?=?nx.edge_betweenness_centrality(G)#計(jì)算所有邊的邊介數(shù)中心性
????????if?bw.values()?==?[]:
????????????break
????????else:
????????????max_?=?max(bw.values())#將邊介數(shù)中心性最大的值賦給max_
????????for?k?v?in?bw.iteritems():#刪除邊介數(shù)中心性的值最大的邊
????????????if?float(v)?==?max_:
????????????????G.remove_edge(k[0]k[1])
????????number_comp?=?nx.number_connected_components(G)#計(jì)算新的社團(tuán)數(shù)量
def?GetModularity(G?deg_?m_):
????New_A?=?nx.adj_matrix(G)#建立一個(gè)表示邊的鄰接矩陣
????New_deg?=?{}
????New_deg?=?UpdateDeg(New_A?G.nodes())
????#計(jì)算Q值
????comps?=?nx.connected_components(G)#建立一個(gè)組成的列表?
????print?‘Number?of?communities?in?decomposed?G:?%d‘?%?nx.number_connected_components(G)
????Mod?=?0#設(shè)定社團(tuán)劃分的模塊化系數(shù)并設(shè)初始值為0
????for?c?in?comps:
????????AVW?=?0#兩條邊在鄰接矩陣中的值
????????K?=?0#兩條邊的度值
????????for?u?in?c:
????????????AVW?+=?New_deg[u]
????????????K?+=?deg_[u]
????????Mod?+=?(?float(AVW)?-?float(K*K)/float(2*m_)?)#計(jì)算出Q值公式累加符號(hào)后的值
????Mod?=?Mod/float(2*m_)#計(jì)算出模塊化Q值
????return?Mod
def?UpdateDeg(A?nod
評(píng)論
共有 條評(píng)論