เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การเทรน K-means

เมื่อ RDD พร้อมสำหรับการเทรนแล้ว ในส่วนที่ 2 นี้ จะทดสอบด้วยค่า k ตั้งแต่ 13 ถึง 16 (เพื่อประหยัดเวลาในการคำนวณ) และใช้ elbow method เพื่อเลือกค่า k ที่เหมาะสม แนวคิดของ elbow method คือการรัน K-means clustering บนชุดข้อมูลด้วยค่า k ที่แตกต่างกัน คำนวณค่า Within Set Sum of Squared Error (WSSSE) แล้วเลือกค่า k ที่ดีที่สุดจากจุดที่ WSSSE ลดลงอย่างชัดเจน (จุดที่เรียกว่า elbow) จากนั้นจะเทรนโมเดลใหม่ด้วยค่า k ที่ดีที่สุด และสุดท้ายดึงค่า centroids (cluster centers) ออกมา

โปรดจำไว้ว่า SparkContext sc และ rdd_split_int RDD พร้อมใช้งานใน workspace ของคุณแล้ว

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Big Data Fundamentals with PySpark

ดูคอร์ส

คำแนะนำการฝึกหัด

  • เทรนโมเดล KMeans โดยใช้จำนวน cluster ตั้งแต่ 13 ถึง 16 และพิมพ์ค่า WSSSE ของแต่ละ cluster
  • เทรนโมเดล KMeans อีกครั้งด้วยค่า k ที่ดีที่สุด
  • ดึงค่า Cluster Centers (centroids) ของโมเดล KMeans ที่เทรนด้วยค่า k ที่ดีที่สุด

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# 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.____
แก้ไขและรันโค้ด