Python 如何将“SciPy 稀疏矩阵”转换为“NumPy 矩阵”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26576524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:41:44  来源:igfitidea点击:

How do I transform a "SciPy sparse matrix" to a "NumPy matrix"?

pythonnumpyscipysparse-matrixnetworkx

提问by Mr.Boy

I am using a python function called "incidence_matrix(G)", which returns the incident matrix of graph. It is from Networkx package. The problem that I am facing is the return type of this function is "Scipy Sparse Matrix". I need to have the Incident matrix in the format of numpy matrix or array. I was wondering if there is any easy way of doing that or not? Or is there any built-in function that can do this transformation for me or not?

我正在使用一个名为“incidence_matrix(G)”的python函数,它返回图形的事件矩阵。它来自 Networkx 包。我面临的问题是这个函数的返回类型是“Scipy Sparse Matrix”。我需要 numpy 矩阵或数组格式的事件矩阵。我想知道是否有任何简单的方法可以做到这一点?或者是否有任何内置函数可以为我进行这种转换?

Thanks

谢谢

采纳答案by sebix

The scipy.sparse.*_matrixhas several useful methods, for example, if ais e.g. scipy.sparse.csr_matrix:

scipy.sparse.*_matrix有几个有用的方法,例如,如果a是例如scipy.sparse.csr_matrix

  • a.toarray()or a.A- Return a dense ndarray representation of this matrix. (numpy.array, recommended)
  • a.todense()or a.M- Return a dense matrix representation of this matrix. (numpy.matrix)
  • a.toarray()a.A- 返回此矩阵的密集 ndarray 表示。( numpy.array, 推荐)
  • a.todense()a.M- 返回此矩阵的密集矩阵表示。( numpy.matrix)

回答by Aric

The simplest way is to call the todense() method on the data:

最简单的方法是对数据调用 todense() 方法:

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

回答by user108569

I found that in the case of csr matrices, todense()and toarray()simply wrapped the tuples rather than producing a ndarray formatted version of the data in matrix form. This was unusable for the skmultilearn classifiers I'm training.

我发现,在CSR矩阵的情况下,todense()toarray()简单地包裹所述元组,而不是以矩阵形式产生数据的ndarray格式化版本。这对于我正在训练的 skmultilearn 分类器是不可用的。

I translated it to a lil matrix- a format numpy can parse accurately, and then ran toarray()on that:

我将它转换为lil 矩阵- 一种格式 numpy 可以准确解析,然后运行toarray()

sparse.lil_matrix(<my-sparse_matrix>).toarray()