Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Circular Permutation (left and right shift) of CSR_Matrix in Scipy Python Sparse Matrices?

I am using Scipy sparse matrix csr_matrix to be used as context vectors in word-context vectors. My csr_matrix is a (1, 300) shape so it is a 1-dimensional vector.

I need to use permutation (circular right shift or circular left shift) on the sparse vector (for showing left context and right context).

example: i have [1, 2, 3, 4] and i want to create right and left permutations as follow:

right permutation: [4, 1, 2, 3]
left permutation: [2, 3, 4, 1]

In csr matrices i can't access to column indices so i can not just change the column indices.

Is there any efficient high performance solution for row permutations in csr_matrix or am i missing something?

runnable code:

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

it means that i have a 300-column vector whose columns 100, 47, 150 all from row 0 are non-zero valued and their value is in data list respectively.

now what i want is a permutation which means i want the columns array be changed into [101, 48, 151] for right permutation and [99, 46, 149] for left permutation.

It should be noted that permutations are circular which means if column 299 has non-zero data, using a right permutation the data will be moved to column 0.

like image 559
alenrooni Avatar asked Dec 09 '13 14:12

alenrooni


1 Answers

You can access and alter the data and indices attributes of your CSR matrix, which are stored as NumPy arrays.

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

So using your code and following the suggestion in the comments you could do this:

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]
like image 116
YXD Avatar answered Sep 24 '22 18:09

YXD