Create A Sparse Matrix

Goal

This post aims to create a sparse matrix in python using following modules:

  • Numpy
  • Scipy

Reference:

  • Scipy Document
  • Chris Albon's blog (I look at his post's title and wrote my own contents to deepen my understanding about the topic.)

Library

In [8]:
import numpy as np
import scipy.sparse

Create a sparse matrix using csr_matrix

CSR stands for "Compressed Sparse Row" matrix

In [9]:
nrow = 10000
ncol = 10000

# CSR stands for "Compressed Sparse Row" matrix
arr_sparse = scipy.sparse.csr_matrix((nrow, ncol))
arr_sparse
Out[9]:
<10000x10000 sparse matrix of type '<class 'numpy.float64'>'
	with 0 stored elements in Compressed Sparse Row format>

Modify elements

In [13]:
arr_sparse[100, 1000] = 10.
arr_sparse
Out[13]:
<10000x10000 sparse matrix of type '<class 'numpy.float64'>'
	with 1 stored elements in Compressed Sparse Row format>

Math Opeartion

In [16]:
# Addition is not supported
arr_sparse + 1
---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-16-db4353ff8482> in <module>
      1 # Addition is not supported
----> 2 arr_sparse + 1

~/anaconda3/envs/py367/lib/python3.6/site-packages/scipy/sparse/base.py in __add__(self, other)
    410                 return self.copy()
    411             # Now we would add this scalar to every element.
--> 412             raise NotImplementedError('adding a nonzero scalar to a '
    413                                       'sparse matrix is not supported')
    414         elif isspmatrix(other):

NotImplementedError: adding a nonzero scalar to a sparse matrix is not supported
In [19]:
arr_sparse - 1
---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-19-d596f7afea6e> in <module>
----> 1 arr_sparse - 1

~/anaconda3/envs/py367/lib/python3.6/site-packages/scipy/sparse/base.py in __sub__(self, other)
    429             if other == 0:
    430                 return self.copy()
--> 431             raise NotImplementedError('subtracting a nonzero scalar from a '
    432                                       'sparse matrix is not supported')
    433         elif isspmatrix(other):

NotImplementedError: subtracting a nonzero scalar from a sparse matrix is not supported
In [17]:
arr_sparse * 2
Out[17]:
<10000x10000 sparse matrix of type '<class 'numpy.float64'>'
	with 1 stored elements in Compressed Sparse Row format>
In [18]:
arr_sparse / 2 
Out[18]:
<10000x10000 sparse matrix of type '<class 'numpy.float64'>'
	with 1 stored elements in Compressed Sparse Row format>

Min & Max

In [26]:
arr_sparse.min()
Out[26]:
0.0
In [27]:
arr_sparse.max()
Out[27]:
10.0

Comments

Comments powered by Disqus