• 稀疏矩阵相乘-Python版


                                          稀疏矩阵相乘-Python版

    Given two sparse matrices A and B, return the result of AB.

    You may assume that A's column number is equal to B's row number.

    Example:

    1. A = [
    2. [ 1, 0, 0],
    3. [-1, 0, 3]
    4. ]
    5. B = [
    6. [ 7, 0, 0 ],
    7. [ 0, 0, 0 ],
    8. [ 0, 0, 1 ]
    9. ]
    10. | 1 0 0 | | 7 0 0 | | 7 0 0 |
    11. AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
    12. | 0 0 1 |

    使用传统的矩阵相乘的算法肯定会处理大量的0乘0的无用功,所以我们适当的优化算法,我们知道一个 i x k 的矩阵A乘以一个 k x j 的矩阵B会得到一个 i x j 大小的矩阵C,那么我们来看结果矩阵中的某个元素C[i][j]是怎么来的,起始是A[i][0]*B[0][j] + A[i][1]*B[1][j] + ... + A[i][k]*B[k][j],那么为了不重复计算0乘0,我们首先遍历A数组,要确保A[i][k]不为0,才继续计算,然后我们遍历B矩阵的第k行,如果B[K][J]不为0,我们累加结果矩阵res[i][j] += A[i][k] * B[k][j]; 这样我们就能高效的算出稀疏矩阵的乘法,参见代码如下:

    1. # -*- coding: utf-8 -*-
    2. """
    3. Created on Sun Sep 02 15:10:34 2018
    4. @author: Administrator
    5. """
    6. def SparseMatrixMultiply(A, B):#减少计算次数
    7. res = [[0 for i in range(len(B[0]))] for j in range(len(A))]
    8. for i in range(len(A)):
    9. for j in range(len(A[0])):
    10. if A[i][j] != 0:#non-zero
    11. for k in range(len(B[0])):
    12. if B[j][k] != 0:#non-zero
    13. res[i][k] += A[i][j] * B[j][k]
    14. return res
    15. if __name__ == '__main__':
    16. A = [[1,0,0],[-1,0,3]]
    17. B = [[7,0,0],[0,0,0],[0,0,1]]
    18. result = SparseMatrixMultiply(A, B)
    19. print(result)

    三元组方法

    typedef struct NODE{ //定义稀疏矩阵结点       
     int i;       //行
     int j;       //列
     int data;   //值
    } Node;
    typedef struct MATRIX{ //定义稀疏矩阵(可以快速访问)       
     int mu, nu, tu;      // mu为矩阵行数,nu为矩阵列数,tu为矩阵中非零元素的个数
     Node matrix[MAXSIZE+1];       
     int rpos[MAXR+1];
    } Matrix; 

    算法时间复杂度为:O(A->tu*B->tu/B->mu)

    此外还有十字链表法。

    Python科学计算包scipy

    import scipy as sp

    a = sp.sparse.linalg.norm(S, 'fro')

  • 相关阅读:
    MongoDB解析 2XML配置文件
    MongoDB解析 1理论基础
    JAVA GoF设计模式6大设计原则
    Kafka解析1快速入门
    JAVA GoF设计模式 1创建型设计模式
    B/S架构与C/S架构的区别
    【笔记】Oracle使用笔记
    如何通过WinDbg获取方法参数值
    Windows 启动过程
    ubuntu安装leveldb
  • 原文地址:https://www.cnblogs.com/AcceptedLin/p/9778834.html
Copyright © 2020-2023  润新知