-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMM3.java
91 lines (66 loc) · 2.89 KB
/
MM3.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
public class MM3 {
private static class MM3Mapper extends Mapper<LongWritable, Text, LongWritable, Text> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
int k = context.getConfiguration().getInt("k", -1);
double[] ai = new double[k];
String[] values = value.toString().split("\\t")[1].split(",");
for (int j = 0; j < k; j++) {
ai[j] = Double.parseDouble(values[j]);
}
for (int j = 0; j < k; j++) {
LongWritable newKey = new LongWritable(j + 1);
StringBuilder result = new StringBuilder();
for (int l = 0; l < k; l++) {
result.append(ai[j] * ai[l]);
if (l < k - 1) {
result.append(",");
}
}
context.write(newKey, new Text(result.toString()));
}
}
}
private static class MM3Reducer extends Reducer<LongWritable, Text, LongWritable, Text> {
@Override
protected void reduce(LongWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
int k = context.getConfiguration().getInt("k", -1);
double[] result = new double[k];
for (Text value : values) {
String[] ai = value.toString().split(",");
for (int j = 0; j < k; j++) {
result[j] += Double.parseDouble(ai[j]);
}
}
StringBuilder res = new StringBuilder();
for (int i = 0; i < k; i++) {
res.append(result[i]);
if (i < k) {
res.append(",");
}
}
context.write(key, new Text(res.toString()));
}
}
private Configuration configuration;
private String inputPath;
private String outputPath;
public MM3(Configuration configuration, String inputPath, String outputPath) {
this.configuration = configuration;
this.inputPath = inputPath;
this.outputPath = outputPath;
}
public void run() throws IOException, ClassNotFoundException, InterruptedException {
Job job = Job.getInstance(configuration, "com.lsdp.matrixmultiplication.MM3");
job.setJarByClass(MRNMF.class);
FileInputFormat.addInputPath(job, new Path(inputPath));
FileOutputFormat.setOutputPath(job, new Path(outputPath));
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
job.setMapOutputKeyClass(LongWritable.class);
job.setMapOutputValueClass(Text.class);
job.setMapperClass(MM3Mapper.class);
job.setReducerClass(MM3Reducer.class);
job.waitForCompletion(true);
}
}