hadoop下实现kmeans一

来源:互联网 发布:淘宝不能登陆 编辑:程序博客网 时间:2024/04/20 02:37

前一段时间,从配置hadoop到运行kmeans的mapreduce程序,着实让我纠结了几天,昨天终于把前面遇到的配置问题和程序运行问题搞定。Kmeans算法看起来很简单,但对于第一次接触mapreduce程序来说,还是有些挑战,还好基本都搞明白了。Kmeans算法是从网上下的在此分析一下过程。

Kmeans.java

[java] view plaincopy
  1. import org.apache.hadoop.conf.Configuration;  
  2. import org.apache.hadoop.fs.FileSystem;  
  3. import org.apache.hadoop.fs.Path;  
  4. import org.apache.hadoop.io.Text;  
  5. import org.apache.hadoop.mapreduce.Job;  
  6. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;  
  7. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;  
  8.   
  9. public class KMeans {  
  10.       
  11.     public static void main(String[] args) throws Exception  
  12.     {  
  13.         CenterInitial centerInitial = new CenterInitial();  
  14.         centerInitial.run(args);//初始化中心点  
  15.         int times=0;  
  16.         double s = 0,shold = 0.1;//shold是预制。  
  17.         do {  
  18.             Configuration conf = new Configuration();  
  19.             conf.set("fs.default.name""hdfs://localhost:9000");  
  20.             Job job = new Job(conf,"KMeans");//建立KMeans的MapReduce作业  
  21.             job.setJarByClass(KMeans.class);//设定作业的启动类  
  22.             job.setOutputKeyClass(Text.class);//设定Key输出的格式:Text  
  23.             job.setOutputValueClass(Text.class);//设定value输出的格式:Text  
  24.             job.setMapperClass(KMapper.class);//设定Mapper类  
  25.             job.setMapOutputKeyClass(Text.class);  
  26.             job.setMapOutputValueClass(Text.class);//设定Reducer类  
  27.             job.setReducerClass(KReducer.class);  
  28.             FileSystem fs = FileSystem.get(conf);  
  29.             fs.delete(new Path(args[2]),true);//args[2]是output目录,fs.delete是将已存在的output删除  
  30.                         //解析输入和输出参数,分别作为作业的输入和输出,都是文件   
  31.                         FileInputFormat.addInputPath(job, new Path(args[0]));  
  32.             FileOutputFormat.setOutputPath(job, new Path(args[2]));  
  33.                         //运行作业并判断是否完成成功  
  34.                         job.waitForCompletion(true);  
  35.             if(job.waitForCompletion(true))//上一次mapreduce过程结束  
  36.             {  
  37.                                 //上两个中心点做比较,如果中心点之间的距离小于阈值就停止;如果距离大于阈值,就把最近的中心点作为新中心点  
  38.                                 NewCenter newCenter = new NewCenter();  
  39.                 s = newCenter.run(args);  
  40.                 times++;  
  41.             }  
  42.         } while(s > shold);//当误差小于阈值停止。  
  43.         System.out.println("Iterator: " + times);//迭代次数       
  44.     }  
  45.   
  46. }  
问题:args[]是什么,这个问题纠结了几日才得到答案,args[]就是最开始向程序中传递的参数,具体在Run Configurations里配置,如下

hdfs://localhost:9000/home/administrator/hadoop/kmeans/input hdfs://localhost:9000/home/administrator/hadoop/kmeans hdfs://localhost:9000/home/administrator/hadoop/kmeans/output

代码的功能在程序中注释。


0 0