手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Hadoop k-means 算法实现

[日期:2012-10-01] 来源:Linux社区  作者:fansy1990 [字体:大 中 小]

经过昨天的准备工作,今天基本就可以编写整个k-means算法程序了。今天编写的时候遇到了一个问题,是combine操作时遇到的问题。除了这个问题基本都按照原来的思路进行。先说下我的思路吧。

准备工作:在上传数据文件到HDFS上之前,先应该产生一个中心文件,比如我的输入文件如下:

  1. 0.0 0.2 0.4 
  2. 0.3 0.2 0.4 
  3. 0.4 0.2 0.4 
  4. 0.5 0.2 0.4 
  5. 5.0 5.2 5.4 
  6. 6.0 5.2 6.4 
  7. 4.0 5.2 4.4 
  8. 10.3    10.4    10.5 
  9. 10.3    10.4    10.5 
  10. 10.3    10.4    10.5 

然后要产生中心文件,可以使用如下命令来操作:

(1)、获取文件的总行数:  wc data.txt 。可以得到文件的行数是 :10

(2)、因为我要分为三类,所以10/3=3,那么我取的行数就是1,3,6(这个行数可以自己选择,比如也可以直接去前三行 head -n 3 data.txt >centers.txt),然后使用如下命令:awk 'NR==1||NR==3||NR==6' data.txt > centers.txt,然后再把centers.txt上传到HDFS上就可以了。

(下面我使用的是前三行作为数据中心文件)

下面的程序中就不用设置要分 的类别和数据文件的维度数了,我在写这篇和前篇文章的时候参考了这篇文章:http://www.linuxidc.com/Linux/2012-10/71538.htm,这篇里面要在代码中自己设置要分的类别以及数据文件的维度数。

下面是map-combine-reduce 操作:

map: map的setup()函数主要是读取中心文件把文件的中心点读入一个double[][]中,然后是map。数据转换为:

Text(包含数据的字符串)--》[index,DataPro(Text(包含数据文件的字符串),IntWritable(1))]

combine:

[index,DataPro(Text(包含数据文件的字符串),IntWritable(1))]-->[index,DataPro(Text(包含数据文件相同index的相加的结果的字符串),IntWritable(sum(1)))]

reduce: reduce的setup()函数主要是读取数据中心文件,然后取出其中的数据维度信息(在reduce操作中需要数组赋值需要知道数据维度),

[index,DataPro(Text(包含数据文件相同index的相加的结果的字符串),IntWritable(sum(1)))]--》[index,DataPro(Text(包含数据文件相同index的相加的结果的字符串),IntWritable(sum(1)))]--》[index,Text(相同index的数据相加的平均值)]

上面的是循环的过程,最后一个job任务是输出分类的结果。

下面贴代码:

