Mean Shift là thuật toán clustering phi tham số (non-parametric), không cần chỉ định số cluster trước. Dịch chuyển điểm dữ liệu về phía mật độ cao nhất (centroid) cho đến hội tụ.
Các bước
- Mỗi điểm là một cluster riêng.
- Tìm centroid của từng cluster.
- Cập nhật vị trí centroid lặp lại về vùng mật độ cao hơn.
- Dừng khi centroid không di chuyển thêm.
Ví dụ với scikit-learn
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("Mean-Shift Clustering")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.scatter(X[:,0], X[:,1])
plt.show()
ms = MeanShift()
ms.fit(X)
labels = ms.labels_
cluster_centers = ms.cluster_centers_
print(cluster_centers)
print("Estimated clusters:", len(np.unique(labels)))
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(cluster_centers[:,0], cluster_centers[:,1],
marker=".", color='k', s=20, linewidths=5, zorder=10)
plt.show()
Kết quả

[[ 3.0525 3.0373 1.0616]
[ 3.9291 4.9996 4.8667]
[10.9913 10.0236 10.0008]]
Estimated clusters: 3

Giải thích
make_blobstạo 3 cụm Gaussian 3D.MeanShift()tự động tìm 3 cluster, centroid gần đúng centers ban đầu.- Khác với K-Means: không cần
n_clusters, tự tìm số lượng.