首页 文章

如何在Scipy Python稀疏矩阵中实现CSR_Matrix的循环置换(左移和右移)?

提问于
浏览
4

我使用Scipy稀疏矩阵 csr_matrix 在字上下文向量中用作上下文向量 . 我的 csr_matrix(1, 300) 形状,所以它是一维矢量 .

我需要在稀疏向量上使用置换(圆右移或圆左移)(用于显示左上下文和右上下文) .

例如:我有 [1, 2, 3, 4] ,我想创建左右排列,如下所示:

正确的排列: [4, 1, 2, 3]
左排列: [2, 3, 4, 1]

在csr矩阵中,我无法访问列索引,所以我不能只改变列索引 .

csr_matrix 中是否存在针对行排列的高效高性能解决方案,还是我错过了什么?

可运行代码:

from scipy.sparse import csr_matrix
rows = [0, 0, 0]
columns = [100, 47, 150]
data = [-1, +1, -1]
contextMatrix = csr_matrix( (data,(rows, columns)), shape=(1, 300) )

这意味着我有一个300列向量,其列100,47,150都来自行0,它们的值都是非零值,它们的值分别在数据列表中 .

现在我想要的是一个排列,这意味着我希望将列数组更改为[101,48,151]以进行右置换,并将[99,46,149]更改为左置换 .

应当注意,排列是循环的,这意味着如果列299具有非零数据,则使用右排列,数据将被移动到列0 .

1 回答

  • 4

    您可以访问和更改CSR矩阵的 dataindices 属性,这些属性存储为NumPy数组 .

    http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html#scipy.sparse.csr_matrix

    因此,使用您的代码并遵循评论中的建议,您可以这样做:

    from scipy.sparse import csr_matrix
    rows = [0, 0, 0]
    columns = [100, 47, 150]
    data = [-1, +1, -1]
    m = csr_matrix( (data,(rows, columns)), shape=(1, 300) )
    
    indices = m.indices
    
    # right permutation
    m.indices = (indices + 1) % m.shape[1]
    
    # left permutation
    m.indices = (indices - 1) % m.shape[1]
    

相关问题