简体   繁体   English

Python NetworkX从关联矩阵创建图形

[英]Python NetworkX creating graph from incidence matrix

I have an incidence matrix (where the rows are nodes and the columns are edges) as follows (it is read from a text file into a NumPy array): 我有一个关联矩阵(其中行是节点,列是边),如下所示(从文本文件读取到NumPy数组):

[[1 1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 0 0 0]
 [1 1 1 1 1 0 1 1 0 0]
 [0 0 1 1 1 0 1 0 0 0]
 [1 1 1 1 1 1 0 0 0 0]
 [1 1 0 1 1 0 0 0 0 0]
 [1 0 1 0 0 1 0 1 0 0]
 [0 1 0 1 1 0 0 0 0 0]
 [1 1 1 0 0 1 0 0 0 0]
 [0 0 1 1 0 1 0 0 0 0]
 [1 0 1 0 0 1 0 0 0 0]
 [1 0 1 1 0 0 0 0 0 0]
 [1 0 0 0 0 0 1 1 0 0]
 [1 1 0 0 0 0 1 0 0 0]
 [0 1 0 0 0 1 0 0 0 0]
 [1 0 0 1 0 0 0 0 0 0]
 [0 0 1 1 0 0 0 0 0 0]
 [1 1 0 0 0 0 0 0 0 0]
 [0 1 0 0 0 0 0 0 0 0]
 [0 0 0 1 0 0 0 0 0 0]
 [1 0 0 0 0 0 0 0 0 0]
 [0 0 0 1 0 0 0 0 0 0]
 [0 1 0 0 0 0 0 0 0 0]
 [0 0 1 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 1 0 0 0]
 [0 1 0 0 0 0 0 0 0 0]]

I would like to create a graph using NetworkX from this matrix, but could not find how to do that. 我想从这个矩阵使用NetworkX创建一个图表,但是找不到如何做到这一点。 NetworkX from_numpy_matrix works only with adjacency matrices. NetworkX from_numpy_matrix仅适用于邻接矩阵。 Here is a good example of how to create an incidence matrix using NetworkX (but that's not my case, because I have already an incidence matrix to begin with). 以下是如何使用NetworkX创建关联矩阵的一个很好的示例(但这不是我的情况,因为我已经开始使用关联矩阵)。 I have also tried this , but got the nasty error: 我也试过这个 ,但得到了令人讨厌的错误:

File "C:\Python27\lib\site-packages\networkx\convert.py", line 150, in to_networkx_graph
    "Input is not a correct numpy matrix or array.")
networkx.exception.NetworkXError: Input is not a correct numpy matrix or array.

Looks a simple question, but perhaps it isn't. 看起来一个简单的问题,但也许不是。 Can anyone help me with it? 任何人都可以帮助我吗?

Thanks in advance! 提前致谢!

Networkx has a handy nx.from_numpy_matrix function taking an adjacency matrix, so once we convert the incidence matrix to an adjacency matrix, we're good. Networkx有一个方便的nx.from_numpy_matrix函数采用邻接矩阵,所以一旦我们将关联矩阵转换为邻接矩阵,我们就很好了。

Say we start with the incidence matrix 假设我们从关联矩阵开始

im = np.array([[0, 1, 1], [0, 1, 1], [0, 0, 0]])

To convert it to an adjacency matrix, first let's see which nodes are connected: 要将其转换为邻接矩阵,首先让我们看看哪些节点是连接的:

am = (np.dot(im, im.T) > 0).astype(int)

Here we're just checking if any two nodes have at least one edge between them. 这里我们只是检查两个节点之间是否至少有一条边。

If you want to remove self loops, you can call 如果要删除自循环,可以调用

np.fill_diagonal(am, 0)

Let's see now am : 现在,让我们看看am

>>> am
array([[0, 1, 0],
       [1, 0, 0],
       [0, 0, 0]])

To create the graph, now we can just call 要创建图表,现在我们可以调用

networkx.from_numpy_matrix(am)

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

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