【问题标题】:How to implement Circular Permutation (left and right shift) of CSR_Matrix in Scipy Python Sparse Matrices?如何在 Scipy Python 稀疏矩阵中实现 CSR_Matrix 的循环排列(左移和右移)?
【发布时间】:2013-12-26 17:06:15
【问题描述】:

我正在使用 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 列的向量,其第 0 行的第 100、47、150 列都是非零值,它们的值分别在数据列表中。

现在我想要的是一个排列,这意味着我希望将列数组更改为 [101, 48, 151] 用于右排列,[99, 46, 149] 用于左排列。

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

【问题讨论】:

    标签: python scipy permutation sparse-matrix


    【解决方案1】:

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

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

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

    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]
    

    【讨论】:

    • 你可以说:the_matrix.indices = (the_matrix.indices+1)%the_matrix.shape[1]我猜
    • 非常感谢您的帮助。我对其进行了测试,效果很好。
    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 2021-11-23
    • 1970-01-01
    • 2019-08-09
    • 2014-10-15
    • 2012-05-23
    • 2015-05-08
    • 2017-10-23
    相关资源
    最近更新 更多