【Spark】聚类分析
本节主要讲Spark ML中关于聚类算法的实现。示例的算法Demo包含:K-means、LDA、高斯混合模型(GMM)等。
1. K-means
KMeans作为Estimator实现,并生成KMeansModel作为基本模型。
1.1 输入
Param name | Type(s) | Default | Description |
---|---|---|---|
featuresCol | Vector | “features” | Feature vector |
1.2 输出
Param name | Type(s) | Default | Description |
---|---|---|---|
predictionCol | Int | “prediction” | Predicted cluster center |
示例代码如下:
1 | # -*- coding: utf-8 -*- |
结果如下:
1 | Silhouette with squared euclidean distance = 0.999753030538 |
2. 隐狄利克雷分布(Latent Dirichlet Allocation, LDA)
LDA实现支持EMLDAOptimizer和OnlineLDAOptimizer的Estimator,并生成LDAModel作为基本模型。 如果需要,用户可以将EMLDAOptimizer生成的LDAModel转换为DistributedLDAModel。
示例代码如下:
1 | # -*- coding: utf-8 -*- |
结果如下:
1 | The lower bound on the log likelihood of the entire corpus: -819.009950373 |
3. 二分K-means(Bisecting K-means)
二分k-means是一种使用分裂(或“自上而下”)方法的层次聚类:首先将所有点作为一个簇, 然后将该簇一分为二,递归地执行拆分。二分K-means通常比常规K-means快得多,但它通常会产生不同的聚类。
BisectingKMeans作为Estimator实现,并生成BisectingKMeansModel作为基本模型。
示例代码如下:
1 | # -*- coding: utf-8 -*- |
结果如下:
1 | Within Set Sum of Squared Errors = 0.12 |
4. 混合高斯模型(Gaussian Mixture Model, GMM)
高斯混合模型表示复合分布,其中从k个高斯子分布中的一个绘制点,每个子分布具有其自己的概率。 spark.ml实现使用期望最大化算法求解最大似然模型。
4.1 输入
Param name | Type(s) | Default | Description |
---|---|---|---|
featuresCol | Vector | “features” | Feature vector |
4.2 输出
Param name | Type(s) | Default | Description |
---|---|---|---|
predictionCol | Int | “prediction” | Predicted cluster center |
probabilityCol | Vector | “probability” | Probability of each cluster |
示例代码如下:
1 | # -*- coding: utf-8 -*- |
结果如下:
1 | Gaussians shown as a DataFrame: |