社区发现算法——KL算法

2023-11-23 02:31
文章标签 算法 发现 社区 kl

本文主要是介绍社区发现算法——KL算法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

K-L(Kernighan-Lin)算法

原始论文(An efficient heuristic procedure for partitioning graphs)

K-L(Kernighan-Lin)算法是一种将已知网络划分为已知大小的两个社区的二分方法,它是一种贪婪算法。

它的主要思想是为网络划分定义了一个函数增益Q

Q表示的是社区内部的边数与社区之间的边数之差

根据这个方法找出使增益函数Q的值成为最大值的划分社区的方法。

具体策略是,将社区结构中的结点移动到其他的社区结构中或者交换不同社区结构中的结点。从初始解开始搜索,直到从当前的解出发找不到更优的候选解,然后停止。

首先将整个网络的节点随机的或根据网络的现有信息分为两个部分,在两个社团之间考虑所有可能的节点对,试探交换每对节点并计算交换前后的ΔQ,ΔQ=Q交换后-Q交换前,记录ΔQ最大的交换节点对,并将这两个节点互换,记录此时的Q值。
规定每个节点只能交换一次,重复这个过程直至网络中的所有节点都被交换一次为止。需要注意的是不能在Q值发生下降时就停止,因为Q值不是单调增加的,既使某一步交换会使Q值有所下降,但其后的一步交换可能会出现一个更大的Q值。在所有的节点都交换过之后,对应Q值最大的社团结构即被认为是该网络的理想社团结构。

K-L算法的缺陷是必须先指定了两个子图的大小,不然不会得到正确的结果,实际应用意义不大。

Python代码如下:

import networkx as nx
import matplotlib.pyplot as plt
from networkx.algorithms.community import kernighan_lin_bisectiondef draw_spring(G, com):"""G:图com:划分好的社区node_size表示节点大小node_color表示节点颜色node_shape表示节点形状with_labels=True表示节点是否带标签"""pos = nx.spring_layout(G)  # 节点的布局为spring型NodeId = list(G.nodes())node_size = [G.degree(i) ** 1.2 * 90 for i in NodeId]  # 节点大小plt.figure(figsize=(8, 6))  # 图片大小nx.draw(G, pos, with_labels=True, node_size=node_size, node_color='w', node_shape='.')color_list = ['pink', 'orange', 'r', 'g', 'b', 'y', 'm', 'gray', 'black', 'c', 'brown']# node_shape = ['s','o','H','D']for i in range(len(com)):nx.draw_networkx_nodes(G, pos, nodelist=com[i], node_color=color_list[i])plt.show()if __name__ == "__main__":G = nx.karate_club_graph()  # 空手道俱乐部# KL算法com = list(kernighan_lin_bisection(G))print('社区数量', len(com))print(com)draw_spring(G, com)

这里直接使用了networkx库中的kl算法,数据集Zachary karate club网络是通过对一个美国大学空手道俱乐部进行观测而构建出的一个社会网络.网络包含 34 个节点和 78 条边,其中个体表示俱乐部中的成员,而边表示成员之间存在的友谊关系.空手道俱乐部网络已经成为复杂网络社区结构探测中的一个经典问题。

经过一次kl算法划分为如图两个部分。
在这里插入图片描述

社区划分相关的代码与数据集放在github,可以自行下载。

具体的kl算法如下,是networkx库中的算法,可以参考下:

