1 描述
假定有一个n*n的矩阵M,其第i行第j列的元素记为。假定有一个n维向量v,其第j个元素记为。于是,矩阵M和向量v的乘积结果是一个n维向量x,其第i个元素为
如:
要求输入:向量为(2,3,4)
11 22 33 33 44 55 66 77 88
输出:
0 220 1 418 2 715
2 实现思路
假如这里n很大,但还没有大到向量v不足以放入内存的地步。将矩阵M存放在一个文件中,向量v作为常量数组放在程序中。那么我们便可以从矩阵元素在文件中的位置确定该元素的行列下标。同样,v向量的元素,可以通过数组下标获取该元素的行列下标。
Map函数:
对矩阵元素,Map任务会产生键值对(i,)。因此,计算的所有n个求和项的键值都相同。
Reduce函数:
Reduce任务将所有与给定键i关联的值相加即可得到(i,)。
逻辑图:
3 代码实现
public class MatrixVectorCompute { public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> { private Text lineNumber = new Text(); // 矩阵行序号 private static int i = 0; private final static int[] vector = {2, 3, 4}; // 向量值 public void map(Object key, Text value, Context context) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(value.toString()); int j = 0; // 向量序号 lineNumber.set(i + ""); while (itr.hasMoreTokens()) { int result = vector[j] * Integer.parseInt(itr.nextToken()); IntWritable one = new IntWritable(result); context.write(lineNumber, one); j ++; } i ++; } } public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> { private IntWritable result = new IntWritable(); public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = new Job(conf, "word count11"); job.setJarByClass(MatrixVectorCompute.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path("input")); FileOutputFormat.setOutputPath(job, new Path("output")); System.exit(job.waitForCompletion(true) ? 0 : 1); } }