scipy 稀疏矩阵的条件切片
conditional slicing of scipy sparse matrix
抱歉,如果这是重复的。
我有另一个函数返回的大 coo_matrix
(比如 x
),我需要在 numpy 数组 a
中对匹配条件的行进行切片,具有相同的数量行和单个列(具有二进制值)。
我正在使用 scipy.sparse.hstack([x,a]) 将两者连接起来,以便执行类似这样的操作
x1 = x[x[:,-1] == 0]
x2 = x[x[:,-1] == 1]
但是失败并出现以下错误。
TypeError: 'coo_matrix' object is not subscriptable
x.toarray()
解决方案因 MemoryError
.
而无效
有没有办法做到以上几点?最后我需要 coo_matrix
的切片矩阵。
制作一个随机的csr
格式矩阵:
In [795]: M = sparse.random(20,10,.2,'csr')
获取最后一列的密集一维数组。 (我不想要矩阵或矩阵中的二维数组):
In [805]: M1 = M[:,-1].A.ravel()
现在我可以将其用作行掩码:
In [808]: M[M1==0,:]
Out[808]:
<16x10 sparse matrix of type '<class 'numpy.float64'>'
with 30 stored elements in Compressed Sparse Row format>
In [809]: M[M1>0,:]
Out[809]:
<4x10 sparse matrix of type '<class 'numpy.float64'>'
with 10 stored elements in Compressed Sparse Row format>
尝试使用稀疏列进行屏蔽无效:
M[M[:,-1]>0,:]
IndexError: Indexing with sparse matrices is not supported except boolean indexing where matrix and index are equal shapes.
csr
矩阵的索引是通过矩阵乘法完成的。索引变成了 1 和 0 的稀疏矩阵,乘法最终选择了所需的行。稀疏求和也是用乘法完成的。
lil
格式的行索引也很容易。
重新阅读您的问题,我建议将 x
和 a
分开。由于 a
已经是密集的,只需使用
M1 = a.ravel() # if a is (n,1) array
M1 = a.A1 # if a is (n,1) np.matrix
制作 1d ndarray
,如上文 [805] 所示。因为它有二进制值,你只对 0 vs 1
感兴趣
M1 = M1.astype(bool)
和
M[~M1,:]
M[M1,:]
对于两个子集。
同样,如果不清楚,我们无法索引 coo
格式矩阵。它必须是 csr
或 lil
格式。
抱歉,如果这是重复的。
我有另一个函数返回的大 coo_matrix
(比如 x
),我需要在 numpy 数组 a
中对匹配条件的行进行切片,具有相同的数量行和单个列(具有二进制值)。
我正在使用 scipy.sparse.hstack([x,a]) 将两者连接起来,以便执行类似这样的操作
x1 = x[x[:,-1] == 0]
x2 = x[x[:,-1] == 1]
但是失败并出现以下错误。
TypeError: 'coo_matrix' object is not subscriptable
x.toarray()
解决方案因 MemoryError
.
有没有办法做到以上几点?最后我需要 coo_matrix
的切片矩阵。
制作一个随机的csr
格式矩阵:
In [795]: M = sparse.random(20,10,.2,'csr')
获取最后一列的密集一维数组。 (我不想要矩阵或矩阵中的二维数组):
In [805]: M1 = M[:,-1].A.ravel()
现在我可以将其用作行掩码:
In [808]: M[M1==0,:]
Out[808]:
<16x10 sparse matrix of type '<class 'numpy.float64'>'
with 30 stored elements in Compressed Sparse Row format>
In [809]: M[M1>0,:]
Out[809]:
<4x10 sparse matrix of type '<class 'numpy.float64'>'
with 10 stored elements in Compressed Sparse Row format>
尝试使用稀疏列进行屏蔽无效:
M[M[:,-1]>0,:]
IndexError: Indexing with sparse matrices is not supported except boolean indexing where matrix and index are equal shapes.
csr
矩阵的索引是通过矩阵乘法完成的。索引变成了 1 和 0 的稀疏矩阵,乘法最终选择了所需的行。稀疏求和也是用乘法完成的。
lil
格式的行索引也很容易。
重新阅读您的问题,我建议将 x
和 a
分开。由于 a
已经是密集的,只需使用
M1 = a.ravel() # if a is (n,1) array
M1 = a.A1 # if a is (n,1) np.matrix
制作 1d ndarray
,如上文 [805] 所示。因为它有二进制值,你只对 0 vs 1
M1 = M1.astype(bool)
和
M[~M1,:]
M[M1,:]
对于两个子集。
同样,如果不清楚,我们无法索引 coo
格式矩阵。它必须是 csr
或 lil
格式。