Mahout clustering Canopy+K-means 源码分析

 

聚类分析

 

     聚类(Clustering)可以简单的理解为将数据对象分为多个簇(Cluster),每个簇 里的所有数据对象具有一定的相似性,这样一个簇可以看多一个整体对待,以此可以提高计算质量或减少计算量。而数据对象间相似性的衡量通常是通过坐标系中空间距离的大小来判断;常见的有 欧几里得距离算法、余弦距离算法、皮尔逊相关系数算法等,Mahout对此都提供了实现,并且你可以在实现自己的聚类时,通过接口切换不同的距离算法。

 

 

数据模型

 

     在Mahout的聚类分析的计算过程中,数据对象会转化成向量(Vector)参与运算,在Mahout中的接口是org.apache.mahout.math.Vector  它里面每个域用一个浮点数(double)表示,你可以通过继承Mahout里的基类如:AbstractVector来实现自己的向量模型,也可以直接使用一些它提供的已有实现如下:

 

    1. DenseVector,它的实现就是一个浮点数数组,对向量里所有域都进行存储,适合用于存储密集向量。

 

    2. RandomAccessSparseVector 基于浮点数的 HashMap 实现的,key 是整形 (int) 类型,value 是浮点数(double) 类型,它只存储向量中不为空的值,并提供随机访问。

 

    3. SequentialAccessVector 实现为整形 (int) 类型和浮点数 (double) 类型的并行数组,它也只存储向量中不 为空的值,但只提供顺序访问。

 

 

聚类算法K-means与Canopy

 

       首先介绍先K-means算法:所有做聚类分析的数据对象,会被描述成n为空间中的一个点,用向量(Vector)表示;算法开始会随机选择K个点,作为一个簇的中心,然后其余的点会根据它与每个簇心的距离,被分配到最近簇中去;接着以迭代的方式,先重新计算每个簇的中心(通过其包含的所有向量的平均值),计算完成后对所有点属于哪个簇进行重新划分;一直如此迭代直到过程收敛;可证明迭代次数是有限的。

 

       虽然K-means简单且高效,但它存在一定问题,首先K值(即簇的数量)是人为确定的,在对数据不了解的情况下,很难给出合理的K值;其次初始簇心的选择是随机的,若选择到了较孤立的点,会对聚类的效果产生非常大的影响。因此通常会用Canopy算法配合,进行初始化,确定簇数以及初始簇心。

 

       Canopy算法首先会要求输入两个阀值 T1和T2,T1>T2;算法有一个集群这里叫Canopy的集合(Set),当然一开始它是空的;然后会将读取到的第一个点作为集合中的一个Canopy,接着读取下一个点,若该点与集合中的每个Canopy计算距离,若这个距离小于T1,则这个点会分配给这个Canopy(一个点可以分配给多个Canopy),而当这个距离小于T2时这个点不能作为一个新的Canopy而放到集合中。也就是说当一个点只要与集合中任意一个Canopy的距离小于T2了,即表示它里那个Canopy太近不能作为新的Canopy。若都没有则生成一个新的Canopy放入集合中。以此循环,直到没有点了。

 

       所以这里用到的聚类分析算法的思路是:首先通过Canopy算法进行聚类,以确定簇数以及初始簇心的,接着通过K-means算法进行迭代运算,收敛出最后的聚类结果。接下来我们看看实现。

 

 

 

 

代码示例

在 mahout-examples 中的 org.apache.mahout.clustering.syntheticcontrol.kmeans.Job类,对上述算法提供了较完整的实现,它是一个Hadoop的job,我们从源代码入手,看如何将实际的数据跑起来。下面是该类的核心逻辑代码:

