k-派系过滤算法,也称为团渗流算法或CPM算法,是一个复杂网络重叠社团检测的经典算法,在2005年由Polla提出。
算法步骤分两步,
第一步:找出所有极大团(大于等于k阶)
第二步:将团视为节点,团与团之间的渗流关系视为边,此网络的连通分支即为k-连通社团。
算法在此处已经讲解的很清晰,也非常感谢小伙伴的分享。小伙伴贴示的Python代码是错的,花了本人不少时间改错。他的代码错误在重叠矩阵使用社团编号还原社团信息的地方,对社团进行编号会被覆盖,且对于两个子图无法合并,会造成某一社团是另一社团子集的错误结果。
算法本质上寻找团渗流图的连通分量,此处代码实现无需构造重叠矩阵,避免了重叠矩阵过大无法构造的问题。时间复杂度为e的n次方。
官方代码在networkxnx.algorithms.community.k_clique_communities()库中。
希望此处分享对后来者有所帮助,共同进步。
在此贴示正确代码:
def k_clique_communities(G, k, cliques=None):
"""
References
----------
.. [1] Gergely Palla, Imre Derényi, Illés Farkas1, and Tamás Vicsek,
Uncovering the overlapping community structure of complex networks
in nature and society Nature 435, 814-818, 2005,
doi:10.1038/nature03607
"""
if k < 2:
raise nx.NetworkXError(f"k={k}, k must be greater than 1.")
if cliques is None:
cliques = nx.find_cliques(G)
cliques = [frozenset(c) for c in cliques if len(c) >= k]
# First index which nodes are in which cliques
membership_dict = defaultdict(list)
for clique in cliques:
for node in clique:
membership_dict[node].append(clique)
# For each clique, see which adjacent cliques percolate
perc_graph = nx.Graph()
perc_graph.add_nodes_from(cliques)
for clique in cliques:
for adj_clique in _get_adjacent_cliques(clique, membership_dict):
if len(clique.intersection(adj_clique)) >= (k - 1):
perc_graph.add_edge(clique, adj_clique)
# Connected components of clique graph with perc edges
# are the percolated cliques
for component in nx.connected_components(perc_graph):
yield (frozenset.union(*component))
def _get_adjacent_cliques(clique, membership_dict):
adjacent_cliques = set()
for n in clique:
for adj_clique in membership_dict[n]:
if clique != adj_clique:
adjacent_cliques.add(adj_clique)
return adjacent_cliques
```python