检查documentation后和 this question我尝试拆分 numpy 数组和稀疏 scipy 矩阵,如下所示:
>>>print(X.shape)
(2399, 39999)
>>>print(type(X))
<class 'scipy.sparse.csr.csr_matrix'>
>>>print(X.toarray())
[[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
...,
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]
[0 0 0 ..., 0 0 0]]
然后:
new_array = np.split(X,3)
输出:
ValueError: array split does not result in an equal division
然后我尝试:
new_array = np.hsplit(X,3)
输出:
ValueError: bad axis1 argument to swapaxes
因此,如何将数组拆分为 N
个不同的大小不等的 block ?
最佳答案
制作稀疏矩阵:
In [62]: M=(sparse.rand(10,3,.3,'csr')*10).astype(int)
In [63]: M
Out[63]:
<10x3 sparse matrix of type '<class 'numpy.int32'>'
with 9 stored elements in Compressed Sparse Row format>
In [64]: M.A
Out[64]:
array([[0, 7, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 5],
[0, 0, 2],
[0, 0, 6],
[0, 4, 4],
[7, 1, 0],
[0, 0, 2]])
稠密等价物很容易 split 。 array_split
处理不相等的 block ,但您也可以按照其他答案中的说明拼出拆分。
In [65]: np.array_split(M.A, 3)
Out[65]:
[array([[0, 7, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]), array([[0, 0, 5],
[0, 0, 2],
[0, 0, 6]]), array([[0, 4, 4],
[7, 1, 0],
[0, 0, 2]])]
一般来说,numpy 函数不能直接作用于稀疏矩阵。他们不是一个子类。除非函数将操作委托(delegate)给数组自己的方法,否则该函数可能无法工作。该函数通常以 np.asarray(M)
开头,它与 M.toarray()
不同(您自己尝试一下)。
但是split
只不过是沿着所需的轴进行切片。我可以使用以下命令生成相同的 4,2,3 分割:
In [143]: alist = [M[0:4,:], M[4:7,:], M[7:10]]
In [144]: alist
Out[144]:
[<4x3 sparse matrix of type '<class 'numpy.int32'>'
with 1 stored elements in Compressed Sparse Row format>,
<3x3 sparse matrix of type '<class 'numpy.int32'>'
with 3 stored elements in Compressed Sparse Row format>,
<3x3 sparse matrix of type '<class 'numpy.int32'>'
with 5 stored elements in Compressed Sparse Row format>]
In [145]: [m.A for m in alist]
Out[145]:
[array([[0, 7, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]], dtype=int32), array([[0, 0, 5],
[0, 0, 2],
[0, 0, 6]], dtype=int32), array([[0, 4, 4],
[7, 1, 0],
[0, 0, 2]], dtype=int32)]
剩下的就是管理细节。
我应该补充一点,稀疏切片从来都不是 View 。它们是新的稀疏矩阵,具有自己的 data
属性。
利用列表中的拆分索引,我们可以通过简单的迭代来构造拆分列表:
In [146]: idx = [0,4,7,10]
In [149]: alist = []
In [150]: for i in range(len(idx)-1):
...: alist.append(M[idx[i]:idx[i+1]])
我还没有弄清楚如何构造 idx
的细节,尽管 10
中的一个明显的起点是 M.shape[0]
.
均匀分割(适合)
In [160]: [M[i:i+5,:] for i in range(0,M.shape[0],5)]
Out[160]:
[<5x3 sparse matrix of type '<class 'numpy.int32'>'
with 2 stored elements in Compressed Sparse Row format>,
<5x3 sparse matrix of type '<class 'numpy.int32'>'
with 7 stored elements in Compressed Sparse Row format>]
关于python - 如何有效地将 scipy 稀疏数组和 numpy 数组分割成较小的 N 个不等 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43049072/