MapReduce 求平均数

该博客介绍了一个使用MapReduce实现的求平均分的程序。Mapper阶段读取包含姓名和成绩的数据,过滤无效记录并输出键值对。Reducer阶段接收Mapper的输出,计算平均分并输出结果。
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.LongWritable;
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.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.lib.partition.HashPartitioner;

import java.io.IOException;

public class Avg {
    private static class AverageMapper extends Mapper<LongWritable, Text, Text, Text> {
        //设置输出的key和value
        private Text outKey = new Text();
        private Text outValue = new Text();

        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context) throws IOException, InterruptedException {
            //获取输入的行
            String line = value.toString();
            //取出无效记录
            if (line == null || line.equals("")) {
                return;
            }
            //对数据进行切分
            String[] splits = line.split("\t");
            //截取姓名和成绩
            String name = splits[0];
            String score = splits[2];
            //设置输出的Key和value
            outKey.set(name);
            outValue.set(score);
            //将结果写出去
            context.write(outKey, outValue);
        }
    }

    public static class AverageReducer extends Reducer<Text, Text, Text, FloatWritable> {
        //定义写出去的Key和value
        private Text name = new Text();
        private FloatWritable avg = new FloatWritable();

        @Override
        protected void reduce(Text key, Iterable<Text> value, Reducer<Text, Text, Text, FloatWritable>.Context context) throws IOException, InterruptedException {
            //定义科目数量
            int courseCount = 0;
            //定义中成绩
            int sum = 0;
            //定义平均分
            float average = 0;

            //遍历集合求总成绩
            for (Text val : value) {
                sum += Integer.parseInt(val.toString());
                courseCount++;
            }

            //求平均成绩
            average = sum / courseCount;

            //设置写出去的名字和成绩
            name.set(key);
            avg.set(average);
            //把结果写出去
            context.write(name, avg);
        }
    }

    private static final String INPUT_PATH = "hdfs://liaozhongmin:9000/average_file";
    // 定义输出路径
    private static final String OUT_PATH = "hdfs://liaozhongmin:9000/out";

    public static void main(String[] args) throws InterruptedException, IOException, ClassNotFoundException {
            // 创建配置信息
            Configuration conf = new Configuration();
            // 创建文件系统
            FileSystem fileSystem = FileSystem.get(conf);
            // 如果输出目录存在,我们就删除
            if (fileSystem.exists(new Path(OUT_PATH))) {
                fileSystem.delete(new Path(OUT_PATH), true);
            }
            // 创建任务
            Job job =Job.getInstance();
            //1.1  设置输入目录和设置输入数据格式化的类
            FileInputFormat.setInputPaths(job, INPUT_PATH);
            job.setInputFormatClass(TextInputFormat.class);
            //1.2  设置自定义Mapper类和设置map函数输出数据的key和value的类型
            job.setMapperClass(AverageMapper.class);
            job.setMapOutputKeyClass(Text.class);
            job.setMapOutputValueClass(Text.class);
            //1.3  设置分区和reduce数量(reduce的数量,和分区的数量对应,因为分区为一个,所以reduce的数量也是一个)
            job.setPartitionerClass(HashPartitioner.class);
            job.setNumReduceTasks(1);
            //1.4  排序
            //1.5  归约
            //2.1  Shuffle把数据从Map端拷贝到Reduce端。
            //2.2  指定Reducer类和输出key和value的类型
            job.setReducerClass(AverageReducer.class);
            job.setOutputKeyClass(Text.class);
            job.setOutputValueClass(FloatWritable.class);
            //2.3  指定输出的路径和设置输出的格式化类
            FileOutputFormat.setOutputPath(job, new Path(OUT_PATH));
            job.setOutputFormatClass(TextOutputFormat.class);
            // 提交作业 退出
            System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
### 使用MapReduce编程实现平均数MapReduce框架下,计算平均值的过程涉及两个主要阶段:`Map` 和 `Reduce`。为了完成这一目标,通常会先通过映射函数处理输入数据集中的每一项记录,将其转换成键值对的形式;之后利用规约函数来聚合这些中间结果,并最终得到所需的统计数据。 #### Map 阶段 对于每一条输入的数据行,map 函数解析该条目并将它转化为一对或多对(key,value),其中key可以是任意标识符(比如"average"),value则是具体的数值加上计数器1表示当前样本的数量。这样做的目的是为了让后续reduce过程能够区分不同类型的统计量以及累积次数信息[^2]。 ```java public class AverageMapper extends Mapper<LongWritable, Text, Text, IntSumPair> { private static final String AVG_KEY = "avg"; @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { int num = Integer.parseInt(value.toString()); context.write(new Text(AVG_KEY), new IntSumPair(num, 1)); } } ``` 这里定义了一个名为`IntSumPair`的类用于存储整型数值及其对应的权重或频次: ```java public class IntSumPair implements WritableComparable<IntSumPair> { private int sum; private int count; public IntSumPair() {} public IntSumPair(int sum, int count) { this.sum = sum; this.count = count; } // Getters and setters... @Override public void write(DataOutput out) throws IOException { out.writeInt(sum); out.writeInt(count); } @Override public void readFields(DataInput in) throws IOException { sum = in.readInt(); count = in.readInt(); } @Override public int compareTo(IntSumPair o) { return Double.compare((double)this.sum / this.count, (double)o.getSum() / o.getCount()); } } ``` #### Reduce 阶段 Reducer接收来自mapper发出的所有相同key关联起来的一系列values对象列表作为参数。在这个例子中,所有的value都具有相同的key `"avg"` ,因此reducer只需要遍历这个集合累加各个成员所携带的信息——即总数和个数,最后返回它们之间的比率作为整体均值。 ```java public class AverageReducer extends Reducer<Text, IntSumPair, Text, FloatWritable> { @Override protected void reduce(Text key, Iterable<IntSumPair> values, Context context) throws IOException, InterruptedException { int totalSum = 0; int totalCount = 0; for (IntSumPair val : values) { totalSum += val.getSum(); totalCount += val.getCount(); } float average = ((float)totalSum)/totalCount; context.write(key, new FloatWritable(average)); } } ``` 上述代码展示了如何构建一个简单的基于MapReduce架构的应用程序来进行大规模数据集中平均值得到高效计算。需要注意的是实际应用可能还需要考虑更多细节如异常情况下的健壮性等问题[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值