以前有做过在Hadoop编写程序时使用全局变量的想法,但是最后却没有实现,上网查才看到说Hadoop不支持全局变量。但是有时候编程的时候又会用到,比如编写k-means算法的时候,如果可以有个全局变量存储中心点该多好呀。其实在hadoop中确实是有相关的实现的,比如可以在mapper中的setup函数中读取一个小文件,然后从这个文件中取出全局变量的值。
那具体如何实现呢?首先提出一个问题,然后利用这种思想去解决会比较好。首先说下我要实现的问题:我现在有输入数据如下:
- 0.0 0.2 0.4
- 0.3 0.2 0.4
- 0.4 0.2 0.4
- 0.5 0.2 0.4
- 5.0 5.2 5.4
- 6.0 5.2 6.4
- 4.0 5.2 4.4
- 10.3 10.4 10.5
- 10.3 10.4 10.5
- 10.3 10.4 10.5
而且还有一个小数据文件(中心点)如下:
- 0 0 0
- 5 5 5
- 10 10 10
我想做的事情就是把输入数据按照中心点求平均值,即首先我把输入数据分类,比如倒数三行应该都是属于(10,10,10)这个中心点的,那么我的map就把倒数三行的key都赋值为2,然后value值还是保持这三行不变。在reduce阶段,我求出相同key的sum值,同时求出一共的行数count,最后我用sum/count得到我想要的按照中心点求出的平均值了。
下面贴代码:
KmeansDriver:
- package org.fansy.date927;
- import java.io.IOException;
- //import org.apache.commons.logging.Log;
- //import org.apache.commons.logging.LogFactory;
- import org.apache.hadoop.conf.Configuration;
- import org.apache.hadoop.filecache.DistributedCache;
- //import org.apache.hadoop.fs.FileSystem;
- import org.apache.hadoop.fs.Path;
- import org.apache.hadoop.io.IntWritable;
- import org.apache.hadoop.io.NullWritable;
- import org.apache.hadoop.io.Text;
- import org.apache.hadoop.mapreduce.Job;
- import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
- import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
- import org.apache.hadoop.util.GenericOptionsParser;
- public class KmeansDriver {
- /**
- * k-means algorithm program
- */
- public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
- // TODO Auto-generated method stub
- Configuration conf=new Configuration();
- // set the centers data file
- <SPAN style="COLOR: #ff0000">Path centersFile=new Path("hdfs://fansyPC:9000/user/fansy/input/centers");
- DistributedCache.addCacheFile(centersFile.toUri(), conf);</SPAN>
- String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
- if (otherArgs.length != 2) {
- System.err.println("Usage: KmeansDriver <in> <out>");
- System.exit(2);
- }
- Job job = new Job(conf, "kmeans job");
- job.setJarByClass(KmeansDriver.class);
- job.setMapperClass(KmeansM.class);
- job.setMapOutputKeyClass(IntWritable.class);
- job.setMapOutputValueClass(DataPro.class);
- job.setNumReduceTasks(2);
- // job.setCombinerClass(KmeansC.class);
- job.setReducerClass(KmeansR.class);
- job.setOutputKeyClass(NullWritable.class);
- job.setOutputValueClass(Text.class);
- FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
- FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
- if(!job.waitForCompletion(true)){
- System.exit(1); // run error then exit
- }
- }
- }
上面代码中加红的部分比较重要,是mapper的setup函数实现读取文件数据的关键;
