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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With