Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Single Entries in Sparse Matrix in Python

I want to use sparse matrices for BOW feature representation. I have experimented with coo_matrix from scipy, but it doesn't seem to support what I want to do:

I would like to initialize a matrix of all zeros and then change a given entry to one when appropriate. But when I try to index the matrix how I think I should -- myMatrix[0][0] = 1 (or even myMatrix[0][0][0] =1), for example -- it changes all the values in a row to 1. I want to just make a single entry 1.

I can do this easily with numpy matrices, but I would like to use sparse matrices for space efficiency.

like image 995
airpierre Avatar asked Oct 30 '13 21:10

airpierre


People also ask

How do you read a sparse matrix in python?

To check whether a matrix is a sparse matrix, we only need to check the total number of elements that are equal to zero. If this count is more than (m * n)/2, we return true.

How do you store a sparse matrix in python?

Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of no use in most of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero elements. This means storing non-zero elements with triples- (Row, Column, value).


1 Answers

Using the right sparse type helps.

from scipy import sparse
M = sparse.lil_matrix((10,10))
M[1,1] = 1
M[5,5] = 1
# <10x10 sparse matrix of type '<type 'numpy.float64'>'
#   with 2 stored elements in LInked List format>

dok also works. csr suggests using lil. 'coo' can't be set this way. Once filled it is easy to convert to another format.

like image 70
hpaulj Avatar answered Sep 23 '22 18:09

hpaulj