给定一个任意数值数组(ndarray
),有没有一个函数或一种简单的方法可以将它转换成一个scipy.sparse
矩阵?
我想要像这样工作的东西:
A = numpy.array([0,1,0],[0,0,0],[1,0,0])
S = to_sparse(A, type="csr_matrix")
发布于 2012-05-21 14:18:27
我通常会做这样的事情
>>> import numpy, scipy.sparse
>>> A = numpy.array([[0,1,0],[0,0,0],[1,0,0]])
>>> Asp = scipy.sparse.csr_matrix(A)
>>> Asp
<3x3 sparse matrix of type '<type 'numpy.int64'>'
with 2 stored elements in Compressed Sparse Row format>
发布于 2012-05-21 14:20:05
在帮助中有一个非常有用和相关的例子!
import scipy.sparse as sp
help(sp)
这提供了:
Example 2
---------
Construct a matrix in COO format:
>>> from scipy import sparse
>>> from numpy import array
>>> I = array([0,3,1,0])
>>> J = array([0,3,1,2])
>>> V = array([4,5,7,9])
>>> A = sparse.coo_matrix((V,(I,J)),shape=(4,4))
还值得注意的是,不同的构造函数(同样来自帮助):
1. csc_matrix: Compressed Sparse Column format
2. csr_matrix: Compressed Sparse Row format
3. bsr_matrix: Block Sparse Row format
4. lil_matrix: List of Lists format
5. dok_matrix: Dictionary of Keys format
6. coo_matrix: COOrdinate format (aka IJV, triplet format)
7. dia_matrix: DIAgonal format
To construct a matrix efficiently, use either lil_matrix (recommended) or
dok_matrix. The lil_matrix class supports basic slicing and fancy
indexing with a similar syntax to NumPy arrays.
您的示例将与以下内容一样简单:
S = sp.csr_matrix(A)
发布于 2020-11-26 06:44:10
请参考这个答案:https://stackoverflow.com/a/65017153/9979257
在这个答案中,我已经解释了如何将二维NumPy矩阵转换为CSR或CSC格式。
https://stackoverflow.com/questions/10686924
复制