Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การนำ Mean Shift Algorithm ไปใช้ใน Python ด้วย scikit-learn

บทนำ

Mean Shift เป็น Clustering Algorithm แบบ Unsupervised Learning ไม่ต้องกำหนดจำนวน Cluster ล่วงหน้า (ต่างจาก K-Means) ทำงานโดยย้าย Data Points ไปยังจุดหนาแน่นที่สุด (Centroid) ซ้ำๆ จน收敛

ขั้นตอน Mean Shift

  1. กำหนดแต่ละ Data Point เป็น Cluster ของตัวเอง
  2. หา Centroid ของแต่ละ Cluster
  3. อัปเดตตำแหน่ง Centroid ไปยังพื้นที่หนาแน่นกว่า
  4. ทำซ้ำจน Centroid ไม่เคลื่อนที่แล้ว

ตัวอย่างโค้ด

import numpy as np
from sklearn.cluster import MeanShift
import matplotlib.pyplot as plt
from matplotlib import style
from sklearn.datasets import make_blobs

style.use("ggplot")
centers = [[3,3,1], [4,5,5], [11,10,10]]
X, _ = make_blobs(n_samples=950, centers=centers, cluster_std=0.89)

plt.title("Implementation of Mean-Shift algorithm")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.scatter(X[:,0], X[:,1])
plt.show()

ms = MeanShift()
ms.fit(X)
labels = ms.labels_
clusterCent = ms.cluster_centers_
print(clusterCent)
numCluster = len(np.unique(labels))
print("Estimated clusters:", numCluster)

colors = 10*['r.', 'g.', 'b.', 'c.', 'k.', 'y.', 'm.']
for i in range(len(X)):
    plt.plot(X[i][0], X[i][1], colors[labels[i]], markersize=3)
plt.scatter(clusterCent[:,0], clusterCent[:,1], marker=".", color='k', s=20, linewidths=5, zorder=10)
plt.show()

ผลลัพธ์

[[ 3.05250924  3.03734994  1.06159541]
 [ 3.92913017  4.99956874  4.86668482]
 [10.99127523 10.02361122 10.00084718]]
Estimated clusters: 3

คำอธิบาย

  • ใช้ make_blobs สร้างข้อมูลทดสอบ 3 กลุ่ม

  • เรียก MeanShift().fit(X)

  • ดึง labels_ และ cluster_centers_

  • พลอตผลลัพธ์ พร้อมแสดง Centroid