如何用Hadoop计算平均值

2019-03-28 12:59|来源: 网络

如何用Hadoop计算平均值

数据

data.txt
a 2
a 3
a 4
b 5
b 6
b 7

代码

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

public class Average {

 public static class TokenizerMapper extends
   Mapper<Object, Text, Text, Text> {

  private final static IntWritable one = new IntWritable(1);
  private Text word = new Text();

  public void map(Object key, Text value, Context context)
    throws IOException, InterruptedException {
   StringTokenizer itr = new StringTokenizer(value.toString());
   while (itr.hasMoreTokens()) {
    word.set(itr.nextToken());
    if (itr.hasMoreTokens()) {
     context.write(word, new Text(itr.nextToken() + ",1"));
    }
   }
  }
 }

 static class AverageCombine extends Reducer<Text, Text, Text, Text> {
  public void reduce(Text key, Iterable<Text> values, Context context)
    throws IOException, InterruptedException {
   int sum = 0, cnt = 0;
   for (Text val : values) {
    String[] s1 = val.toString().split(",");
    sum += Integer.parseInt(s1[0]);
    cnt += Integer.parseInt(s1[1]);
   }
   String s;
   System.out.println("Combine" + (s = new String(sum + "," + cnt)));
   context.write(key, new Text(new String(sum + "," + cnt)));
  }
 }

 static class AverageReducer extends
   Reducer<Text, Text, Text, DoubleWritable> {
  public void reduce(Text key, Iterable<Text> values, Context context)
    throws IOException, InterruptedException {
   int sum = 0, cnt = 0;
   for (Text val : values) {
    String[] s = val.toString().split(",");
    sum += Integer.parseInt(s[0]);
    cnt += Integer.parseInt(s[1]);
   }
   String s;
   System.out.println("reduce"
     + (s = new String(key + "," + (sum * 1.0 / cnt))));
   context.write(key, new DoubleWritable(sum * 1.0 / cnt));
  }
 }

 public static void main(String[] args) throws Exception {
  Configuration conf = new Configuration();
  String[] otherArgs = args;
  if (otherArgs.length != 2) {
   System.err.println("Usage:Data Average <in> <out>");
   System.exit(2);
  }
  Job job = new Job(conf, "Data Average");
  job.setJarByClass(Average.class);
  job.setMapperClass(TokenizerMapper.class);
  job.setCombinerClass(AverageCombine.class);
  job.setReducerClass(AverageReducer.class);
  job.setOutputKeyClass(Text.class);
  job.setOutputValueClass(Text.class);
  FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
  FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
  System.exit(job.waitForCompletion(true) ? 0 : 1);
 }
}

执行

bin/hadoop jar Average.jar Average data.txt out

结果

a 3.0
b 6.0

更多Hadoop相关信息见Hadoop 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=13

相关问答

更多
  • 动物园包裹中的滚动平均值/最大/中位数(rollmean) TTR中的移动平均值 在预测中 Rolling Means/Maximums/Medians in the zoo package (rollmean) MovingAverages in TTR ma in forecast
  • 对于一个简单,快速的解决方案,在一个循环中完成整个事情,没有依赖关系,下面的代码工作得很好。 mylist = [1, 2, 3, 4, 5, 6, 7] N = 3 cumsum, moving_aves = [0], [] for i, x in enumerate(mylist, 1): cumsum.append(cumsum[i-1] + x) if i>=N: moving_ave = (cumsum[i] - cumsum[i-N])/N #c ...
  • 我不知道标准库中有什么。 但是,您可以使用以下内容: def mean(numbers): return float(sum(numbers)) / max(len(numbers), 1) >>> mean([1,2,3,4]) 2.5 >>> mean([]) 0.0 在numpy中,有numpy.mean() 。 I am not aware of anything in the standard library. However, you could use something like ...
  • 你想要这个: MIN(ts1, ts2) + ABS(ROUND((ts1-ts2)/2)) ? You would like to have this: MIN(ts1, ts2) + ABS(ROUND((ts1-ts2)/2)) ?
  • 将cAll声明为Double以避免溢出。 Dim cAll as Double 接着 cAll += Convert.ToDouble(m(i).Count) * Convert.ToDouble(m(i).Value) 双范围高达约±1.7×10 ^ 308。 Declare cAll as Double to avoid an overflow. Dim cAll as Double and then cAll += Convert.ToDouble(m(i).Count) * Convert.T ...
  • 我会做的是以下几点: double mean(double arr[], int len) { double total = 0; for(int i = 0; i < len; i++) total += arr[i]; return total / len; } 然后你像这样从main调用它: double mean2 = mean(numbers, numValue); what I would do is the following: double mea ...
  • 您缺少group by子句 select c.university_name, c.country, AVG(c.world_rank) as AvgC, AVG(s.world_rank) as AvgS, AVG(t.world_rank) as AvgT, (AvgC+AvgS+AvgT)/3 as TotalAvg from cwur c join shanghai s on (c.university_name ...
  • 您可以使用findInterval和tapply 。 set.seed(1) vec = rnorm(1000) qs <- quantile(vec, seq(from = 0, to = 1, by = 0.2)) tapply(vec, findInterval(vec, qs), mean) # 1 2 3 4 5 6 # -1.46746 -0.54260 -0.02399 0.54492 1.41894 ...
  • 使用Linq ... Dim average As Double = y.Average() 你可以用Linq做的另一件事是从平均数中排除某些值。 以这个例子为例,它将myNumbers() 9个项目设置为10,然后将第10个项目设置为零。 我使用Linq首先筛选大于零的数字,然后执行Average聚合。 Dim myNumbers(9) As Double For i As Integer = 0 To 8 Step 1 myNumbers(i) = 10 Next i myNumbers(9 ...
  • 要计算实际平均值而不将其向下舍入,请使用float。 你还需要一对额外的括号,否则它将是y / 2而不是(x + y / 2)。 至于那个错误,我不确定你在Listofvalues列表中使用的是什么作为输入,以下对我来说很好。 Averagelist = [] Listofvalues1 = [1,2] Listofvalues2 = [6,7] for i, x in enumerate(Listofvalues1): for j, y in enumerate(Listofvalues2): ...