本頁介紹MLlib中的聚類算法。 在基於RDD的API中聚類的指南還具有關於這些算法的相關信息。
目錄
1 k-均值 K-means
2 Dirichlet allocation (LDA)
3 平分k-均值 Bisecting k-means
4 高斯混合模型(GMM)
1 K-means
k-means是將數據點聚類到預定數量的聚類中最常用的聚類算法之一。 MLlib實現包括一個名爲kmeans ||的k-means ++方法的並行化變體。
KMeans實現爲一個估計器,並生成一個KMeansModel作爲基本模型。
from pyspark.ml.clustering import KMeans # Loads data. dataset = spark.read.format("libsvm").load("data/mllib/sample_kmeans_data.txt") # Trains a k-means model. kmeans = KMeans().setK(2).setSeed(1) model = kmeans.fit(dataset) # Evaluate clustering by computing Within Set Sum of Squared Errors. wssse = model.computeCost(dataset) print("Within Set Sum of Squared Errors = " + str(wssse)) # Shows the result. centers = model.clusterCenters() print("Cluster Centers: ") for center in centers: print(center)2 Dirichlet allocation (LDA)
LDA實現爲一個支持EMLDAOptimizer和OnlineLDAOptimizer的估計器,並生成一個LDAModel作爲基本模型。 如果需要,專家用戶可以將EMLDAOptimizer生成的LDAModel轉換爲DistributedLDAModel。
from pyspark.ml.clustering import LDA # Loads data. dataset = spark.read.format("libsvm").load("data/mllib/sample_lda_libsvm_data.txt") # Trains a LDA model. lda = LDA(k=10, maxIter=10) model = lda.fit(dataset) ll = model.logLikelihood(dataset) lp = model.logPerplexity(dataset) print("The lower bound on the log likelihood of the entire corpus: " + str(ll)) print("The upper bound bound on perplexity: " + str(lp)) # Describe topics. topics = model.describeTopics(3) print("The topics described by their top-weighted terms:") topics.show(truncate=False) # Shows the result transformed = model.transform(dataset) transformed.show(truncate=False)
3 Bisecting k-means
平分k均值是使用分裂(或“自上而下”)方法的一種分層聚類:所有觀察在一個簇中開始,並且分層在層級結構向下移動時遞歸地執行。
平分K均值通常比常規K均值快得多,但通常會產生不同的聚類。
BisectingKMeans被實現爲一個估計器,並生成一個BisectingKMeansModel作爲基本模型。
from pyspark.ml.clustering import BisectingKMeans # Loads data. dataset = spark.read.format("libsvm").load("data/mllib/sample_kmeans_data.txt") # Trains a bisecting k-means model. bkm = BisectingKMeans().setK(2).setSeed(1) model = bkm.fit(dataset) # Evaluate clustering. cost = model.computeCost(dataset) print("Within Set Sum of Squared Errors = " + str(cost)) # Shows the result. print("Cluster Centers: ") centers = model.clusterCenters() for center in centers: print(center)4 高斯混合模型(GMM)
高斯混合模型表示複合分佈,其中點從k個高斯子分佈中的一個繪出,每個具有其自身的概率。 spark.ml實現使用期望最大化算法來給出給定一組樣本的最大似然模型。
GaussianMixture作爲估計器實現,並生成GaussianMixtureModel作爲基本模。
from pyspark.ml.clustering import GaussianMixture # loads data dataset = spark.read.format("libsvm").load("data/mllib/sample_kmeans_data.txt") gmm = GaussianMixture().setK(2).setSeed(538009335) model = gmm.fit(dataset) print("Gaussians shown as a DataFrame: ") model.gaussiansDF.show(truncate=False)