KmeansDriver:

  1. package org.fansy.date928; 
  2.  
  3. import java.io.BufferedReader; 
  4. import java.io.IOException; 
  5. import java.io.InputStreamReader; 
  6.  
  7. import org.apache.commons.logging.LogFactory; 
  8. import org.apache.commons.logging.Log; 
  9. //import org.apache.commons.logging.LogFactory;  
  10. import org.apache.Hadoop.conf.Configuration; 
  11. import org.apache.hadoop.filecache.DistributedCache; 
  12. import org.apache.hadoop.fs.FSDataInputStream; 
  13. import org.apache.hadoop.fs.FileSystem; 
  14. //import org.apache.hadoop.fs.FileSystem;  
  15. import org.apache.hadoop.fs.Path; 
  16. import org.apache.hadoop.io.IntWritable; 
  17. import org.apache.hadoop.io.NullWritable; 
  18. import org.apache.hadoop.io.Text; 
  19. import org.apache.hadoop.mapreduce.Job; 
  20. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; 
  21. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; 
  22. import org.apache.hadoop.util.GenericOptionsParser; 
  23.  
  24. public class KmeansDriver { 
  25.  
  26.     /** 
  27.      *   k-means algorithm program   
  28.      */ 
  29.     private static final String temp_path="hdfs://fansyPC:9000/user/fansy/date928/kmeans/temp_center/"; 
  30.     private static final String dataPath="hdfs://fansyPC:9000/user/fansy/input/smallkmeansdata"; 
  31.     private static final int iterTime=300; 
  32.     private static int iterNum=1; 
  33.     private static final double threadHold=0.01; 
  34.      
  35.     private static Log log=LogFactory.getLog(KmeansDriver.class); 
  36.      
  37.     public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException { 
  38.         // TODO Auto-generated method stub  
  39.         Configuration conf=new Configuration(); 
  40.          
  41.         // set the centers data file  
  42.         Path centersFile=new Path("hdfs://fansyPC:9000/user/fansy/input/centers"); 
  43.         DistributedCache.addCacheFile(centersFile.toUri(), conf); 
  44.          
  45.         String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); 
  46.         if (otherArgs.length != 1) { 
  47.           System.err.println("Usage: KmeansDriver <indatafile> "); 
  48.           System.exit(2); 
  49.         } 
  50.         Job job = new Job(conf, "kmeans job 0"); 
  51.         job.setJarByClass(KmeansDriver.class); 
  52.         job.setMapperClass(KmeansM.class); 
  53.         job.setMapOutputKeyClass(IntWritable.class); 
  54.         job.setMapOutputValueClass(DataPro.class); 
  55.         job.setNumReduceTasks(1); 
  56.         job.setCombinerClass(KmeansC.class); 
  57.         job.setReducerClass(KmeansR.class); 
  58.         job.setOutputKeyClass(NullWritable.class); 
  59.         job.setOutputValueClass(Text.class);     
  60.         FileInputFormat.addInputPath(job, new Path(dataPath)); 
  61.         FileOutputFormat.setOutputPath(job, new Path(temp_path+0+"/"));   
  62.         if(!job.waitForCompletion(true)){ 
  63.             System.exit(1); // run error then exit  
  64.         } 
  65.         //  do iteration  
  66.         boolean flag=true; 
  67.         while(flag&&iterNum<iterTime){ 
  68.             Configuration conf1=new Configuration(); 
  69.              
  70.             // set the centers data file  
  71.             Path centersFile1=new Path(temp_path+(iterNum-1)+"/part-r-00000");  //  the new centers file  
  72.             DistributedCache.addCacheFile(centersFile1.toUri(), conf1); 
  73.             boolean iterflag=doIteration(conf1,iterNum); 
  74.             if(!iterflag){ 
  75.                 log.error("job fails"); 
  76.                 System.exit(1); 
  77.             } 
  78.             //  set the flag based on the old centers and the new centers  
  79.              
  80.             Path oldCentersFile=new Path(temp_path+(iterNum-1)+"/part-r-00000"); 
  81.             Path newCentersFile=new Path(temp_path+iterNum+"/part-r-00000"); 
  82.             FileSystem fs1=FileSystem.get(oldCentersFile.toUri(),conf1); 
  83.             FileSystem fs2=FileSystem.get(oldCentersFile.toUri(),conf1); 
  84.             if(!(fs1.exists(oldCentersFile)&&fs2.exists(newCentersFile))){ 
  85.                 log.info("the old centers and new centers should exist at the same time"); 
  86.                 System.exit(1); 
  87.             } 
  88.             String line1,line2; 
  89.             FSDataInputStream in1=fs1.open(oldCentersFile); 
  90.             FSDataInputStream in2=fs2.open(newCentersFile); 
  91.             InputStreamReader istr1=new InputStreamReader(in1); 
  92.             InputStreamReader istr2=new InputStreamReader(in2); 
  93.             BufferedReader br1=new BufferedReader(istr1); 
  94.             BufferedReader br2=new BufferedReader(istr2); 
  95.             double error=0.0; 
  96.             while((line1=br1.readLine())!=null&&((line2=br2.readLine())!=null)){ 
  97.                 String[] str1=line1.split("\t"); 
  98.                 String[] str2=line2.split("\t"); 
  99.                 for(int i=0;i<str1.length;i++){ 
  100.                     error+=(Double.parseDouble(str1[i])-Double.parseDouble(str2[i]))*(Double.parseDouble(str1[i])-Double.parseDouble(str2[i])); 
  101.                 } 
  102.             } 
  103.             if(error<threadHold){ 
  104.                 flag=false; 
  105.             } 
  106.             iterNum++; 
  107.              
  108.         } 
  109.         // the last job , classify the data  
  110.          
  111.         Configuration conf2=new Configuration(); 
  112.         // set the centers data file  
  113.         Path centersFile2=new Path(temp_path+(iterNum-1)+"/part-r-00000");  //  the new centers file  
  114.         DistributedCache.addCacheFile(centersFile2.toUri(), conf2); 
  115.         lastJob(conf2,iterNum); 
  116.         System.out.println(iterNum); 
  117.     } 
  118.      
  119.     public static boolean doIteration(Configuration conf,int iterNum) throws IOException, ClassNotFoundException, InterruptedException{ 
  120.         boolean flag=false; 
  121.         Job job = new Job(conf, "kmeans job"+" "+iterNum); 
  122.         job.setJarByClass(KmeansDriver.class); 
  123.         job.setMapperClass(KmeansM.class); 
  124.         job.setMapOutputKeyClass(IntWritable.class); 
  125.         job.setMapOutputValueClass(DataPro.class); 
  126.         job.setNumReduceTasks(1); 
  127.         job.setCombinerClass(KmeansC.class); 
  128.         job.setReducerClass(KmeansR.class); 
  129.         job.setOutputKeyClass(NullWritable.class); 
  130.         job.setOutputValueClass(Text.class);     
  131.         FileInputFormat.addInputPath(job, new Path(dataPath)); 
  132.         FileOutputFormat.setOutputPath(job, new Path(temp_path+iterNum+"/"));   
  133.         flag=job.waitForCompletion(true); 
  134.         return flag; 
  135.     } 
  136.     public static void lastJob(Configuration conf,int iterNum) throws IOException, ClassNotFoundException, InterruptedException{ 
  137.         Job job = new Job(conf, "kmeans job"+" "+iterNum); 
  138.         job.setJarByClass(KmeansDriver.class); 
  139.         job.setMapperClass(KmeansLastM.class); 
  140.         job.setMapOutputKeyClass(IntWritable.class); 
  141.         job.setMapOutputValueClass(Text.class); 
  142.         job.setNumReduceTasks(4); 
  143.       //  job.setCombinerClass(KmeansC.class);  
  144.         job.setReducerClass(KmeansLastR.class); 
  145.         job.setOutputKeyClass(IntWritable.class); 
  146.         job.setOutputValueClass(Text.class);     
  147.         FileInputFormat.addInputPath(job, new Path(dataPath)); 
  148.         FileOutputFormat.setOutputPath(job, new Path(temp_path+iterNum+"/"));   
  149.         job.waitForCompletion(true); 
  150.     } 
  151.  
  152. } 
linux
相关资讯       HDFS 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款