I would like to apply map-reduce to deal with matrix multiplication in python with Hadoop. The goal is to calculate A * B. The output should be similar with the input.
Input are two matrix A and B formate looks like this:
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 means the index is A(0,0) and the value is 0.0, same for B.
This is my map function:
import sys
import string
import numpy
#Split line into array of entry data
entry = line.split(",")
# Set row, column, and value for this entry
row = int(entry[1])
col = int(entry[2])
value = float(entry[3])
#If this is an entry in matrix A...
if (entry[0] == "A"):
#Generate the necessary key-value pairs
for i in range(col):
print('<{}{},{} {} {}}>'.format(row,i,A,col,value))
#Otherwise, if this is an entry in matrix B...
else:
#Generate the necessary key-value pairs
for i in range(row):
print('<{}{},{} {} {}}>'.format(i,col,B,row,value))
I could like to know how to write the reduce function. Here is the frame that I will work with:
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)
To run these two functions, i will test them with a small test dataset with the following code:
cat smalltest.txt | python src/map.py 2 3 | sort -n | python src/reduce.py 5
Map gives the output of , then use sort -n
to sort the keys, so I will use the reducer to deal with the matrix calculation. My confusion is in writing the reducer function.