"""Functions for computing the Kernighan–Lin bipartition algorithm."""import networkx as nx
from itertools import count
from networkx.utils import not_implemented_for, py_random_state, BinaryHeap
from networkx.algorithms.community.community_utils import is_partition__all__ = ["kernighan_lin_bisection"]def _kernighan_lin_sweep(edges, side):"""This is a modified form of Kernighan-Lin, which moves single nodes at atime, alternating between sides to keep the bisection balanced.  We keeptwo min-heaps of swap costs to make optimal-next-move selection fast."""costs0, costs1 = costs = BinaryHeap(), BinaryHeap()for u, side_u, edges_u in zip(count(), side, edges):cost_u = sum(w if side[v] else -w for v, w in edges_u)costs[side_u].insert(u, cost_u if side_u else -cost_u)def _update_costs(costs_x, x):for y, w in edges[x]:costs_y = costs[side[y]]cost_y = costs_y.get(y)if cost_y is not None:cost_y += 2 * (-w if costs_x is costs_y else w)costs_y.insert(y, cost_y, True)i = totcost = 0while costs0 and costs1:u, cost_u = costs0.pop()_update_costs(costs0, u)v, cost_v = costs1.pop()_update_costs(costs1, v)totcost += cost_u + cost_vyield totcost, i, (u, v)@py_random_state(4)
@not_implemented_for("directed")
def kernighan_lin_bisection(G, partition=None, max_iter=10, weight="weight", seed=None):"""Partition a graph into two blocks using the Kernighan–Linalgorithm.This algorithm partitions a network into two sets by iterativelyswapping pairs of nodes to reduce the edge cut between the two sets.  Thepairs are chosen according to a modified form of Kernighan-Lin, whichmoves node individually, alternating between sides to keep the bisectionbalanced.Parameters----------G : graphpartition : tuplePair of iterables containing an initial partition. If notspecified, a random balanced partition is used.max_iter : intMaximum number of times to attempt swaps to find animprovemement before giving up.weight : keyEdge data key to use as weight. If None, the weights are allset to one.seed : integer, random_state, or None (default)Indicator of random number generation state.See :ref:`Randomness<randomness>`.Only used if partition is NoneReturns-------partition : tupleA pair of sets of nodes representing the bipartition.Raises-------NetworkXErrorIf partition is not a valid partition of the nodes of the graph.References----------.. [1] Kernighan, B. W.; Lin, Shen (1970)."An efficient heuristic procedure for partitioning graphs."*Bell Systems Technical Journal* 49: 291--307.Oxford University Press 2011."""n = len(G)labels = list(G)seed.shuffle(labels)index = {v: i for i, v in enumerate(labels)}if partition is None:side = [0] * (n // 2) + [1] * ((n + 1) // 2)else:try:A, B = partitionexcept (TypeError, ValueError) as e:raise nx.NetworkXError("partition must be two sets") from eif not is_partition(G, (A, B)):raise nx.NetworkXError("partition invalid")side = [0] * nfor a in A:side[a] = 1if G.is_multigraph():edges = [[(index[u], sum(e.get(weight, 1) for e in d.values()))for u, d in G[v].items()]for v in labels]else:edges = [[(index[u], e.get(weight, 1)) for u, e in G[v].items()] for v in labels]for i in range(max_iter):costs = list(_kernighan_lin_sweep(edges, side))min_cost, min_i, _ = min(costs)if min_cost >= 0:breakfor _, _, (u, v) in costs[: min_i + 1]:side[u] = 1side[v] = 0A = {u for u, s in zip(labels, side) if s == 0}B = {u for u, s in zip(labels, side) if s == 1}return A, B

这篇关于社区发现算法——KL算法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/414709

相关文章

openCV中KNN算法的实现

《openCV中KNN算法的实现》KNN算法是一种简单且常用的分类算法,本文主要介绍了openCV中KNN算法的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录KNN算法流程使用OpenCV实现KNNOpenCV 是一个开源的跨平台计算机视觉库,它提供了各

springboot+dubbo实现时间轮算法

《springboot+dubbo实现时间轮算法》时间轮是一种高效利用线程资源进行批量化调度的算法,本文主要介绍了springboot+dubbo实现时间轮算法,文中通过示例代码介绍的非常详细,对大家... 目录前言一、参数说明二、具体实现1、HashedwheelTimer2、createWheel3、n

SpringBoot实现MD5加盐算法的示例代码

《SpringBoot实现MD5加盐算法的示例代码》加盐算法是一种用于增强密码安全性的技术,本文主要介绍了SpringBoot实现MD5加盐算法的示例代码,文中通过示例代码介绍的非常详细,对大家的学习... 目录一、什么是加盐算法二、如何实现加盐算法2.1 加盐算法代码实现2.2 注册页面中进行密码加盐2.

Java时间轮调度算法的代码实现

《Java时间轮调度算法的代码实现》时间轮是一种高效的定时调度算法,主要用于管理延时任务或周期性任务,它通过一个环形数组(时间轮)和指针来实现,将大量定时任务分摊到固定的时间槽中,极大地降低了时间复杂... 目录1、简述2、时间轮的原理3. 时间轮的实现步骤3.1 定义时间槽3.2 定义时间轮3.3 使用时

SpringCloud之consul服务注册与发现、配置管理、配置持久化方式

《SpringCloud之consul服务注册与发现、配置管理、配置持久化方式》:本文主要介绍SpringCloud之consul服务注册与发现、配置管理、配置持久化方式,具有很好的参考价值,希望... 目录前言一、consul是什么?二、安装运行consul三、使用1、服务发现2、配置管理四、数据持久化总

如何通过Golang的container/list实现LRU缓存算法

《如何通过Golang的container/list实现LRU缓存算法》文章介绍了Go语言中container/list包实现的双向链表,并探讨了如何使用链表实现LRU缓存,LRU缓存通过维护一个双向... 目录力扣:146. LRU 缓存主要结构 List 和 Element常用方法1. 初始化链表2.

golang字符串匹配算法解读

《golang字符串匹配算法解读》文章介绍了字符串匹配算法的原理,特别是Knuth-Morris-Pratt(KMP)算法,该算法通过构建模式串的前缀表来减少匹配时的不必要的字符比较,从而提高效率,在... 目录简介KMP实现代码总结简介字符串匹配算法主要用于在一个较长的文本串中查找一个较短的字符串(称为

通俗易懂的Java常见限流算法具体实现

《通俗易懂的Java常见限流算法具体实现》:本文主要介绍Java常见限流算法具体实现的相关资料,包括漏桶算法、令牌桶算法、Nginx限流和Redis+Lua限流的实现原理和具体步骤,并比较了它们的... 目录一、漏桶算法1.漏桶算法的思想和原理2.具体实现二、令牌桶算法1.令牌桶算法流程:2.具体实现2.1

Python中的随机森林算法与实战

《Python中的随机森林算法与实战》本文详细介绍了随机森林算法,包括其原理、实现步骤、分类和回归案例,并讨论了其优点和缺点,通过面向对象编程实现了一个简单的随机森林模型,并应用于鸢尾花分类和波士顿房... 目录1、随机森林算法概述2、随机森林的原理3、实现步骤4、分类案例:使用随机森林预测鸢尾花品种4.1

不懂推荐算法也能设计推荐系统

本文以商业化应用推荐为例,告诉我们不懂推荐算法的产品,也能从产品侧出发, 设计出一款不错的推荐系统。 相信很多新手产品,看到算法二字,多是懵圈的。 什么排序算法、最短路径等都是相对传统的算法(注:传统是指科班出身的产品都会接触过)。但对于推荐算法,多数产品对着网上搜到的资源,都会无从下手。特别当某些推荐算法 和 “AI”扯上关系后,更是加大了理解的难度。 但,不了解推荐算法,就无法做推荐系