基于LFM的重叠社区发现算法python代码实现

2024-03-06 15:48

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

基于LFM的重叠社区发现算法python代码实现

import random
import networkx as nx
import matplotlib.pyplot as plt
import zipfile
#import urllib.request as urllib
class Community():''' use set operation to optimize calculation '''def __init__(self,G,alpha=1.0):self._G = Gself._alpha = alphaself._nodes = set()self._k_in = 0self._k_out = 0def add_node(self,node):neighbors = set(self._G.neighbors(node))#print("添加令居节点",neighbors , self._nodes,neighbors & self._nodes)node_k_in = len(neighbors & self._nodes)#neighbor和self._nodes公有节点的数目存入node_k_in#print("node_k_in",node_k_in)node_k_out = len(neighbors) - node_k_in#print("node_k_out",node_k_out)self._nodes.add(node)self._k_in += 2*node_k_inself._k_out = self._k_out+node_k_out-node_k_indef remove_node(self,node):neighbors = set(self._G.neighbors(node))community_nodes = self._nodes#print("community_nodes",community_nodes)node_k_in = len(neighbors & community_nodes)node_k_out = len(neighbors) - node_k_inself._nodes.remove(node)self._k_in -= 2*node_k_inself._k_out = self._k_out - node_k_out+node_k_indef cal_add_fitness(self,node):#fitness适应度neighbors = set(self._G.neighbors(node))old_k_in = self._k_inold_k_out = self._k_outvertex_k_in = len(neighbors & self._nodes)#vertex顶点vertex_k_out = len(neighbors) - vertex_k_in new_k_in = old_k_in + 2*vertex_k_innew_k_out = old_k_out + vertex_k_out-vertex_k_innew_fitness = new_k_in/(new_k_in+new_k_out)**self._alpha#幂次old_fitness = old_k_in/(old_k_in+old_k_out)**self._alphareturn new_fitness-old_fitnessdef cal_remove_fitness(self,node):neighbors = set(self._G.neighbors(node))new_k_in = self._k_innew_k_out = self._k_outnode_k_in = len(neighbors & self._nodes)node_k_out = len(neighbors) - node_k_inold_k_in = new_k_in - 2*node_k_inold_k_out = new_k_out - node_k_out + node_k_inold_fitness = old_k_in/(old_k_in+old_k_out)**self._alpha new_fitness = new_k_in/(new_k_in+new_k_out)**self._alphareturn new_fitness-old_fitnessdef recalculate(self):for vid in self._nodes:fitness = self.cal_remove_fitness(vid)if fitness < 0.0:return vidreturn Nonedef get_neighbors(self):neighbors = set()for node in self._nodes:neighbors.update(set(self._G.neighbors(node)) - self._nodes)return neighborsdef get_fitness(self):return float(self._k_in)/((self._k_in+self._k_out) ** self._alpha)class LFM():def __init__(self, G, alpha):self._G = Gself._alpha = alphadef execute(self):communities = []print("嘿嘿",list(self._G.node.keys()))print("---------------------")node_not_include = list(self._G.node.keys())while(len(node_not_include) != 0):c = Community(self._G, self._alpha)#print("self._alpha",self._alpha)#0.9# randomly select a seed nodeseed = random.choice(node_not_include)c.add_node(seed)print("随机选取节点是:",seed)to_be_examined = c.get_neighbors()print("c.get_neighbors()",c.get_neighbors())while(to_be_examined):#largest fitness to be addedm = {}for node in to_be_examined:fitness = c.cal_add_fitness(node)#计算点的适应度》0加入,小于0删除m[node] = fitnessto_be_add = sorted(m.items(),key=lambda x:x[1],reverse = True)[0]#啥意思???#适应度降序排列#stop conditionif(to_be_add[1] < 0.0):breakc.add_node(to_be_add[0])to_be_remove = c.recalculate()while(to_be_remove != None):c.remove_node(to_be_remove)to_be_remove = c.recalculate()to_be_examined = c.get_neighbors()for node in c._nodes:if(node in node_not_include):node_not_include.remove(node)communities.append(c._nodes)return communitiesif(__name__ == "__main__"):#G = nx.karate_club_graph()#一个边集一个点集# G = nx.florentine_families_graph()zf = zipfile.ZipFile('football.zip')  # zipfile objecttxt = zf.read('football.txt').decode()  # read info filegml = zf.read('football.gml').decode()  # read gml data# throw away bogus first line with # from mejn filesgml = gml.split('\n')[1:]G = nx.parse_gml(gml)  # parse gml dataprint(txt)# print degree for each team - number of gamesfor n, d in G.degree():print('%s %d' % (n, d))options = {'node_color': 'red','node_size': 50,'line_color': 'grey','linewidths': 0,'width': 0.1,}nx.draw(G, **options)#networkx.draw(G, with_labels=True)plt.show()algorithm = LFM(G,0.9)communities = algorithm.execute()for c in communities:print (len(c),sorted(c))

