简体   繁体   English

Python Nympy 中 Graph 的邻接矩阵

[英]Adjacency matrix for Graph in Python Nympy

I need to make an adjacency metrics我需要制定邻接指标

I have the edges information.我有边缘信息。

edges = numpy.array([[0,1],[0,3],[1,2],[1,4],[2,5],[3,4],[3,5],[4,5]])

I need a python code to generate the adjacency metrics using NumPy only from the edges information.我需要一个 python 代码来仅从边缘信息中使用 NumPy 生成邻接度量。 Can someone help?有人可以帮忙吗?

It depends what type of adjacency matrix you want, but here's an example with 0 for not connected and 1 for connected, rows are from and columns are to.这取决于您想要哪种类型的邻接矩阵,但这里有一个示例,其中 0 表示未连接,1 表示已连接,行来自,列来自。

import numpy

edges = numpy.array([[0,1],[0,3],[1,2],[1,4],[2,5],[3,4],[3,5],[4,5]])

matrix = numpy.zeros((edges.max()+1, edges.max()+1))
matrix[edges[:,0], edges[:,1]] = 1

gives

array([[0., 1., 0., 1., 0., 0.],
       [0., 0., 1., 0., 1., 0.],
       [0., 0., 0., 0., 0., 1.],
       [0., 0., 0., 0., 1., 1.],
       [0., 0., 0., 0., 0., 1.],
       [0., 0., 0., 0., 0., 0.]])

If you want the connections to be bidirectional (ie. 0->1 also connects 1->0), then add another line of code to do the reverse connection.如果您希望连接是双向的(即 0->1 也连接 1->0),则添加另一行代码来进行反向连接。

import numpy

edges = numpy.array([[0,1],[0,3],[1,2],[1,4],[2,5],[3,4],[3,5],[4,5]])

matrix = numpy.zeros((edges.max()+1, edges.max()+1))
matrix[edges[:,0], edges[:,1]] = 1
matrix[edges[:,1], edges[:,0]] = 1

gives

array([[0., 1., 0., 1., 0., 0.],
       [1., 0., 1., 0., 1., 0.],
       [0., 1., 0., 0., 0., 1.],
       [1., 0., 0., 0., 1., 1.],
       [0., 1., 0., 1., 0., 1.],
       [0., 0., 1., 1., 1., 0.]])

The easiest way to get the job done would be using the NetworkX package (if you are allowed to).完成工作的最简单方法是使用NetworkX package(如果允许的话)。

In [72]: import networkx as nx

In [73]: edges = [[0, 1], [0, 3], [1, 2], [1, 4], [2, 5], [3, 4], [3, 5], [4, 5]]

In [74]: nodes = sorted(set(node for edge in edges for node in edge))

In [75]: G = nx.Graph()

In [76]: G.add_nodes_from(nodes)

In [77]: G.add_edges_from(edges)

In [78]: A = nx.adjacency_matrix(G)

In [79]: A.toarray()
Out[79]: 
array([[0, 1, 0, 1, 0, 0],
       [1, 0, 1, 0, 1, 0],
       [0, 1, 0, 0, 0, 1],
       [1, 0, 0, 0, 1, 1],
       [0, 1, 0, 1, 0, 1],
       [0, 0, 1, 1, 1, 0]], dtype=int32)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM