我遇到了大麻烦。我在python中编写的代码使用Numpy
和Networkx
6个月前使用此代码:
import numpy as np
import networkx as nx
G = nx.Graph()
#add node and edges to G ...
A = nx.adj_matrix(Gx)
A = np.asarray(A)
现在我需要在具有最新版Numpy的计算集群上运行它。但是当我运行此代码时,它会失败,因为A = np.asarray(A)
会返回()
我不知道该怎么做,因为这段代码无处不在。这是Numpy中的一个错误还是什么?
此问题与我的earlier question
有关答案 0 :(得分:1)
函数 nx.adj_matrix(G)
会返回一个scipy.sparse
矩阵对象,其中包含G的邻接矩阵。
如果您想要numpy
矩阵或数组,只需使用 .todense()
方法即可:
In [1]: import networkx as nx
In [2]: G = nx.path_graph(4)
In [3]: S = nx.adj_matrix(G)
In [4]: S
Out[4]:
<4x4 sparse matrix of type '<type 'numpy.int64'>'
with 6 stored elements in Compressed Sparse Row format>
In [5]: A = S.todense()
In [6]: A
Out[6]:
matrix([[0, 1, 0, 0],
[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0]])
In [7]: A.A
Out[7]:
array([[0, 1, 0, 0],
[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0]])
答案 1 :(得分:1)
从这个拉动请求判断:
https://github.com/networkx/networkx/commit/67bf6c1b4d2844a859b21057a63a72b36a45906b
2013年11月,networkx
将adjacency_matrix
(同义词adj_matrix
)从生成密集矩阵变为生成稀疏矩阵。在许多情况下,他们在调用此函数时必须添加.todense()
。
因此,更改可能是networkx
而不是numpy
。我认为np.asarray
从未sparse
知道np.matrix
。通常用于将np.ndarray
转换为adj_matrix().A
。
使用np.matrix
应该适用于这两种环境。 csr_matrix
和{{1}}都有此属性。