实现一个稀疏矩阵乘法,支持链式操作

实现稀疏矩阵乘法并支持链式操作可以通过创建一个稀疏矩阵类来完成。这个类需要支持矩阵乘法运算,并且返回的结果仍然是一个稀疏矩阵对象,以便可以继续进行链式操作。以下是一个简单的Python实现:

pythonCopy Codeclass SparseMatrix:    def __init__(self, data=None, shape=None):        """
        初始化稀疏矩阵
        :param data: 字典表示的非零元素 {(i, j): value}
        :param shape: 矩阵的形状 (rows, cols)
        """
        self.data = data if data is not None else {}
        self.shape = shape if shape is not None else (0, 0)
        self._validate_shape()    def _validate_shape(self):        """验证所有索引是否在形状范围内"""
        if not all(0 <= i < self.shape[0] and 0 <= j < self.shape[1] for i, j in self.data.keys()):            raise ValueError("索引超出矩阵范围")    @staticmethod
    def from_dense(dense_matrix):        """从密集矩阵创建稀疏矩阵"""
        data = {}
        shape = (len(dense_matrix), len(dense_matrix[0]) if dense_matrix else 0)        for i, row in enumerate(dense_matrix):            for j, value in enumerate(row):                if value != 0:
                    data[(i, j)] = value        return SparseMatrix(data, shape)    def __matmul__(self, other):        """矩阵乘法操作"""
        if self.shape[1] != other.shape[0]:            raise ValueError("矩阵维度不匹配")
        result_data = {}
        result_shape = (self.shape[0], other.shape[1])        # 转换其他矩阵为字典表示(如果不是稀疏矩阵)
        other_data = other.data if isinstance(other, SparseMatrix) else {
            (i, j): val for i, row in enumerate(other.to_dense())            for j, val in enumerate(row)
        }        # 执行乘法
        for i in range(self.shape[0]):            for k in range(self.shape[1]):                if (i, k) not in self.data:                    continue
                for j in range(other.shape[1]):                    if (k, j) in other_data:                        if (i, j) in result_data:
                            result_data[(i, j)] += self.data[(i, k)] * other_data[(k, j)]                        else:
                            result_data[(i, j)] = self.data[(i, k)] * other_data[(k, j)]        return SparseMatrix(result_data, result_shape)    def to_dense(self):        """将稀疏矩阵转换为密集矩阵"""
        dense = [[0] * self.shape[1] for _ in range(self.shape[0])]        for (i, j), value in self.data.items():
            dense[i][j] = value        return dense    def __str__(self):        """打印矩阵"""
        dense = self.to_dense()        return '\n'.join([' '.join(map(str, row)) for row in dense])# 示例使用A_dense = [
    [1, 0, 0],
    [0, 0, 2],
    [3, 0, 0]
]
B_dense = [
    [0, 4, 0],
    [5, 0, 0],
    [0, 0, 6]
]
A = SparseMatrix.from_dense(A_dense)
B = SparseMatrix.from_dense(B_dense)# 链式操作C = A @ B @ SparseMatrix.from_dense([[1, 0], [0, 1], [0, 0]])  # 示例链式乘法print("结果矩阵:")print(C)

代码说明:

  1. 稀疏矩阵表示‌:使用字典存储非零元素,键为元组 (i, j)表示矩阵位置,值为对应的非零元素。
  2. 矩阵乘法‌:实现了 __matmul__方法,支持 @运算符进行矩阵乘法。
  3. 链式操作‌:由于 __matmul__方法返回一个新的 SparseMatrix对象,因此支持链式调用。
  4. 密集矩阵转换‌:提供 to_dense方法将稀疏矩阵转换为密集矩阵,便于验证和打印。
  5. 从密集矩阵创建‌:提供 from_dense静态方法,方便从密集矩阵创建稀疏矩阵。

这种实现方式在处理大规模稀疏矩阵时能有效节省内存,并支持灵活的链式操作。


http://xuexi.liyintong.com

http://xuexi.naqimai.cn

http://xuexi.kucedu.cn

http://xuexi.yueluyan.cn

http://xuexi.huayuke.cn

http://xuexi.haizichu.cn

http://xuexi.yawanmei.cn

