K-means 訓練
現在 RDD 已可用於訓練。在第 2 部分,你將用 k=13 到 16(以節省計算時間)進行測試,並使用 elbow 方法來選擇正確的 k。Elbow 方法的概念是:對資料集以不同的 k 值執行 K-means 分群,計算群內平方誤差總和(Within Set Sum of Squared Error,WSSSE),然後根據 WSSSE 的明顯下降來選出最佳的 k,也就是「手肘」出現的位置。接著,你會用最佳的 k 重新訓練模型,最後取得質心(叢集中心)。
提醒:你的工作區已經有 SparkContext sc 與 rdd_split_int RDD 可供使用。
本練習屬於課程
使用 PySpark 的 Big Data 基礎
練習說明
- 使用 13 到 16 的叢集數訓練 KMeans 模型,並列印每個叢集數對應的 WSSSE。
- 使用最佳的 k 再次訓練 KMeans 模型。
- 取得以最佳 k 訓練之 KMeans 模型的叢集中心(centroids)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Train the model with clusters from 13 to 16 and compute WSSSE
for clst in range(13, 17):
model = KMeans.____(rdd_split_int, clst, seed=1)
WSSSE = rdd_split_int.____(lambda point: error(point)).reduce(lambda x, y: x + y)
print("The cluster {} has Within Set Sum of Squared Error {}".format(clst, ____))
# Train the model again with the best k
model = KMeans.train(rdd_split_int, k=____, seed=1)
# Get cluster centers
cluster_centers = model.____