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

ale*_*oni 5 python permutation scipy sparse-matrix

我正在使用 Scipy 稀疏矩阵csr_matrix作为词上下文向量中的上下文向量。Mycsr_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) )
Run Code Online (Sandbox Code Playgroud)

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

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

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

YXD*_*YXD 5

您可以访问和更改CSR 矩阵的data和indices属性,它们存储为 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]
Run Code Online (Sandbox Code Playgroud)

  • 你可以说:`the_matrix.indices = (the_matrix.indices+1)%the_matrix.shape[1]` 我猜 (2认同)