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

Hadoop k-means 算法实现

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

Mapper:

  1. package org.fansy.date928; 
  2.  
  3. import java.io.BufferedReader; 
  4. import java.io.FileReader; 
  5. import java.io.IOException; 
  6. import java.util.ArrayList; 
  7. import java.util.List; 
  8.  
  9. import org.apache.commons.logging.Log; 
  10. import org.apache.commons.logging.LogFactory; 
  11. import org.apache.Hadoop.filecache.DistributedCache; 
  12. import org.apache.hadoop.fs.Path; 
  13. import org.apache.hadoop.io.IntWritable; 
  14. import org.apache.hadoop.io.LongWritable; 
  15. import org.apache.hadoop.io.Text; 
  16. import org.apache.hadoop.mapreduce.Mapper; 
  17.  
  18. public class KmeansM extends Mapper<LongWritable,Text,IntWritable,DataPro>{ 
  19.     private static Log log=LogFactory.getLog(KmeansM.class); 
  20.      
  21.     private double[][] centers; 
  22.     private int dimention_m;  //  this is the k   
  23.     private int dimention_n;   //  this is the features   
  24.  
  25.      
  26.     static enum Counter{Fansy_Miss_Records}; 
  27.     @Override 
  28.     public void setup(Context context) throws IOException,InterruptedException{ 
  29.         Path[] caches=DistributedCache.getLocalCacheFiles(context.getConfiguration()); 
  30.         if(caches==null||caches.length<=0){ 
  31.             log.error("center file does not exist"); 
  32.             System.exit(1); 
  33.         } 
  34.         BufferedReader br=new BufferedReader(new FileReader(caches[0].toString())); 
  35.         String line; 
  36.         List<ArrayList<Double>> temp_centers=new ArrayList<ArrayList<Double>>(); 
  37.         ArrayList<Double> center=null; 
  38.         //  get the file data  
  39.         while((line=br.readLine())!=null){ 
  40.             center=new ArrayList<Double>(); 
  41.             String[] str=line.split("\t"); 
  42.         //  String[] str=line.split("\\s+");  
  43.             for(int i=0;i<str.length;i++){ 
  44.                 center.add(Double.parseDouble(str[i])); 
  45.             //  center.add((double)Float.parseFloat(str[i]));  
  46.             } 
  47.             temp_centers.add(center); 
  48.         } 
  49.         try { 
  50.             br.close(); 
  51.         } catch (Exception e) { 
  52.             // TODO Auto-generated catch block  
  53.             e.printStackTrace(); 
  54.         } 
  55.         //  fill the centers   
  56.         @SuppressWarnings("unchecked") 
  57.         ArrayList<Double>[] newcenters=temp_centers.toArray(new ArrayList[]{}); 
  58.          dimention_m=temp_centers.size(); 
  59.          dimention_n=newcenters[0].size(); 
  60.         centers=new double[dimention_m][dimention_n]; 
  61.         for(int i=0;i<dimention_m;i++){ 
  62.             Double[] temp_double=newcenters[i].toArray(new Double[]{}); 
  63.             for(int j=0;j<dimention_n;j++){ 
  64.                 centers[i][j]=temp_double[j]; 
  65.         //      System.out.print(temp_double[j]+",");  
  66.             } 
  67.         //  System.out.println();  
  68.         } 
  69.     } 
  70.          
  71.          
  72.     public void map(LongWritable key,Text value,Context context)throws IOException,InterruptedException{ 
  73.         String[] values=value.toString().split("\t"); 
  74.     //  String[] values=value.toString().split("\\s+");  
  75.         if(values.length!=dimention_n){ 
  76.             context.getCounter(Counter.Fansy_Miss_Records).increment(1); 
  77.             return; 
  78.         } 
  79.         double[] temp_double=new double[values.length]; 
  80.         for(int i=0;i<values.length;i++){ 
  81.             temp_double[i]=Double.parseDouble(values[i]); 
  82.         } 
  83.         //  set the index  
  84.         double distance=Double.MAX_VALUE; 
  85.         double temp_distance=0.0; 
  86.         int index=0; 
  87.         for(int i=0;i<dimention_m;i++){ 
  88.             double[] temp_center=centers[i]; 
  89.             temp_distance=getEnumDistance(temp_double,temp_center); 
  90.             if(temp_distance<distance){ 
  91.                  index=i; 
  92.                 distance=temp_distance; 
  93.             } 
  94.         } 
  95.         DataPro newvalue=new DataPro(); 
  96.         newvalue.set(value, new IntWritable(1)); 
  97.     //  System.out.println("the map out:"+index+","+value);  
  98.         context.write(new IntWritable(index), newvalue); 
  99.          
  100.     } 
  101.     public static double getEnumDistance(double[] source,double[] other){  //  get the distance  
  102.         double distance=0.0; 
  103.         if(source.length!=other.length){ 
  104.             return Double.MAX_VALUE; 
  105.         } 
  106.         for(int i=0;i<source.length;i++){ 
  107.             distance+=(source[i]-other[i])*(source[i]-other[i]); 
  108.         } 
  109.         distance=Math.sqrt(distance); 
  110.         return distance; 
  111.     } 
  112. } 

