日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發布時間:2023/12/10 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 邻接矩阵实现无向图的创建并根据louvain算法实现分区 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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算法实现分区的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。