图形和控制台输出不同。两者应该是一样的。我的错误在哪里?

Graph and console output are different. Both should be the same .Where is my mistake?

根据我的数据集,

Karata_Club 数据集共有 4 个社区。但是当绘制图表时,图表显示了五个不同的社区,两者应该是相同的。

import networkx as nx
import matplotlib.pyplot as plt
import networkx.algorithms.community as nxcom
import community 

G=nx.read_adjlist('D:\Research Folder\Datasets\Karata club\karate.txt')   \You can take any Karate club dataset to check.
    # find the value of K-core
G2 = nx.k_core(G,k=4)
nx.draw(G2 , with_labels=True)
print(G2)
print(G2.nodes()) 
print(G2.edges())
# Find the communities
communities = sorted(nxcom.greedy_modularity_communities(G), key=len, reverse=True)
        # Count the communities
print(f"The Total {len(communities)} communities.")
print(communities)
for node in G: 
    partition = community.best_partition(G)  # compute communities
print(partition)
pos = nx.spring_layout(G)  # compute graph layout
plt.figure(figsize=(9, 9))  # image is 9 x 9 inches
plt.axis('off')
nx.draw_networkx_nodes(G, pos, node_size=600, cmap=plt.cm.RdYlBu, node_color=list(partition.values()))
nx.draw_networkx_edges(G, pos, alpha=0.3)
nx.draw_networkx_labels(G, pos)
plt.show(G)

您在这里使用 networkx 计算社区数量

communities = sorted(nxcom.greedy_modularity_communities(G), key=len,reverse=True)  

它使用 Clauset-Newman-Moore 算法在图中查找社区。

并且在计算 partition(也用于打印图表)时,您正在使用“社区”模块

for node in G: 
    partition = community.best_partition(G)  # compute communities
print(partition)

并且该模块使用 Louvain 启发式算法进行社区检测。

由于两种算法都使用不同的社区检测方法,因此两种算法的结果可能不同,这就是您的情况。