[英]Networkx - entropy of subgraphs generated from detected communities
我有 4 個函數用於復雜網絡分析中的一些統計計算。
import networkx as nx
import numpy as np
import math
from astropy.io import fits
圖的度數分布:
def degree_distribution(G):
vk = dict(G.degree())
vk = list(vk.values()) # we get only the degree values
maxk = np.max(vk)
mink = np.min(min)
kvalues= np.arange(0,maxk+1) # possible values of k
Pk = np.zeros(maxk+1) # P(k)
for k in vk:
Pk[k] = Pk[k] + 1
Pk = Pk/sum(Pk) # the sum of the elements of P(k) must to be equal to one
return kvalues,Pk
圖的社區檢測:
def calculate_community_modularity(graph):
communities = greedy_modularity_communities(graph) # algorithm
modularity_dict = {} # Create a blank dictionary
for i,c in enumerate(communities): # Loop through the list of communities, keeping track of the number for the community
for name in c: # Loop through each neuron in a community
modularity_dict[name] = i # Create an entry in the dictionary for the neuron, where the value is which group they belong to.
nx.set_node_attributes(graph, modularity_dict, 'modularity')
print (graph_name)
for i,c in enumerate(communities): # Loop through the list of communities
#if len(c) > 2: # Filter out modularity classes with 2 or fewer nodes
print('Class '+str(i)+':', len(c)) # Print out the classes and their member numbers
return modularity_dict
圖的模塊化分數:
def modularity_score(graph):
return nx_comm.modularity(graph, nx_comm.label_propagation_communities(graph))
最后是圖熵:
def shannon_entropy(G):
k,Pk = degree_distribution(G)
H = 0
for p in Pk:
if(p > 0):
H = H - p*math.log(p, 2)
return H
問題
我現在想要實現的是找到每個社區的局部熵(變成一個子圖),並保留邊緣信息。
這可能嗎? 怎么會這樣?
編輯:
正在使用的矩陣在此鏈接中:
with fits.open('mind_dataset/matrix_CEREBELLUM_large.fits') as data:
matrix = pd.DataFrame(data[0].data.byteswap().newbyteorder())
然后將鄰接矩陣變成一個圖,“圖”或“G”,如下所示:
def matrix_to_graph(matrix):
from_matrix = matrix.copy()
to_numpy = from_matrix.to_numpy()
G = nx.from_numpy_matrix(to_numpy)
return G
編輯 2 :
根據下面提出的答案,我創建了另一個 function:
def community_entropy(modularity_dict):
communities = {}
#create communities as lists of nodes
for node, community in modularity_dict.items():
if community not in communities.keys():
communities[community] = [node]
else:
communities[community].append(node)
print(communities)
#transform lists of nodes to actual subgraphs
for subgraph, community in communities.items():
communities[community] = nx.Graph.subgraph(subgraph)
local_entropy = {}
for subgraph, community in communities.items():
local_entropy[community] = shannon_entropy(subgraph)
return local_entropy
和:
cerebellum_graph = matrix_to_graph(matrix)
modularity_dict_cereb = calculate_community_modularity(cerebellum_graph)
community_entropy_cereb = community_entropy(modularity_dict_cereb)
但它會拋出錯誤:
TypeError: subgraph() missing 1 required positional argument: 'nodes'
有什么幫助嗎?
看起來,在calculate_community_modularity
中,您使用greedy_modularity_communities
創建了一個字典, modularity_dict
,它將您圖中的一個節點映射到一個community
。 如果我理解正確,您可以將shannon_entropy
modularity_dict
計算該社區的熵。
這是偽代碼,所以可能會有一些錯誤。 不過,這應該傳達原則。
運行calculate_community_modularity
后,你有一個這樣的字典,其中鍵是每個節點,值是社區所屬的
modularity_dict = {node_1: community_1, node_2: community_1, node_3: community_2}
我從未使用過nx
,但看起來您可以根據節點列表提取子圖。 因此,您將遍歷您的 dict,並為每個社區創建一個節點列表。 然后您將使用該節點列表來提取該社區的實際nx
子圖。
communities = {}
#create communities as lists of nodes
for node, community in modularity_dict.iteritems():
if community not in communities.keys():
communities[community] = [node]
else:
communities[community].append(node)
#transform lists of nodes to actual subgraphs
for subgraph, community in communities.iteritems():
communities[community] = networkx.Graph.subgraph(subgraph)
既然communities
是一個帶有社區 id 鍵的字典,以及定義該社區的nx
子圖的值,您應該能夠通過shannon_entropy
運行這些子圖,因為子圖的類型與您的類型相同原始圖
local_entropy = {}
for subgraph, community in communities.iteritems():
local_entropy[community] = shannon_entropy(subgraph)
使用我在此處提供的代碼作為您的問題的答案,從社區創建圖表。 您可以首先為每個社區創建不同的圖表(基於圖表的社區邊緣屬性)。 然后,您可以使用您的shannon_entropy
和degree_distribution
function 計算每個社區的熵。
根據您在上面提到的其他問題中提供的空手道俱樂部示例,請參閱下面的代碼:
import networkx as nx
import networkx.algorithms.community as nx_comm
import matplotlib.pyplot as plt
import numpy as np
import math
def degree_distribution(G):
vk = dict(G.degree())
vk = list(vk.values()) # we get only the degree values
maxk = np.max(vk)
mink = np.min(min)
kvalues= np.arange(0,maxk+1) # possible values of k
Pk = np.zeros(maxk+1) # P(k)
for k in vk:
Pk[k] = Pk[k] + 1
Pk = Pk/sum(Pk) # the sum of the elements of P(k) must to be equal to one
return kvalues,Pk
def shannon_entropy(G):
k,Pk = degree_distribution(G)
H = 0
for p in Pk:
if(p > 0):
H = H - p*math.log(p, 2)
return H
G = nx.karate_club_graph()
# Find the communities
communities = sorted(nx_comm.greedy_modularity_communities(G), key=len, reverse=True)
# Count the communities
print(f"The club has {len(communities)} communities.")
'''Add community to node attributes'''
for c, v_c in enumerate(communities):
for v in v_c:
# Add 1 to save 0 for external edges
G.nodes[v]['community'] = c + 1
'''Find internal edges and add their community to their attributes'''
for v, w, in G.edges:
if G.nodes[v]['community'] == G.nodes[w]['community']:
# Internal edge, mark with community
G.edges[v, w]['community'] = G.nodes[v]['community']
else:
# External edge, mark as 0
G.edges[v, w]['community'] = 0
N_coms=len(communities)
edges_coms=[]#edge list for each community
coms_G=[nx.Graph() for _ in range(N_coms)] #community graphs
colors=['tab:blue','tab:orange','tab:green']
fig=plt.figure(figsize=(12,5))
for i in range(N_coms):
edges_coms.append([(u,v,d) for u,v,d in G.edges(data=True) if d['community'] == i+1])#identify edges of interest using the edge attribute
coms_G[i].add_edges_from(edges_coms[i]) #add edges
ent_coms=[shannon_entropy(coms_G[i]) for i in range(N_coms)] #Compute entropy
for i in range(N_coms):
plt.subplot(1,3,i+1)#plot communities
plt.title('Community '+str(i+1)+ ', entropy: '+str(np.round(ent_coms[i],1)))
pos=nx.circular_layout(coms_G[i])
nx.draw(coms_G[i],pos=pos,with_labels=True,node_color=colors[i])
output 給出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.