社区发现算法——KL算法

news/2024/10/21 9:30:32/

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

http://www.ppmy.cn/news/414662.html

相关文章

MPEG2和MPEG4视频编码的比较

1 MPEG-2技术 MPEG-2的初衷是为广播级电视质量&#xff08;CCIR601格式&#xff09;的视音频信号定义的压缩编码标准&#xff0c;但最终结果是成为了一个通用的标准&#xff0c;能在很大范围内对不同分辨率和不同输出比特率的图像信号进行有效编码。 MPEG-2的编码技术主要基于…

KL25嵌入式实验考核

KL25嵌入式实验考核&#xff08; 6/43 &#xff09; 404 页面找不到 说明资源在审核中... 1. 利用 KL25 小板实现:控制红色 LED 灯每隔 2 秒钟亮暗变换的同时 在 PC 机上显示 MCU 的计时时间&#xff0c;MCU 的初始时间由 PC 设置。/ 百度云备用&#xff1a;密码ub5t 2. 利…

Kullback-Leibler(KL)散度介绍

在这篇文章中&#xff0c;我们将探讨一种比较两个概率分布的方法&#xff0c;称为Kullback-Leibler散度(通常简称为KL散度)。通常在概率和统计中&#xff0c;我们会用更简单的近似分布来代替观察到的数据或复杂的分布。KL散度帮助我们衡量在选择近似值时损失了多少信息。 让我们…

关于PCA主成分分析与KL变换

最近看了PCA主成分分析,其中KL变化是其中的一种方法 具体的原理我转载了以下文章 http://blog.csdn.net/kingskyleader/article/details/7734710 先贴一记代码 clear all; close all; N=500; for i=1:Nx1(1,i)=-2+0.8*randn(1);x1(2,i)=-1+0.9*randn(1);x1(3,i)= 2+0.7*ran…

版图设计心得

过去的一周&#xff0c;经过没日没夜的layout&#xff0c;感觉自己确实成为了一名已经入门的layout machine。在这里总结一下layout的心得 版图设计的概念 版图设计的目的是把设计好的电路的原理图变成可以生产在硅片上的实际电路。最后经过版图提取形成gds文件格式&#xff…

电路期末考试复习提纲(考点知识点概览)

笔者博客另有数据结构 期末考试等复习提纲及知识点集萃 【陆续更新大学生期末考试各科复习要点】 电路期末考试复习提纲&#xff08;考点知识点概览&#xff09; 一、前言二、各章节考点1.第一章 电路的基本概念与基本定律2.第二章 电路分析的基本方法3.第三章 交流稳态电路分析…

华为服务器u盘安装win系统,华为电脑u盘重装系统win10教程

目前华为的品牌做得响亮&#xff0c;华为的电脑自然也有一定的销量。最近小编身边的朋友有问道华为电脑如何通过u盘重装win10系统&#xff0c;于是小编我就整理了一篇华为电脑u盘重装系统win10教程&#xff0c;希望这篇教程能帮助有需要重装win10系统的人。话不多说&#xff0c…

KL Divergence(KL 散度)

KLDivergence 理解 在数理统计( mathematical statistics )中&#xff0c; Kullback–Leibler divergence 使用来衡量一个概率分布和预期的概率分布偏离的程度。在信息系统( information system )中我们称其为相对熵( relative entropy ) 从概率分布 Q 到概率分布P的散度( d…