/**

	 * Run the kmeans clustering job on an input dataset using the given
	 * distance measure, t1, t2 and iteration parameters. All output data will
	 * be written to the output directory, which will be initially deleted if it
	 * exists. The clustered points will reside in the path
	 * <output>/clustered-points. By default, the job expects the a file
	 * containing synthetic_control.data as obtained from
	 * http://archive.ics.uci.
	 * edu/ml/datasets/Synthetic+Control+Chart+Time+Series resides in a
	 * directory named "testdata", and writes output to a directory named
	 * "output".
	 * 
	 * @param conf
	 *            the Configuration to use
	 * @param input
	 *            the String denoting the input directory path
	 * @param output
	 *            the String denoting the output directory path
	 * @param measure
	 *            the DistanceMeasure to use
	 * @param t1
	 *            the canopy T1 threshold
	 * @param t2
	 *            the canopy T2 threshold
	 * @param convergenceDelta
	 *            the double convergence criteria for iterations
	 * @param maxIterations
	 *            the int maximum number of iterations
	 */
	public static void run(Configuration conf, Path input, Path output,
			DistanceMeasure measure, double t1, double t2,
			double convergenceDelta, int maxIterations) throws Exception {
	
		System.out.println("run canopy output: " + output);
		Path directoryContainingConvertedInput = new Path(output,
				DIRECTORY_CONTAINING_CONVERTED_INPUT);
		log.info("Preparing Input");
		InputDriver.runJob(input, directoryContainingConvertedInput,
				"org.apache.mahout.math.RandomAccessSparseVector");
		log.info("Running Canopy to get initial clusters");
		CanopyDriver.run(conf, directoryContainingConvertedInput, output,
				measure, t1, t2, false, false);
		log.info("Running KMeans");
		System.out.println("kmeans cluster starting...");
		KMeansDriver.run(conf, directoryContainingConvertedInput, new Path(
				output, Cluster.INITIAL_CLUSTERS_DIR+"-final"), output, measure,
				convergenceDelta, maxIterations, true, false);
		// run ClusterDumper
		ClusterDumper clusterDumper = new ClusterDumper(finalClusterPath(conf,
				output, maxIterations), new Path(output, "clusteredPoints"));
		clusterDumper.printClusters(null);
	}

       这个Job中调用了3个Map/Reduce 任务以及一个转换,它们如下:


       1. 第8行: InputDriver.runJob ( ) ,它用于将原始数据文件转换成 Mahout进行计算所需格式的文件 SequenceFile,它是Hadoop API提供的一种二进制文件支持。这种二进制文件直接将<key, value>对序列化到文件中。

       2. 第11行:CanopyDriver.run( ) , 即用Canopy算法确定初始簇的个数和簇的中心。

       3.  第14行:KMeansDriver.run( ) , 这显然是K-means算法进行聚类。

       4. 第18~20行,ClusterDumper类将聚类的结果装换并写出来,若你了解了源代码,你也可以自己实现这个类的功能,因为聚类后的数据存储格式,往往跟自身业务有关。 

         这里细讲下第一个Map/Reduce: InputDriver.runJob ( )因为我们需要了解,初始数据的格式,其他的任务CanopyDriver.run( )和KMeansDriver.run( )任务就不细讲了,主要就是Canopy和K-means算法,原理已经介绍了,实现也不难,需要你了解hadoop编程。
 InputDriver.runJob( )实现也非常简单,它只有Map,其代码如下:
@Override
protected void map(LongWritable key, Text values, Context context) throws IOException, InterruptedException {

  String[] numbers = SPACE.split(values.toString());
  // sometimes there are multiple separator spaces
  Collection<Double> doubles = Lists.newArrayList();
  for (String value : numbers) {
    if (!value.isEmpty()) {
      doubles.add(Double.valueOf(value));
    }
  }
  // ignore empty lines in data file
  if (!doubles.isEmpty()) {
    try {
      Vector result = (Vector) constructor.newInstance(doubles.size());
      int index = 0;
      for (Double d : doubles) {
        result.set(index++, d);
      }
      VectorWritable vectorWritable = new VectorWritable(result);
      context.write(new Text(String.valueOf(index)), vectorWritable);

    } catch (InstantiationException e) {
      throw new IllegalStateException(e);
    } catch (IllegalAccessException e) {
      throw new IllegalStateException(e);
    } catch (InvocationTargetException e) {
      throw new IllegalStateException(e);
    }
  }
}
   由代码可以看出,它将你初始数据文件的每一行用空格切开成个 String[] numbers ,然后再将 numbers中的每个String转换成Double类型,并以此生成一个向量 Vector ,然后通过 SequenceFileOutputFormat的方式输出成SequenceFile,以作下一步计算的输入。由此我们可以了解到我们的初始数据的格式需要 以一行为一个单位,用空格分隔,每一列为一个Double数即可(当然你也可以反过来修改例子中的实现)。


参考资料:

https://cwiki.apache.org/confluence/display/MAHOUT/K-Means+Clustering

https://cwiki.apache.org/confluence/display/MAHOUT/Canopy+Clustering

http://www.ibm.com/developerworks/cn/java/j-mahout-scaling/

http://www.ibm.com/developerworks/cn/web/1103_zhaoct_recommstudy3/

《Mahout in action》

https://cwiki.apache.org/MAHOUT/cluster-dumper.html

原创博客,转载请注明:http://my.oschina.net/BreathL/blog/58104


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值