Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't understand scipy.sparse.csr_matrix example

Tags:

python

scipy

I can't wrap my head around csr_matrix examples in scipy documentation: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html

Can someone explain how this example work?

>>> row = np.array([0, 0, 1, 2, 2, 2])
>>> col = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
array([[1, 0, 2],
       [0, 0, 3],
       [4, 5, 6]])

I believe this is following this format.

csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])

where data, row_ind and col_ind satisfy the relationship a[row_ind[k], col_ind[k]] = data[k].

What is a here?

like image 485
aerin Avatar asked Nov 11 '18 23:11

aerin


2 Answers

row = np.array([0, 0, 1, 2, 2, 2])
col = np.array([0, 2, 2, 0, 1, 2])
data = np.array([1, 2, 3, 4, 5, 6])

from the above arrays;

for k in 0~5
a[row_ind[k], col_ind[k]] = data[k]

                  a 
row[0],col[0] = [0,0] = 1 (from data[0])  
row[1],col[1] = [0,2] = 2 (from data[1])  
row[2],col[2] = [1,2] = 3 (from data[2])  
row[3],col[3] = [2,0] = 4 (from data[3])  
row[4],col[4] = [2,1] = 5 (from data[4])  
row[5],col[5] = [2,2] = 6 (from data[5])

so let's arrange matrix 'a' in shape(3X3)

a
   0  1  2
0 [1, 0, 2]  
1 [0, 0, 3]  
2 [4, 5, 6]
like image 193
pplkjh Avatar answered Sep 22 '22 01:09

pplkjh


This is a sparse matrix. So, it stores the explicit indices and values at those indices. So for example, since row=0 and col=0 corresponds to 1 (the first entries of all three arrays in your example). Hence, the [0,0] entry of the matrix is 1. And so on.

like image 33
Rohit Pandey Avatar answered Sep 22 '22 01:09

Rohit Pandey