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

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

我正在尝试从邻接矩阵生成图形。我知道这里已经有人问过这个问题,但我无法正确生成一个。我的密码是

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")

它生成一个邻接矩阵,每个连接发生的概率为 60%。一个结果是

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.]]

但我不知道为什么图形结果是this one,这显然是不正确的。

add_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

在您的例子中,您传递的是单个元组(检查 Adj.nonzero() 的结果)。要修复它,只需试试这个:

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