聚类简介

使用 PySpark 的大数据基础

Upendra Devisetty

Science Analyst, CyVerse

什么是聚类?

  • 聚类是一种无监督学习任务,用于将数据集组织成若干组

  • PySpark MLlib 目前支持以下聚类模型

    • K-means
    • 高斯混合
    • 幂迭代聚类(PIC)
    • 二分 K-means
    • 流式 K-means
使用 PySpark 的大数据基础

K-means 聚类

  • K-means 是最常用的聚类方法

使用 PySpark 的大数据基础

用 Spark MLLib 进行 K-means

RDD = sc.textFile("WineData.csv"). \
       map(lambda x: x.split(",")).\
       map(lambda x: [float(x[0]), float(x[1])])
RDD.take(5)
[[14.23, 2.43], [13.2, 2.14], [13.16, 2.67], [14.37, 2.5], [13.24, 2.87]]
使用 PySpark 的大数据基础

训练 K-means 聚类模型

  • 训练 K-means 模型使用 KMeans.train() 方法
from pyspark.mllib.clustering import KMeans
model = KMeans.train(RDD, k = 2, maxIterations = 10)
model.clusterCenters
[array([12.25573171,  2.28939024]), array([13.636875  ,  2.43239583])]
使用 PySpark 的大数据基础

评估 K-means 模型

from math import sqrt
def error(point):
    center = model.centers[model.predict(point)]
    return sqrt(sum([x**2 for x in (point - center)]))
WSSSE = RDD.map(lambda point: error(point)).reduce(lambda x, y: x + y)
print("Within Set Sum of Squared Error = " + str(WSSSE))
Within Set Sum of Squared Error = 77.96236420499056
使用 PySpark 的大数据基础

可视化 K-means 聚类

使用 PySpark 的大数据基础

可视化聚类

wine_data_df = spark.createDataFrame(RDD, schema=["col1", "col2"])
wine_data_df_pandas = wine_data_df.toPandas()
cluster_centers_pandas = pd.DataFrame(model.clusterCenters, columns=["col1", "col2"])
cluster_centers_pandas.head()
plt.scatter(wine_data_df_pandas["col1"], wine_data_df_pandas["col2"]);
plt.scatter(cluster_centers_pandas["col1"], cluster_centers_pandas["col2"], color="red", marker="x");
使用 PySpark 的大数据基础

聚类练习

使用 PySpark 的大数据基础

Preparing Video For Download...