1 要安装的包

使用community安装python-louvain即可
pip install python-louvain
pip install networkx

2、描述

  lst1=[ [0, 1, 1, 1, 1, 1, 0, 0],  [0, 0, 1, 0, 1, 0, 0, 0],  [0, 0, 0, 1, 0, 0, 0, 0],  [0, 0, 0, 0, 1, 0, 0, 0],  [0, 0, 0, 0, 0, 1, 0, 0],  [0, 0, 1, 0, 0, 0, 1, 1],  [0, 0, 0, 0, 0, 1, 0, 1],  [0, 0, 0, 0, 0, 1, 1, 0]  ]由邻接矩阵lst1生成如下无向图


再根据louvain算法进行分区得到下图

3、程序

import numpy as np
import community.community_louvain
import networkx as nx
import matplotlib.pyplot as plt
#图类
class Graph_Matrix:"""Adjacency Matrix"""def __init__(self, vertices=[], matrix=[]):""":param vertices:a dict with vertex id and index of matrix , such as {vertex:index}:param matrix: a matrix"""self.matrix = matrixself.edges_dict = {}  # {(tail, head):weight}self.edges_array = []  # (tail, head, weight)self.vertices = verticesself.num_edges = 0# if provide adjacency matrix then create the edges listif len(matrix) > 0:if len(vertices) != len(matrix):raise IndexErrorself.edges = self.getAllEdges()self.num_edges = len(self.edges)# if do not provide a adjacency matrix, but provide the vertices list, build a matrix with 0elif len(vertices) > 0:self.matrix = [[0 for col in range(len(vertices))] for row in range(len(vertices))]self.num_vertices = len(self.matrix)def isOutRange(self, x):try:if x >= self.num_vertices or x <= 0:raise IndexErrorexcept IndexError:print("节点下标出界")def isEmpty(self):if self.num_vertices == 0:self.num_vertices = len(self.matrix)return self.num_vertices == 0def add_vertex(self, key):if key not in self.vertices:self.vertices[key] = len(self.vertices) + 1# add a vertex mean add a row and a column# add a column for every rowfor i in range(self.getVerticesNumbers()):self.matrix[i].append(0)self.num_vertices += 1nRow = [0] * self.num_verticesself.matrix.append(nRow)def getVertex(self, key):passdef add_edges_from_list(self, edges_list):  # edges_list : [(tail, head, weight),()]for i in range(len(edges_list)):self.add_edge(edges_list[i][0], edges_list[i][1], edges_list[i][2], )def add_edge(self, tail, head, cost=0):# if self.vertices.index(tail) >= 0:#   self.addVertex(tail)if tail not in self.vertices:self.add_vertex(tail)# if self.vertices.index(head) >= 0:#   self.addVertex(head)if head not in self.vertices:self.add_vertex(head)# for directory matrixself.matrix[self.vertices.index(tail)][self.vertices.index(head)] = cost# for non-directory matrix# self.matrix[self.vertices.index(fromV)][self.vertices.index(toV)] = \#   self.matrix[self.vertices.index(toV)][self.vertices.index(fromV)] = costself.edges_dict[(tail, head)] = costself.edges_array.append((tail, head, cost))self.num_edges = len(self.edges_dict)def getEdges(self, V):passdef getVerticesNumbers(self):if self.num_vertices == 0:self.num_vertices = len(self.matrix)return self.num_verticesdef getAllVertices(self):return self.verticesdef getAllEdges(self):for i in range(len(self.matrix)):for j in range(len(self.matrix)):if 0 < self.matrix[i][j] < float('inf'):self.edges_dict[self.vertices[i], self.vertices[j]] = self.matrix[i][j]self.edges_array.append([self.vertices[i], self.vertices[j], self.matrix[i][j]])return self.edges_arraydef __repr__(self):return str(''.join(str(i) for i in self.matrix))def to_do_vertex(self, i):print('vertex: %s' % (self.vertices[i]))def to_do_edge(self, w, k):print('edge tail: %s, edge head: %s, weight: %s' % (self.vertices[w], self.vertices[k], str(self.matrix[w][k])))if __name__=='__main__':th1 = np.array([[0, 1, 1, 1, 1, 1, 0, 0],[0, 0, 1, 0, 1, 0, 0, 0],[0, 0, 0, 1, 0, 0, 0, 0],[0, 0, 0, 0, 1, 0, 0, 0],[0, 0, 0, 0, 0, 1, 0, 0],[0, 0, 1, 0, 0, 0, 1, 1],[0, 0, 0, 0, 0, 1, 0, 1],[0, 0, 0, 0, 0, 1, 1, 0]])#根据邻接矩阵生成图nodes=[i for i in range(8)]my_graph = Graph_Matrix(nodes, th1)G = nx.Graph()  # 建立一个空的无向图G#将点和邻接关系加入到图中for node in my_graph.vertices:G.add_node(str(node))for edge in my_graph.edges:G.add_edge(str(edge[0]), str(edge[1]))#根据louvain算法计算最佳分区partition = community.community_louvain.best_partition(G)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.5, edge_color='#00649a')nx.draw_networkx_edges(G,pos, width=1.0,edge_color='k',style='solid',alpha=None)plt.show()

