Jan*_*Jan 5 matlab numpy scipy sparse-matrix
我有大而稀疏的数组,我想通过交换行来重新排列它们.有什么好办法scipy.sparse吗?
一些问题
我不认为排列矩阵非常适合这项任务,因为他们喜欢随机改变稀疏结构.并且操纵将总是"倍增"所有列或行,即使只需要少量交换.
scipy.sparse这项任务的最佳稀疏矩阵表示是什么?
非常欢迎实施建议.
我也用Matlab标记了这个,因为这个问题可能找到一个不一定scipy具体的答案.
CSC 格式保留所有非零条目的行索引列表,CSR 格式保留所有非零条目的列索引列表。我认为你可以利用这一点来交换如下内容,而且我认为它不应该有任何副作用:
def swap_rows(mat, a, b) :
mat_csc = scipy.sparse.csc_matrix(mat)
a_idx = np.where(mat_csc.indices == a)
b_idx = np.where(mat_csc.indices == b)
mat_csc.indices[a_idx] = b
mat_csc.indices[b_idx] = a
return mat_csc.asformat(mat.format)
def swap_cols(mat, a, b) :
mat_csr = scipy.sparse.csr_matrix(mat)
a_idx = np.where(mat_csr.indices == a)
b_idx = np.where(mat_csr.indices == b)
mat_csr.indices[a_idx] = b
mat_csr.indices[b_idx] = a
return mat_csr.asformat(mat.format)
Run Code Online (Sandbox Code Playgroud)
你现在可以做这样的事情:
>>> mat = np.zeros((5,5))
>>> mat[[1, 2, 3, 3], [0, 2, 2, 4]] = 1
>>> mat = scipy.sparse.lil_matrix(mat)
>>> mat.todense()
matrix([[ 0., 0., 0., 0., 0.],
[ 1., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 0., 1., 0., 1.],
[ 0., 0., 0., 0., 0.]])
>>> swap_rows(mat, 1, 3)
<5x5 sparse matrix of type '<type 'numpy.float64'>'
with 4 stored elements in LInked List format>
>>> swap_rows(mat, 1, 3).todense()
matrix([[ 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 1.],
[ 0., 0., 1., 0., 0.],
[ 1., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
>>> swap_cols(mat, 0, 4)
<5x5 sparse matrix of type '<type 'numpy.float64'>'
with 4 stored elements in LInked List format>
>>> swap_cols(mat, 0, 4).todense()
matrix([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1.],
[ 0., 0., 1., 0., 0.],
[ 1., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 0.]])
Run Code Online (Sandbox Code Playgroud)
我使用 LIL 矩阵来展示如何保留输出的类型。在您的应用程序中,您可能希望已经采用 CSC 或 CSR 格式,并选择是否首先根据它交换行或列,以最大限度地减少转换。