在我的 Reducer 代码中,我使用此代码片段对值求和:
for(IntWritable val : values) {
sum += val.get();
}
由于上面提到的给了我预期的输出,我尝试将代码更改为:
for(IntWritable val : values) {
sum += 1;
}
谁能解释一下当我在 reducer 中使用 sum += 1
而不是 sum += val.get()
时有什么不同?为什么它给我相同的输出?它与 Combiner 有什么关系吗,因为当我使用与 Combiner 相同的 reducer 代码时,类输出不正确,所有单词都显示计数为 1。
映射器代码:
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer token = new StringTokenizer(line);
while(token.hasMoreTokens()) {
word.set(token.nextToken());
context.write(word, new IntWritable(1));
}
}
reducer 代码:
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for(IntWritable val : values) {
//sum += val.get();
sum += 1;
}
context.write(key, new IntWritable(sum));
}
司机代码:
job.setJarByClass(WordCountWithCombiner.class);
//job.setJobName("WordCount");
job.setMapperClass(WordCountMapper.class);
job.setCombinerClass(WordCountReducer.class);
job.setReducerClass(WordCountReducer.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
输入-“成为或不成为”
预期输出 - (be,2) , (to,2) , (or,1) , (not,1)
但我得到的输出是 - (be,1) , (to,1) , (or,1) , (not,1)
最佳答案
Can anyone please explain what is the difference it makes when I use
sum += 1
in the reducer rather thansum += val.get()
?
两条语句都在进行加法运算。首先,您要计算 for-loop
运行了多少次。在后面,您实际上是在对给定 key
的每个 val
对象返回的 int
值进行求和运算。
Why does it give me the same output? Does it have anything to do with Combiner
答案是是的。这是因为 Combiner
。
现在让我们看看您传递的输入,这将只实例化一个 Mapper
。 Mapper
的输出是:
(to,1), (be,1), (or,1), (not,1), (to,1), (be,1)
当这进入 Combiner
时,这与 Reducer
本质上是相同的逻辑。输出将是:
(be,2) , (to,2) , (or,1) , (not,1)
现在 Combiner
的上述输出转到 Reducer
并且它将执行您定义的求和操作。因此,如果您的逻辑是 sum += 1
,那么输出将是:
(be,1) , (to,1) , (or,1) , (not,1)
但是如果您的逻辑是 sum += val.get()
那么您的输出将是:
(be,2) , (to,2) , (or,1) , (not,1)
我希望你现在明白了。 Combiner
和 Reducer
的逻辑是一样的,但是它们要处理的输入是不同的。
关于Hadoop - 经典 MapReduce 字数统计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32810343/