参考文章如下:
Python社区发现—Louvain—networkx和community
Python 邻接矩阵实现无向图、有向图的三种方法,并绘图显示

邻接矩阵实现无向图的创建并根据louvain算法实现分区相关推荐

  1. 实现教材算法7.2利用邻接矩阵构造无向图的算法,在此基础上进行深度优先遍历和广度优先遍历。

    软件学院实验报告 姓名:              学号:              专业:               年级: 课程名称 数据结构 实验名称 实验9.图的遍历 实验的准备阶段 实验内 ...

  2. python画矩阵图_Python根据已知邻接矩阵绘制无向图操作示例

    本文实例讲述了Python根据已知邻接矩阵绘制无向图操作.分享给大家供大家参考,具体如下: 有六个点:[0,1,2,3,4,5,6],六个点之间的邻接矩阵如表格所示,根据邻接矩阵绘制出相对应的图 0 ...

  3. 社区发现不得不了解的库,包含Louvain 算法、Girvan-Newman 算法等多种社区发现算法,还具有可视化功能

    熟知社区发现算法,你不能错过这个 Python 库.它涵盖 Louvain 算法.Girvan-Newman 算法等多种社区发现算法,还具有可视化功能. 网络是由一些紧密相连的节点组成的,并且根据不同 ...

  4. 基于无向图的城市间快递派送算法

    1.题目分析 1.1题目简介   假设你为快递公司设计快递投递路线优化程序.(1)每个市有个中转分发点,有些城市之间有直通路线,有些城市之间没有直通路线:(2)城市与城市之间的运费计算公式为:距离*1 ...

  5. Community detection|模块度含义理解|Louvain算法

    文章目录 Community detection:团伙挖掘/社团发现 Modularity:模块度 模块度增益 Louvain算法 Community detection:团伙挖掘/社团发现 利用图拓 ...

  6. 创建分区表+分区表的分类+创建散列分区表+查看散列分区表分区中的数据+创建列表分区表+查看列表分区表分区中的数据...

    创建分区表 分区表的分类 范围分区:对数据表的某个值的范围进行分区,需要使用partition by range字句. 散列分区: 1通过hash算法均匀分布数据的一种分区类型. 2通过在I/O设备上 ...

  7. louvain算法_单细胞聚类(四)图解Leiden算法对Louvain算法的优化

    Louvain算法是目前单细胞分析中最常用的聚类算法[1],Seurat/Scanpy/RaceID等单细胞分析工具都默认louvain算法.6天前HumanCell Atlas(HCA)团队发表在N ...

  8. 单细胞算法-聚类-louvain算法

    单细胞算法-聚类-louvain算法 什么是Louvain算法 Louvain算法是利用度量社区模块度进行聚类的一个算法. 关于模块度的介绍: link 关于louvain算法的介绍: https:/ ...

  9. Louvain 算法

    Louvain 算法 简介 Louvain 算法是一种基于贪心的社群发现算法,其主要思想是将节点不断地聚合成社区(community),并最大化社区内部的连通性以及社区之间的连接弱化.该算法的特点在于 ...

  10. MATLAB强化学习实战(十二) 创建自定义强化学习算法的智能体

    创建自定义强化学习算法的智能体 创建环境 定义策略 自定义智能体类 智能体属性 构造函数 相关函数 可选功能 创建自定义智能体 训练自定义智能体 自定义智能体仿真 本示例说明如何为您自己的自定义强化学 ...

最新文章

  1. 微型计算机重点,微型计算机理期末重点.doc
  2. Windows和Linux下apache-artemis-2.10.0安装配置
  3. 做 SQL 性能优化真是让人干瞪眼
  4. 二进制法生成1-n的子集
  5. Vue之v-if, v-else, v-show, v-for, v-bind
  6. 如何在 M1 Mac 上运行Intel架构的应用程序?
  7. (转载) flex builder
  8. 复制xml导致乱码问题解决。
  9. KMeans算法流程
  10. Java 程序员新机必备程序清单
  11. 如何快速入侵一个网站
  12. 电脑在使用b站的时候插入耳机,耳机没有声音,只能外放,其他软件可以正常使用。
  13. 15个令iPhone用户嫉妒的Android widgets 桌面组件
  14. XXE漏洞(XML外部实体注入)
  15. android手机病毒多杀毒,手机中毒不用慌!教你几招安卓手机怎么彻底的进行杀毒...
  16. SQL基础教程学习第六站:数据更新
  17. Wifi密码 (10分)
  18. 【pwsh】按键自动切换中文输入法
  19. 第4章:色彩空间类型转换
  20. 项目经理,你要考的证书都在这

热门文章

  1. 回顾jvisualvm安装插件简单操作
  2. 快手滑块验证码分析 2022/03/17
  3. 【MySQL建表语句转PostgreSQL建表语句】MySQL建表语句转PostgreSQL建表语句 接上一篇
  4. Acme CAD Converter 2019简体中文直装破解版
  5. 最简单的Dubbo教程(springBoot纯注解版)
  6. 极域电子教室超级管理员密码
  7. 程序员100套简历模板,全网最全
  8. 一个故事讲完CPU的工作原理
  9. oracle ocp考题,Oracle OCP认证考试题库更新,052新考题整理(带答案)-72
  10. 2021年老杨通信工程师中级互联网技术视频讲解