python:稀疏矩阵存储,相乘,转置

稀疏矩阵存储,相乘,转置

  • 存储:利用三个列表进行存储

  • 相乘:这里只写了稀疏矩阵与全矩阵的乘法,并返回全矩阵

  • 转置:返回稀疏矩阵

  • 这里默认稀疏矩阵较大例如(5000X5000)而全矩阵很小(5000X1)

import sys
import numpy as np

class TSMatrix:
    def __init__(self, rows, cols, value, shape):
        self.rows = rows
        self.cols = cols
        self.value = value
        [self.m, self.n] = shape
    
    def Shape(self):
        print("Rows:",self.m,"  Cols:",self.n)
    
    def Dot(self, b):
        #Sparse matrix multiplied by full matrix, return full matrix
        bm,bn = b.shape
        if self.n != bm:
            print("Dimension mismatch")
            sys.exit(0)
        
        a = np.zeros([self.m, bn])
        truthnum = len(self.rows)
        for n in range(truthnum):
            i = self.rows[n]
            j = self.cols[n]
            value = self.value[n]
            for m in range(bn):
                a[i,m] += value*b[j,m]
        return a
    
    def T(self):
        #Sparse matrix transpose
        return TSMatrix(self.cols, self.rows, self.value, [self.m, self.n])
    
    def Full(self):
        #Convert to full matrix and output
        if self.m * self.n > 12800000:
            print("The full matrix is too large to display")
            sys.exit(0)
        if self.m < max(self.rows) or self.n < max(self.cols):
            print("Incomplete display")
            sys.exit(0)
            
        FMatrix = np.zeros([self.m, self.n])
        for n in range(len(self.rows)):
            i = self.rows[n]
            j = self.cols[n]
            value = self.value[n]
            FMatrix[i,j] += value
        return FMatrix

if __name__=='__main__':
    #test
    row = [0, 1, 2, 2]
    col = [0, 1, 2, 3]
    data = [1, 2, 3, 4]
    Mtest = TSMatrix(row,col,data,[5,5])
    #Full
    print(Mtest.Full())
    #Shape
    Mtest.Shape()
    #Dot
    b = np.ones([5,1])
    print(Mtest.Dot(b))
    #Transpose
    print(Mtest.T().Full())

你可能感兴趣的:(python,矩阵)