简体   繁体   English

使用 Python 上的图形工具从邻接矩阵生成不正确的图形

[英]Generating incorrect graphs from adjacency matrices using graph-tool on Python

I am trying to generate a graph from an adjacency matrix.我正在尝试从邻接矩阵生成图形。 I know it is something that has already been asked here but I can't get to generate one correctly.我知道这是已经在这里问过的东西,但我无法正确生成一个。 My code is我的代码是

import numpy as np
import graph_tool.all as gt

L = 10; p = 0.6

Adj = np.zeros((L,L))

for i in range(0,L):
    for j in range(i+1,L):
        if np.random.rand() < p:
            Adj[i,j] = 1

Adj = Adj + np.transpose(Adj)

print('Adjacency matrix is \n', Adj)

g = gt.Graph(directed=False)
g.add_edge_list(Adj.nonzero())

gt.graph_draw(g, vertex_text=g.vertex_index, output="two-nodes.pdf")

It generates an adjacency matrix with each connection happening with a probability of 60%.它生成一个邻接矩阵,每个连接发生的概率为 60%。 One result is一个结果是

Adjacency matrix is 
 [[0. 1. 1. 0. 1. 0. 1. 1. 1. 0.]
 [1. 0. 1. 1. 1. 1. 1. 0. 1. 1.]
 [1. 1. 0. 1. 1. 0. 1. 1. 1. 0.]
 [0. 1. 1. 0. 1. 1. 1. 0. 1. 1.]
 [1. 1. 1. 1. 0. 1. 1. 1. 0. 1.]
 [0. 1. 0. 1. 1. 0. 0. 0. 1. 0.]
 [1. 1. 1. 1. 1. 0. 0. 1. 0. 1.]
 [1. 0. 1. 0. 1. 0. 1. 0. 0. 0.]
 [1. 1. 1. 1. 0. 1. 0. 0. 0. 1.]
 [0. 1. 0. 1. 1. 0. 1. 0. 1. 0.]]

But I don't know why the graphical result is this one which is clearly incorrect.但我不知道为什么图形结果是这个明显不正确的结果。

As stated in add_edge_list docs , you needadd_edge_list docs中所述,您需要

an iterator of (source, target) pairs where both source and target are vertex indexes, or a numpy.ndarray of shape (E,2), where E is the number of edges, and each line specifies a (source, target) pair (source, target) 对的迭代器,其中 source 和 target 都是顶点索引,或形状为 (E,2) 的 numpy.ndarray,其中 E 是边数,每行指定一个 (source, target) 对

In your case, you're passing a single tuple (check the result of Adj.nonzero() ).在您的情况下,您正在传递一个元组(检查Adj.nonzero()的结果)。 To fix it, just try this:要修复它,只需尝试以下操作:

g.add_edge_list(np.transpose(Adj.nonzero()))

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

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