Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit from scipy.sparse.csr_matrix class

I want to augment the scipy.sparse.csr_matrix class with a few methods and replace a few others for personal use. I am making a child class which inherits from csr_matrix, as such:

class SparseMatrix(sp.csr_matrix):
    def __init__(self, matrix):
        super(type(self), self).__init__(matrix)

This won't work though, throwing:

AttributeError: toSpa not found

Could you please explain to me what I'm doing wrong?

like image 662
Jimmy C Avatar asked Jul 01 '14 10:07

Jimmy C


1 Answers

Somewhere in the SciPy Sparse Matrix implementation the first three letters of the class name are used to define a method that will do the transformations among the different sparse matrix types (see this thread). Therefore, you have to implement using a name like:

import numpy as np
from scipy.sparse import csr_matrix

class csr_matrix_alt(csr_matrix):
    def __init__(self, *args, **kwargs):
        super(csr_matrix_alt, self).__init__(*args, **kwargs)

s = csr_matrix_alt(np.random.random((10, 10)))
print(type(s))
#<class '__main__.csr_matrix_alt'>

Other names like csr_mymatrix, csr_test and so forth would be possible...

like image 119
Saullo G. P. Castro Avatar answered Oct 08 '22 23:10

Saullo G. P. Castro