剪辑 scipy 稀疏矩阵切片的规范方法

问题描述 投票:0回答:0

我正在寻找剪切稀疏矩阵的一部分。这对于密集矩阵来说相当容易。

import numpy as np
dense_matrix = np.array(
            [
                [100, 200, 0, 0, 164],
                [134, 682, 417, 8, 391],
                [0, 133, 780, 0, 0],
                [396, 76, 96, 214, 0],
            ], 
            dtype=np.int16,
        )

dense_matrix[2:4,2:] = np.clip(dense_matrix[2:4,2:], 0, 100)

这给了我

dense_matrix
作为

array([[100, 200,   0,   0, 164],
       [134, 682, 417,   8, 391],
       [  0, 133, 100,   0,   0],
       [396,  76,  96, 100,   0]], dtype=int16)

有没有办法对稀疏矩阵做同样的事情?除了遍历

index
indptr
并在索引位于切片中时手动剪裁
data
之外,我能想到的唯一选择是复制数据并使用
data
的slice,像下面的代码:

sparse_matrix = scipy.sparse.csr_matrix(dense_matrix)
temp_slice = sparse_matrix[2:4,2:] 
temp_slice.data =  np.clip(temp_slice.data, 0, 97)
sparse_matrix[2:4,2:] = temp_slice
sparse_matrix.todense()

这给了我

matrix([[100, 200,   0,   0, 164],
        [134, 682, 417,   8, 391],
        [  0, 133,  97,   0,   0],
        [396,  76,  96,  97,   0]], dtype=int16)

有更好的方法吗?

python numpy matrix scipy sparse-matrix
© www.soinside.com 2019 - 2024. All rights reserved.