Giới thiệu về phân cụm

Nền tảng Big Data với PySpark

Upendra Devisetty

Science Analyst, CyVerse

Phân cụm là gì?

  • Phân cụm là bài toán học không giám sát để tổ chức dữ liệu thành các nhóm

  • Thư viện PySpark MLlib hiện hỗ trợ các mô hình phân cụm sau

    • K-means
    • Hỗn hợp Gaussian
    • Phân cụm lặp lũy thừa (PIC)
    • K-means phân đôi
    • K-means luồng dữ liệu
Nền tảng Big Data với PySpark

Phân cụm K-means

  • K-means là phương pháp phân cụm phổ biến nhất

Nền tảng Big Data với PySpark

K-means với Spark MLLib

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]]
Nền tảng Big Data với PySpark

Huấn luyện mô hình K-means

  • Huấn luyện mô hình K-means bằng phương thức 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])]
Nền tảng Big Data với PySpark

Đánh giá mô hình 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
Nền tảng Big Data với PySpark

Trực quan hóa các cụm K-means

Nền tảng Big Data với PySpark

Trực quan hóa cụm

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");
Nền tảng Big Data với PySpark

Luyện tập phân cụm

Nền tảng Big Data với PySpark

Preparing Video For Download...