社区网络:
初步社区网络结构图
重叠社区划分结果:
社区划分结果

这篇关于基于LFM的重叠社区发现算法python代码实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Python列表去重的4种核心方法与实战指南详解

《Python列表去重的4种核心方法与实战指南详解》在Python开发中,处理列表数据时经常需要去除重复元素,本文将详细介绍4种最实用的列表去重方法,有需要的小伙伴可以根据自己的需要进行选择... 目录方法1:集合(set)去重法(最快速)方法2:顺序遍历法(保持顺序)方法3:副本删除法(原地修改)方法4:

Python运行中频繁出现Restart提示的解决办法

《Python运行中频繁出现Restart提示的解决办法》在编程的世界里,遇到各种奇怪的问题是家常便饭,但是,当你的Python程序在运行过程中频繁出现“Restart”提示时,这可能不仅仅是令人头疼... 目录问题描述代码示例无限循环递归调用内存泄漏解决方案1. 检查代码逻辑无限循环递归调用内存泄漏2.

pytorch自动求梯度autograd的实现

《pytorch自动求梯度autograd的实现》autograd是一个自动微分引擎,它可以自动计算张量的梯度,本文主要介绍了pytorch自动求梯度autograd的实现,具有一定的参考价值,感兴趣... autograd是pytorch构建神经网络的核心。在 PyTorch 中,结合以下代码例子,当你

Python中判断对象是否为空的方法

《Python中判断对象是否为空的方法》在Python开发中,判断对象是否为“空”是高频操作,但看似简单的需求却暗藏玄机,从None到空容器,从零值到自定义对象的“假值”状态,不同场景下的“空”需要精... 目录一、python中的“空”值体系二、精准判定方法对比三、常见误区解析四、进阶处理技巧五、性能优化

使用Python构建一个Hexo博客发布工具

《使用Python构建一个Hexo博客发布工具》虽然Hexo的命令行工具非常强大,但对于日常的博客撰写和发布过程,我总觉得缺少一个直观的图形界面来简化操作,下面我们就来看看如何使用Python构建一个... 目录引言Hexo博客系统简介设计需求技术选择代码实现主框架界面设计核心功能实现1. 发布文章2. 加

SpringBoot集成Milvus实现数据增删改查功能

《SpringBoot集成Milvus实现数据增删改查功能》milvus支持的语言比较多,支持python,Java,Go,node等开发语言,本文主要介绍如何使用Java语言,采用springboo... 目录1、Milvus基本概念2、添加maven依赖3、配置yml文件4、创建MilvusClient

python logging模块详解及其日志定时清理方式

《pythonlogging模块详解及其日志定时清理方式》:本文主要介绍pythonlogging模块详解及其日志定时清理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录python logging模块及日志定时清理1.创建logger对象2.logging.basicCo

JS+HTML实现在线图片水印添加工具

《JS+HTML实现在线图片水印添加工具》在社交媒体和内容创作日益频繁的今天,如何保护原创内容、展示品牌身份成了一个不得不面对的问题,本文将实现一个完全基于HTML+CSS构建的现代化图片水印在线工具... 目录概述功能亮点使用方法技术解析延伸思考运行效果项目源码下载总结概述在社交媒体和内容创作日益频繁的

Python如何自动生成环境依赖包requirements

《Python如何自动生成环境依赖包requirements》:本文主要介绍Python如何自动生成环境依赖包requirements问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录生成当前 python 环境 安装的所有依赖包1、命令2、常见问题只生成当前 项目 的所有依赖包1、

如何将Python彻底卸载的三种方法

《如何将Python彻底卸载的三种方法》通常我们在一些软件的使用上有碰壁,第一反应就是卸载重装,所以有小伙伴就问我Python怎么卸载才能彻底卸载干净,今天这篇文章,小编就来教大家如何彻底卸载Pyth... 目录软件卸载①方法:②方法:③方法:清理相关文件夹软件卸载①方法:首先,在安装python时,下