用Hadoop实现python中矩阵乘法的MapReduce求解

2024-04-26 18:28:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用mapreduce来处理python中的矩阵乘法和Hadoop。目标是计算A*B。输出应该与输入类似。在

输入是两个矩阵A和B格式如下:

A,0,0,0.0
A,0,1,1.0
...
A,1,3,8.0
A,1,4,9.0
B,0,0,0.0
B,0,1,1.0
...
B,4,0,12.0
B,4,1,13.0

A,0,0,0.0表示索引是A(0,0),值是0.0,B也是一样

这是我的地图功能:

^{pr2}$

我想知道如何写reduce函数。 以下是我将使用的框架:

import sys
import string
import numpy

#number of columns of A/rows of B
n = int(sys.argv[1])

#Create data structures to hold the current row/column values (if needed; your code goes here)



currentkey = None

# input comes from STDIN (stream data that goes to the program)
for line in sys.stdin:

        #Remove leading and trailing whitespace
        line = line.strip()

        #Get key/value
        key, value = line.split('\t',1)

        #Parse key/value input (your code goes here)

    #If we are still on the same key...
    if key==currentkey:

            #Process key/value pair (your code goes here)


    #Otherwise, if this is a new key...
    else:
            #If this is a new key and not the first key we've seen
            if currentkey:

                    #compute/output result to STDOUT (your code goes here)

            currentkey = key

            #Process input for new key (your code goes here)

#Compute/output result for the last key (your code goes here)

为了运行这两个函数,我将用一个小的测试数据集测试它们,代码如下:

cat smalltest.txt | python src/map.py 2 3 | sort -n | python src/reduce.py 5

Map给出了的输出,然后使用sort -n对键进行排序,因此我将使用reducer来处理矩阵计算。我的困惑在于写reducer函数。在


Tags: ofthekey函数importyourifhere
2条回答

好吧,我直截了当地说

    lines = [*map(lambda x: x.split(","),strin)]

是一种简化方法,如果lambda函数本身甚至不在具有语法的输入中,那就好像字符串不存在一样 老实说,减少它是你应该感谢的,这个代码(不是苛刻的)是凌乱的,所以我不明白你为什么抱怨自动减少。。在

不确定为什么减少
我的numpy方法(使用一些弦乐/链表/拉链体操)

 strin = '''A,0,0,0.0
A,0,1,1.0
A,1,0,8.0
A,1,1,9.0
B,0,0,0.0
B,0,1,1.0
B,1,0,12.0
B,1,1,13.0'''.split()

lines = [*map(lambda x: x.split(","),strin)]

linesT = [*zip(*lines)]

linesT

[('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'),
 ('0', '0', '1', '1', '0', '0', '1', '1'),
 ('0', '1', '0', '1', '0', '1', '0', '1'),
 ('0.0', '1.0', '8.0', '9.0', '0.0', '1.0', '12.0', '13.0')]

现在我们可以得到数组A,B的数据

^{2}$

相关问题 更多 >