2017-07-27 58 views
1

我尝试通过多重继承将我自己的方法和属性添加到稀疏矩阵。但是我发现算术运算符在新类中并没有关闭。如何正确地继承scipy.sparse矩阵?

from scipy.sparse import coo_matrix 
import numpy as np 

class Info(object): 
    def __init__(self, *arg, **args): 
     self.hello = "hello" 
    def say_hello(self): 
     print("hello") 

class A(coo_matrix, Info): 
    def __init__(self, *arg, **args): 
     super(type(self), self).__init__(*arg, **args) 

a = A(np.random.randint(2, size=(3,3))) 
print("type of a: ",type(a)) 
a.say_hello() 
b = 2*a 
print("type of b: ",type(b)) 
+1

这可能会很棘手。不同的稀疏'格式'被实现为不同的类。每个类都有一个'__init__',但也有转换为其他格式的方法。例如,大多数计算都是用'csr'(或'csc')格式完成的。首先,我建议研究一种主要用作输入法的格式,看看它如何与其他格式相互作用,例如'dia_matrix','dok_matrix','bsr_matrix'或'lil_matrix'。 – hpaulj

回答

0

如文档scipy.sparse.coo_matrix所述,它不直接支持算术运算。显然,如果你仍然尝试做算术运算,它会自动转换为csr_matrix。这就是为什么您的b不再是​​3210类型。不过,如果你不是直接做

class A(csr_matrix, Info): 
    ... 

这对算术适当的方法,因此没有转换成另一种格式的作品继承形式,例如,csr_matrix

+0

但是转置'csr'矩阵是一个'csc'矩阵,而'csr'上的许多数学运算产生一个密集的数组或矩阵 – hpaulj

+0

所以你有什么意思?不使用'csr'矩阵?为什么它与转置有关是吗?如果'csc'是算法的更好选择,那么当然你也可以继承它。 – obachtos