本文介绍了如何将numpy.matrix或数组转换为scipy稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于SciPy稀疏矩阵,可以使用todense()
或toarray()
转换为NumPy矩阵或数组.进行逆运算的功能是什么?
For SciPy sparse matrix, one can use todense()
or toarray()
to transform to NumPy matrix or array. What are the functions to do the inverse?
我搜索了,但不知道应该正确选择哪些关键字.
I searched, but got no idea what keywords should be the right hit.
推荐答案
初始化稀疏矩阵时,可以将numpy数组或矩阵作为参数传递.例如,对于CSR矩阵,您可以执行以下操作.
You can pass a numpy array or matrix as an argument when initializing a sparse matrix. For a CSR matrix, for example, you can do the following.
>>> import numpy as np
>>> from scipy import sparse
>>> A = np.array([[1,2,0],[0,0,3],[1,0,4]])
>>> B = np.matrix([[1,2,0],[0,0,3],[1,0,4]])
>>> A
array([[1, 2, 0],
[0, 0, 3],
[1, 0, 4]])
>>> sA = sparse.csr_matrix(A) # Here's the initialization of the sparse matrix.
>>> sB = sparse.csr_matrix(B)
>>> sA
<3x3 sparse matrix of type '<type 'numpy.int32'>'
with 5 stored elements in Compressed Sparse Row format>
>>> print sA
(0, 0) 1
(0, 1) 2
(1, 2) 3
(2, 0) 1
(2, 2) 4
这篇关于如何将numpy.matrix或数组转换为scipy稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!