python 实现矩阵相乘
来源:互联网 发布:路由器编程器 编辑:程序博客网 时间:2024/04/30 08:32
优势在于,矩阵的数据组织方式适合分布式计算
# coding:utf-8__author__ = 'taohao'import randomclass Matrix(object): def build_matrix_a(self, row, col): """ matrix: 1 0 2 -1 3 1 turn to ->Matrix name,rowNum,colNum,elementNum for example: A,1,1,1 A,1,2,1 A,1,3,2 A,2,1,-1 A,2,2,3 A,2,3,1 save the matrix to file for hadoop to read data from file :return: """ fd = open('MatrixA.txt', 'w') num = '' for i in range(row): for j in range(col): num += ',' + str(i+1) + ',' + str(j+1) + ',' num += str(random.randint(1, 10)) fd.write('A' + num + '\n') num = '' fd.close() def build_matrix_b(self, row, col): """ the same as def build_matrix_a :param row: :param col: :return: """ fd = open('MatrixB.txt', 'w') num = '' for i in range(row): for j in range(col): num += ',' + str(i+1) + ',' + str(j+1) + ',' num += str(random.randint(1, 10)) fd.write('B' + num + '\n') num = '' fd.close() def matrix_multify(self, row, col): result = {} matrix_a = {} matrix_b = {} fd_a = open("MatrixA.txt", 'r') fd_b = open('MatrixB.txt', 'r') for line_a in fd_a: line_item = line_a.rstrip('\n').split(r',') if line_item[1] not in matrix_a: matrix_a[line_item[1]] = [] matrix_a[line_item[1]].append(line_item[3]) for line_b in fd_b: line_item_b = line_b.rstrip('\n').split(r',') if line_item_b[2] not in matrix_b: matrix_b[line_item_b[2]] = [] matrix_b[line_item_b[2]].append(line_item_b[3]) fd_a.close() fd_b.close() # print matrix_a # print matrix_b for i in range(row): row_num = matrix_a.get(str(i+1)) # print 'row', row_num for j in range(col): col_num = matrix_b.get(str(j+1)) # print 'col', col_num k = 0 while k < len(row_num): if str(i+1)+str(j+1) not in result: result[str(i+1)+str(j+1)] = 0 result[str(i+1)+str(j+1)] += int(row_num[k]) * int(col_num[k]) k += 1 print result # output the resultif __name__ == '__main__': rowA = 4 colA = 2 rowB = 2 colB = 3 matrix = Matrix() matrix.build_matrix_a(rowA, colA) matrix.build_matrix_b(rowB, colB) matrix.matrix_multify(rowA, colB)
0 0
- Python实现矩阵相乘
- python 实现矩阵相乘
- Python计算矩阵相乘
- MapReduce实现矩阵相乘
- java实现矩阵相乘
- mapreduce实现矩阵相乘
- Hadoop 实现矩阵相乘
- MapReduce实现矩阵相乘
- mpi实现矩阵相乘
- Java实现矩阵相乘
- 矩阵相乘实现
- MapReduce实现矩阵相乘
- 二维矩阵实现矩阵相乘
- 170525 python 矩阵按行按列相乘
- C语言实现矩阵相乘
- 矩阵相乘--高效实现方法
- hadoop矩阵相乘简单实现
- cublasSgemm实现矩阵的相乘
- 通达OA web页面与精灵显示内容更新后不一致的问题
- mobiscroll破解方法
- Java开发中的23种设计模式详解
- 2012年12月21日SAT数学每日一题
- ios_swift开发资源整理
- python 实现矩阵相乘
- RedHat5安装glib过程记录
- Android中几种常用的Dialog
- linux下分析Java程序内存汇总
- jQuery.Validate验证库
- Gauss-Newton algorithm
- 初探单点登录 SSO
- myeclipse将java项目转换成web项目,导出war包
- 学习笔记: 享元模式和值对象