【发布时间】:2021-05-30 04:39:59
【问题描述】:
我正在尝试使用 Map-reduce 程序计算文件中每个字母出现的概率。
我正在使用以下框架进行 map-reduce。 1 个映射器来映射所有字符,例如 ('a',1)。 1个组合器来计算每个字符的出现总数。 1 个减速器来计算平均值。
但是,我无法计算减速器中的平均值。所以,我添加了一个虚拟字符,每当映射器映射一个新字符时,它就会写入一次。
这个虚拟字符代表字符的总数,我不知道如何在reducer中访问它并将所有其他值除以总数。
例如,以下是组合器的输出。
# 10
a 2
b 2
c 2
d 4
我尝试了 1 个减速器,但没有输出。
我特别需要知道必须写在reducer中的逻辑。
public void reduce(Text key, Iterable<DoubleWritable> values, Context context)
throws IOException, InterruptedException {
int wordCount = 0;
double total = 1;
System.out.println("In Reducer now!");
double avg = 0;
total = values.iterator().next().get();
avg = values.get() / total;
context.write(key, new DoubleWritable(avg));
}
上面的代码没有在输出上写任何东西。
映射器
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String s = value.toString();
char[] arrayofChar = s.toCharArray();
for (char ch : arrayofChar) {
System.out.print(ch);
if (Character.isLetter(ch)) {
context.write(new Text(String.valueOf(ch)), new DoubleWritable(1));
context.write(new Text("#"), new DoubleWritable(1));
}
}
}
组合器
public void reduce(Text key, Iterable<DoubleWritable> values, Context context)
throws IOException, InterruptedException {
double total = 0;
System.out.println("In Combiner now!");
for (DoubleWritable value : values) {
total += value.get();
}
context.write(key, new DoubleWritable(total));
}
【问题讨论】:
-
您是否尝试运行您的代码?您必须提供有关使用 id 的对象的更多信息:“values”变量、DoubleWritable 类...
-
我已经为 Reducer、Combiner 和 Mapper 添加了代码。
标签: java hadoop mapreduce average reducers