完整加权网络中的Louvain社区检测仅返回1个分区

时间:2019-05-16 19:50:08

标签: python-3.x graph cluster-analysis networkx

引用:https://stackoverflow.com/a/44907357/305883

我正在使用python-louvain实现来检测完整加权图中的社区。

但是我只能得到一个包含所有节点的分区。

代码:

import community # this is pip install python-louvain
import networkx as nx
import matplotlib.pyplot as plt

# Replace this with your networkx graph loading depending on your format !

# using graph g as a completed graph, weights between 0 and 1

#first compute the best partition
partition = community.best_partition(g)

#drawing
size = float(len(set(partition.values())))
pos = nx.spring_layout(g)
count = 0.
for com in set(partition.values()) :
    count = count + 1.
    list_nodes = [nodes for nodes in partition.keys() if partition[nodes] == com]
    nx.draw_networkx_nodes(g, pos, list_nodes, node_size = 20, node_color = str(count / size))


nx.draw_networkx_edges(g, pos, alpha=0.1)

plt.show()

我想从一个完整的加权网络中提取社区。

我还尝试了girvan_newman(https://networkx.github.io/documentation/networkx-2.0/reference/algorithms/generated/networkx.algorithms.community.centrality.girvan_newman.html),但是在200个节点(包括198个和2个节点)的完整图中只能检测到2个社区。

Louvain是否可以正常工作以检测完整图中的社区? 更好的建议?

2 个答案:

答案 0 :(得分:1)

在这种情况下,使用的模型选择可能返回一个包含所有节点的块,这意味着没有足够的统计证据可用于更多块。

您可以尝试Peixotos graph-tool软件包,该软件包具有weighted stochastic block model的实现。

答案 1 :(得分:0)

如果您拥有加权网络,则需要使用weight='weight'参数:

import networkx as nx
import community
import numpy as np
np.random.seed(0)

W = np.random.rand(15,15)
np.fill_diagonal(W,0.0)

G = nx.from_numpy_array(W)
louvain_partition = community.best_partition(G, weight='weight')
modularity2 = community.modularity(louvain_partition, G, weight='weight')
print("The modularity Q based on networkx is {}".format(modularity2))

基于networkx的模块化Q为0.0849022950503318