How do I transform a “SciPy sparse matrix” to a “NumPy matrix”?
我正在使用一个名为" incidence_matrix(G)"的python函数,该函数返回图的入射矩阵。 它来自Networkx软件包。 我面临的问题是此函数的返回类型是" Scipy Sparse Matrix"。 我需要以numpy矩阵或数组的格式获取事件矩阵。 我想知道是否有任何简便的方法? 还是有任何内置函数可以为我执行此转换?
谢谢
-
a.toarray() 或a.A -返回此矩阵的密集ndarray表示形式。 (numpy.array ,推荐) -
a.todense() 或a.M -返回此矩阵的密集矩阵表示形式。 (numpy.matrix )
最简单的方法是对数据调用todense()方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | In [1]: import networkx as nx In [2]: G = nx.Graph([(1,2)]) In [3]: nx.incidence_matrix(G) Out[3]: <2x1 sparse matrix of type '<type 'numpy.float64'>' with 2 stored elements in Compressed Sparse Column format> In [4]: nx.incidence_matrix(G).todense() Out[4]: matrix([[ 1.], [ 1.]]) In [5]: nx.incidence_matrix(G).todense().A Out[5]: array([[ 1.], [ 1.]]) |
我发现对于csr矩阵,
我将其翻译为lil矩阵-numpy可以准确解析格式,然后在该文件上运行
1 | sparse.lil_matrix(<my-sparse_matrix>).toarray() |