Combiner:

  1. package org.fansy.date928; 
  2.  
  3. import java.io.BufferedReader; 
  4. import java.io.FileReader; 
  5. import java.io.IOException; 
  6.  
  7. import org.apache.commons.logging.Log; 
  8. import org.apache.commons.logging.LogFactory; 
  9. import org.apache.hadoop.filecache.DistributedCache; 
  10. import org.apache.hadoop.fs.Path; 
  11. import org.apache.hadoop.io.IntWritable; 
  12. import org.apache.hadoop.io.Text; 
  13. import org.apache.hadoop.mapreduce.Reducer; 
  14.  
  15. public class KmeansC extends Reducer<IntWritable,DataPro,IntWritable,DataPro> { 
  16.     private static int dimension=0; 
  17.      
  18.     private static Log log =LogFactory.getLog(KmeansC.class); 
  19.     // the main purpose of the sutup() function is to get the dimension of the original data  
  20.     public void setup(Context context) throws IOException{ 
  21.         Path[] caches=DistributedCache.getLocalCacheFiles(context.getConfiguration()); 
  22.         if(caches==null||caches.length<=0){ 
  23.             log.error("center file does not exist"); 
  24.             System.exit(1); 
  25.         } 
  26.         BufferedReader br=new BufferedReader(new FileReader(caches[0].toString())); 
  27.         String line; 
  28.         while((line=br.readLine())!=null){ 
  29.             String[] str=line.split("\t"); 
  30.         //  String[] str=line.split("\\s+");  
  31.             dimension=str.length; 
  32.             break; 
  33.         } 
  34.         try { 
  35.             br.close(); 
  36.         } catch (Exception e) { 
  37.             // TODO Auto-generated catch block  
  38.             e.printStackTrace(); 
  39.         } 
  40.     } 
  41.      
  42.      
  43.     public void reduce(IntWritable key,Iterable<DataPro> values,Context context)throws InterruptedException, IOException{   
  44.         double[] sum=new double[dimension]; 
  45.         int sumCount=0; 
  46.         // operation two  
  47.         for(DataPro val:values){ 
  48.             String[] datastr=val.getCenter().toString().split("\t"); 
  49.     //      String[] datastr=val.getCenter().toString().split("\\s+");  
  50.             sumCount+=val.getCount().get(); 
  51.             for(int i=0;i<dimension;i++){ 
  52.                 sum[i]+=Double.parseDouble(datastr[i]); 
  53.             } 
  54.         } 
  55.         //  calculate the new centers  
  56. //      double[] newcenter=new double[dimension];  
  57.         StringBuffer sb=new StringBuffer(); 
  58.         for(int i=0;i<dimension;i++){ 
  59.             sb.append(sum[i]+"\t"); 
  60.         } 
  61.     //  System.out.println("combine text:"+sb.toString());  
  62.     //  System.out.println("combine sumCount:"+sumCount);  
  63.         DataPro newvalue=new DataPro(); 
  64.         newvalue.set(new Text(sb.toString()), new IntWritable(sumCount)); 
  65.         context.write(key, newvalue); 
  66.     } 
  67. } 

