gpt4 book ai didi

matlab - 通过交换行和列来重新排列稀疏数组

转载 作者:太空宇宙 更新时间:2023-11-03 19:44:57 24 4
gpt4 key购买 nike

我有大而稀疏的数组,我想通过交换行和列来重新排列它们。在 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)

你现在可以做这样的事情:

>>> 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.]])

我使用了 LIL 矩阵来展示如何保留输出的类型。在您的应用程序中,您可能希望已经是 CSC 或 CSR 格式,并根据它选择是否首先交换行或列,以最大限度地减少转换。

关于matlab - 通过交换行和列来重新排列稀疏数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15155276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com