كل المقررات

الرئيسية / مقرر Machine Learning / الفصل 9 الجزء 1

الفصل 9 (الجزء 1): Unsupervised Learning

Clustering with K-Means and DBSCAN

الفصل الأخير عن الـ Unsupervised Learning. في الجزء ده هنتعلّم الـ Clustering: K-Means وإزاي نختار k، وكمان DBSCAN.

فيديو المحاضرة

فيديو المحاضرة

بعد الفيديو: الأمثلة والاختبار والتمارين والمشروع الصغير تحت.

أمثلة Python

أمثلة صغيرة بالـ scikit-learn

الكود والنتيجة معروضين هنا كنص ثابت (النتائج اتجرّبت فعلاً). لتشغيل الكود بنفسك انسخه في Google Colab المجاني. تقدر كمان تفتح الدفتر الرسمي للكتاب (ترخيص Apache-2.0) من الرابط تحت.

المثال ١: K-Means على blobs

Sample output (press Run to produce your own):
cluster sizes: [150, 150, 150, 150]
inertia: 721.5
center of the first cluster: [9.54 0.72]

المثال ٢: اختيار k

Sample output (press Run to produce your own):
k = 2 | inertia 17985 | silhouette 0.6
k = 3 | inertia 4818 | silhouette 0.783
k = 4 | inertia 722 | silhouette 0.849
k = 5 | inertia 655 | silhouette 0.73
k = 6 | inertia 586 | silhouette 0.593
k = 7 | inertia 524 | silhouette 0.45

المثال ٣: DBSCAN على moons

Sample output (press Run to produce your own):
K-Means agrees with the true shapes: 0.762
DBSCAN clusters found: [0, 1] | agreement: 1.0

افتح الدفتر الرسمي في Colab

اختبار قصير

اختبر فهمك

1. K-Means alternates between:

2. Why run K-Means several times (n_init)?

3. A higher silhouette score means:

4. In DBSCAN, a label of -1 means:

5. Which method can find a crescent-shaped cluster?

تمارين برمجة

جرّب بإيدك

التمرين 1

على blobs جرّب n_init = 1 ثم 10 مع random_state مختلف (0, 1, 2) واطبع الـ inertia. إيه اللي يتغيّر؟

On the blobs try n_init = 1 and 10 with random_state 0, 1, 2 and print the inertia. What changes?

(output appears here)

التمرين 2

جرّب DBSCAN بـ eps = 0.05 و 0.2 و 0.6 على moons واطبع عدد المجموعات وعدد نقط الـ noise.

Try DBSCAN with eps = 0.05, 0.2 and 0.6 on moons and print the number of clusters and noise points.

(output appears here)

مشروع صغير في آخر المحاضرة

جمّع أنواع الزهور من غير ما تعرف أسماءها

الداتا: Iris dataset: 150 flowers, 4 measurements, 3 species. Source: Fisher, 1936 (UCI repository).

License / source: Ships with scikit-learn; open data from the UCI repository. Dataset page

الخطوات

  1. حمّل iris وخد الـ ٤ features بس من غير الـ labels.
  2. اعمل StandardScaler.
  3. جرّب k من 2 لـ 6 واطبع silhouette لكل k.
  4. اختار أحسن k وقارن مجموعاته بالأنواع الحقيقية بجدول (pandas crosstab).
  5. اكتب: هل اختيار k أعطاك ٣ مجموعات؟ وليه؟
Expected output (press Run to produce your own):
k = 2 silhouette 0.582
k = 3 silhouette 0.46
k = 4 silhouette 0.387
k = 5 silhouette 0.346
k = 6 silhouette 0.326
best k: 2
cluster (k=3)   0   1   2
species                  
setosa          0  50   0
versicolor     39   0  11
virginica      14   0  36

Credits: topic order follows the public chapter list of Aurélien Géron's book "Hands-On Machine Learning with Scikit-Learn, Keras and TensorFlow" (3rd ed.). All explanations and code here are original.