Reducer:

  1. package org.fansy.date928; 
  2.  
  3. import java.io.BufferedReader; 
  4. import java.io.FileReader; 
  5. import java.io.IOException; 
  6.  
  7. import org.apache.commons.logging.Log; 
  8. import org.apache.commons.logging.LogFactory; 
  9. import org.apache.hadoop.filecache.DistributedCache; 
  10. import org.apache.hadoop.fs.Path; 
  11. import org.apache.hadoop.io.IntWritable; 
  12. import org.apache.hadoop.io.NullWritable; 
  13. import org.apache.hadoop.io.Text; 
  14. import org.apache.hadoop.mapreduce.Reducer; 
  15.  
  16. public class KmeansR extends Reducer<IntWritable,DataPro,NullWritable,Text> { 
  17.     private static int dimension=0; 
  18.      
  19.     private static Log log =LogFactory.getLog(KmeansC.class); 
  20.     // the main purpose of the sutup() function is to get the dimension of the original data  
  21.     public void setup(Context context) throws IOException{ 
  22.         Path[] caches=DistributedCache.getLocalCacheFiles(context.getConfiguration()); 
  23.         if(caches==null||caches.length<=0){ 
  24.             log.error("center file does not exist"); 
  25.             System.exit(1); 
  26.         } 
  27.         BufferedReader br=new BufferedReader(new FileReader(caches[0].toString())); 
  28.         String line; 
  29.         while((line=br.readLine())!=null){ 
  30.             String[] str=line.split("\t"); 
  31.             dimension=str.length; 
  32.             break; 
  33.         } 
  34.         try { 
  35.             br.close(); 
  36.         } catch (Exception e) { 
  37.             // TODO Auto-generated catch block  
  38.             e.printStackTrace(); 
  39.         } 
  40.     } 
  41.     public void reduce(IntWritable key,Iterable<DataPro> values,Context context)throws InterruptedException, IOException{ 
  42.      
  43.         double[] sum=new double[dimension]; 
  44.         int sumCount=0; 
  45.         for(DataPro val:values){ 
  46.             String[] datastr=val.getCenter().toString().split("\t"); 
  47.         //  String[] datastr=val.getCenter().toString().split("\\s+");  
  48.             sumCount+=val.getCount().get(); 
  49.             for(int i=0;i<dimension;i++){ 
  50.                 sum[i]+=Double.parseDouble(datastr[i]); 
  51.             } 
  52.         } 
  53.         //  calculate the new centers  
  54. //      double[] newcenter=new double[dimension];  
  55.         StringBuffer sb=new StringBuffer(); 
  56.         for(int i=0;i<dimension;i++){ 
  57.             sb.append(sum[i]/sumCount+"\t"); 
  58.         //  sb.append(sum[i]/sumCount+"\\s+");  
  59.         } 
  60.         context.write(null, new Text(sb.toString())); 
  61.     } 
  62. } 

