邻接矩阵实现无向图的创建并根据louvain算法实现分区
生活随笔
收集整理的這篇文章主要介紹了
邻接矩阵实现无向图的创建并根据louvain算法实现分区
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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生成如下無(wú)向圖
再根據(jù)louvain算法進(jìn)行分區(qū)得到下圖
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("節(jié)點(diǎn)下標(biāo)出界")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]])#根據(jù)鄰接矩陣生成圖nodes=[i for i in range(8)]my_graph = Graph_Matrix(nodes, th1)G = nx.Graph() # 建立一個(gè)空的無(wú)向圖G#將點(diǎn)和鄰接關(guān)系加入到圖中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]))#根據(jù)louvain算法計(jì)算最佳分區(qū)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社區(qū)發(fā)現(xiàn)—Louvain—networkx和community
Python 鄰接矩陣實(shí)現(xiàn)無(wú)向圖、有向圖的三種方法,并繪圖顯示
總結(jié)
以上是生活随笔為你收集整理的邻接矩阵实现无向图的创建并根据louvain算法实现分区的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: pwm控制舵机转动角度程序_Mixly
- 下一篇: day1||python