http://xuexi.biaolele.cn

http://xuexi.shenhebu.cn

http://xuexi.zimeiren.cn

http://xuexi.qishouka.cn

http://xuexi.ruanding.cn

http://xuexi.xjhsdsc.cn

http://xuexi.itoren.cn

http://xuexi.iseebest.cn

http://xuexi.bndaye.cn

http://xuexi.rustler.cn

http://xuexi.excelta.cn

http://xuexi.diaolift.cn

http://xuexi.jxpfbyjs.cn

http://xuexi.banans.cn

http://xuexi.aspira.cn

http://xuexi.bxhqw.cn

http://xuexi.pudiweng.cn

http://xuexi.tingbu.cn

http://xuexi.ouhei.cn

http://xuexi.huiha.cn

http://xuexi.miuling.cn

http://xuexi.podang.cn

http://xuexi.fenkun.cn

http://xuexi.liangran.cn

http://xuexi.zouliu.cn

http://xuexi.xuhou.cn

http://xuexi.kuopao.cn

http://xuexi.lunkai.cn

http://xuexi.zhaiti.cn

http://xuexi.fogei.cn

http://xuexi.gengluo.cn

http://xuexi.wadiao.cn

http://xuexi.hunjun.cn

http://xuexi.huanken.cn

http://xuexi.chuancong.cn

http://xuexi.buzun.cn

http://xuexi.zhuozou.cn

http://xuexi.lazai.cn

http://xuexi.zengle.cn

http://xuexi.suidun.cn

http://xuexi.zhaojunji.cn

http://xuexi.huihuoban.cn

http://xuexi.wanjiahua.cn

http://xuexi.conglinyi.cn

http://xuexi.henyoupin.cn

http://xuexi.wuwenkang.cn

http://xuexi.tujiachen.cn

http://xuexi.zilaoweng.cn

http://xuexi.baolema.cn

http://xuexi.shumeilin.cn

http://xuexi.anhetong.cn

http://xuexi.wenjishu.cn

http://xuexi.kansande.cn

http://xuexi.yueshijie.cn

http://xuexi.tihujiu.cn

http://xuexi.huatoutou.cn

http://xuexi.xiaolaige.cn

http://xuexi.huguangu.cn

http://xuexi.lvdate.cn

http://xuexi.kesini.cn

http://xuexi.soubianlu.cn

http://xuexi.fuenbu.cn

http://xuexi.liuyakun.cn

http://xuexi.zouyizou.cn

http://xuexi.juyingba.cn

http://xuexi.namahu.cn

http://xuexi.dadudu.cn

http://xuexi.xuewenzi.cn

http://xuexi.lazhuyong.cn

http://xuexi.aizishu.cn

http://xuexi.nianjiepo.cn

http://xuexi.baisuijie.cn

http://xuexi.wanyuecun.cn

http://xuexi.shoupashu.cn

http://xuexi.hetongmei.cn

http://xuexi.ouenming.cn

http://xuexi.qianyiduo.cn

http://xuexi.yidingzhi.cn

http://xuexi.zouyuming.cn

http://xuexi.mofaya.cn

http://xuexi.hexiangru.cn

http://xuexi.quyouban.cn

http://xuexi.mingyinsi.cn

http://xuexi.junepan.cn

http://xuexi.qiyuehong.cn

http://xuexi.ledatong.cn

http://xuexi.chenqinga.cn

http://xuexi.ebuyun.cn

http://xuexi.gayijiu.cn

http://xuexi.liqinge.cn

http://xuexi.liubawan.cn

http://xuexi.huabaohan.cn

http://xuexi.aiguandan.cn

http://xuexi.judoubang.cn

http://xuexi.huachenyu.cn

http://xuexi.hexiaolia.cn

http://xuexi.feiyuxuan.cn

http://xuexi.zhenwasai.cn

http://xuexi.maoweilai.cn

http://xuexi.yunyuewei.cn

http://xuexi.kemensen.cn

http://xuexi.anxinyuan.cn

http://xuexi.deyisheji.cn

http://xuexi.ximaguohe.cn

http://xuexi.gewukeji.cn

http://xuexi.rehuang.cn

请使用浏览器的分享功能分享到微信等