LastMapper:

  1. package org.fansy.date928; 
  2.  
  3. import java.io.BufferedReader; 
  4. import java.io.FileReader; 
  5. import java.io.IOException; 
  6. import java.util.ArrayList; 
  7. import java.util.List; 
  8.  
  9. import org.apache.commons.logging.Log; 
  10. import org.apache.commons.logging.LogFactory; 
  11. import org.apache.hadoop.filecache.DistributedCache; 
  12. import org.apache.hadoop.fs.Path; 
  13. import org.apache.hadoop.io.IntWritable; 
  14. import org.apache.hadoop.io.LongWritable; 
  15. import org.apache.hadoop.io.Text; 
  16. import org.apache.hadoop.mapreduce.Mapper; 
  17.  
  18. public class KmeansLastM extends Mapper<LongWritable,Text,IntWritable,Text>{ 
  19.     private static Log log=LogFactory.getLog(KmeansLastM.class); 
  20.      
  21.     private double[][] centers; 
  22.     private int dimention_m;  //  this is the k   
  23.     private int dimention_n;   //  this is the features   
  24.  
  25.      
  26.     static enum Counter{Fansy_Miss_Records}; 
  27.     @Override 
  28.     public void setup(Context context) throws IOException,InterruptedException{ 
  29.         Path[] caches=DistributedCache.getLocalCacheFiles(context.getConfiguration()); 
  30.         if(caches==null||caches.length<=0){ 
  31.             log.error("center file does not exist"); 
  32.             System.exit(1); 
  33.         } 
  34.         @SuppressWarnings("resource") 
  35.         BufferedReader br=new BufferedReader(new FileReader(caches[0].toString())); 
  36.         String line; 
  37.         List<ArrayList<Double>> temp_centers=new ArrayList<ArrayList<Double>>(); 
  38.         ArrayList<Double> center=null; 
  39.         //  get the file data  
  40.         while((line=br.readLine())!=null){ 
  41.             center=new ArrayList<Double>(); 
  42.             String[] str=line.split("\t"); 
  43.             for(int i=0;i<str.length;i++){ 
  44.                 center.add(Double.parseDouble(str[i])); 
  45.             } 
  46.             temp_centers.add(center); 
  47.         } 
  48.         //  fill the centers   
  49.         @SuppressWarnings("unchecked") 
  50.         ArrayList<Double>[] newcenters=temp_centers.toArray(new ArrayList[]{}); 
  51.          dimention_m=temp_centers.size(); 
  52.          dimention_n=newcenters[0].size(); 
  53.         centers=new double[dimention_m][dimention_n]; 
  54.         for(int i=0;i<dimention_m;i++){ 
  55.             Double[] temp_double=newcenters[i].toArray(new Double[]{}); 
  56.             for(int j=0;j<dimention_n;j++){ 
  57.                 centers[i][j]=temp_double[j]; 
  58.         //      System.out.print(temp_double[j]+",");  
  59.             } 
  60.     //      System.out.println();  
  61.         } 
  62.     } 
  63.          
  64.          
  65.     public void map(LongWritable key,Text value,Context context)throws IOException,InterruptedException{ 
  66.         String[] values=value.toString().split("\t"); 
  67.     //  String[] values=value.toString().split("\\s+");  
  68.         if(values.length!=dimention_n){ 
  69.             context.getCounter(Counter.Fansy_Miss_Records).increment(1); 
  70.             return; 
  71.         } 
  72.         double[] temp_double=new double[values.length]; 
  73.         for(int i=0;i<values.length;i++){ 
  74.             temp_double[i]=Double.parseDouble(values[i]); 
  75.         } 
  76.         //  set the index  
  77.         double distance=Double.MAX_VALUE; 
  78.         double temp_distance=0.0; 
  79.         int index=0; 
  80.         for(int i=0;i<dimention_m;i++){ 
  81.             double[] temp_center=centers[i]; 
  82.             temp_distance=getEnumDistance(temp_double,temp_center); 
  83.             if(temp_distance<distance){ 
  84.                  index=i; 
  85.                 distance=temp_distance; 
  86.             } 
  87.         } 
  88.         context.write(new IntWritable(index), value); 
  89.          
  90.     } 
  91.     public static double getEnumDistance(double[] source,double[] other){  //  get the distance  
  92.         double distance=0.0; 
  93.         if(source.length!=other.length){ 
  94.             return Double.MAX_VALUE; 
  95.         } 
  96.         for(int i=0;i<source.length;i++){ 
  97.             distance+=(source[i]-other[i])*(source[i]-other[i]); 
  98.         } 
  99.         distance=Math.sqrt(distance); 
  100.         return distance; 
  101.     } 
  102. } 

LastReducer:

  1. package org.fansy.date928; 
  2.  
  3. import java.io.IOException; 
  4. import org.apache.hadoop.io.IntWritable; 
  5. import org.apache.hadoop.io.Text; 
  6. import org.apache.hadoop.mapreduce.Reducer; 
  7.  
  8. public class KmeansLastR extends Reducer<IntWritable,Text,IntWritable,Text> { 
  9.      
  10.     public void reduce(IntWritable key,Iterable<Text> values,Context context)throws InterruptedException, IOException{ 
  11.  
  12.         //  output the data directly  
  13.         for(Text val:values){ 
  14.             context.write(key, val); 
  15.         } 
  16.          
  17.     } 
  18. } 
linux
相关资讯       HDFS 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

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