การแสดงภาพ cluster
ได้ฝึกโมเดล k-means ด้วยค่า k ที่เหมาะสม (k=16) และสร้าง cluster centers (centroid) แล้ว ในแบบฝึกหัดสุดท้ายนี้ จะมีการแสดงภาพ cluster และ centroid โดยการซ้อนทับกัน เพื่อประเมินว่าการจัดกลุ่มทำงานได้ดีเพียงใด (ในกรณีที่ดี แต่ละ cluster ควรแยกจากกันชัดเจน และ centroid ควรอยู่ตรงกลางของ cluster นั้น)
ในการทำเช่นนี้ จะแปลง RDD rdd_split_int ให้เป็น Spark DataFrame ก่อน จากนั้นแปลงเป็น pandas DataFrame เพื่อใช้ในการพล็อตกราฟ จากนั้นแปลง cluster_centers เป็น pandas DataFrame เช่นกัน เมื่อสร้าง DataFrame ทั้งสองแล้ว ให้สร้าง scatter plot โดยใช้ Matplotlib
SparkContext sc รวมถึงตัวแปร rdd_split_int และ cluster_centers และแพ็กเกจ matplotlib.pyplot (นำเข้าในชื่อ plt) พร้อมใช้งานใน workspace แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Big Data Fundamentals with PySpark
คำแนะนำการฝึกหัด
- แปลง RDD
rdd_split_intให้เป็น Spark DataFrame จากนั้นแปลงเป็น pandas DataFrame - สร้าง pandas DataFrame จาก list
cluster_centers - สร้าง scatter plot จาก pandas DataFrame ของข้อมูลดิบ (
rdd_split_int_df_pandas) และซ้อนทับด้วย scatter plot จาก pandas DataFrame ของ centroid (cluster_centers_pandas)
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Convert rdd_split_int RDD into Spark DataFrame and then to Pandas DataFrame
rdd_split_int_df_pandas = spark.____(rdd_split_int, schema=["col1", "col2"]).toPandas()
# Convert cluster_centers to a pandas DataFrame
cluster_centers_pandas = pd.DataFrame(____, columns=["col1", "col2"])
# Create an overlaid scatter plot of clusters and centroids
plt.scatter(rdd_split_int_df_pandas["col1"], rdd_split_int_df_pandas["col2"])
plt.scatter(____["col1"], ____["col2"], color="red", marker="x")
plt.show()