【Python例項第17講】均值偏移聚類演算法
阿新 • • 發佈:2018-11-29
機器學習訓練營——機器學習愛好者的自由交流空間(qq 群號:696721295)
均值偏移(mean shift
)是一個非引數特徵空間分析技術,用來尋找密度函式的最大值點。它的應用領域包括聚類分析和影象處理等。
均值偏移演算法
均值偏移是一個迭代地求密度函式極值點的方法。首先,從一個初始估計 出發。這裡要給定一個核函式 , 典型採用的是高斯核。核函式用來確定 的鄰近點的權,而這些鄰近點用來重新計算均值。這樣,在 點的密度的加權均值
其中, 是 的鄰居集。稱
是mean shift
. 現在,升級
的值為
, 重複這個估計過程,直到
收斂。
以下是一個迭代過程的示意圖。
聚類應用
均值偏移聚類的目的是發現來自平滑密度的樣本團(‘blobs’). 它是一個基於質心的演算法,當質心的改變很小時,將停止搜尋。因此,它能夠自動設定類數,這是與k-means
聚類法的顯著區別。當確定所有質心後,質心對應類。對於每一個樣本點,將它歸於距離最近的質心代表的類裡。
A demo example
import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth
from sklearn.datasets.samples_generator import make_blobs
# #############################################################################
# Generate sample data
centers = [[1, 1], [-1, -1], [1, -1]]
X, _ = make_blobs(n_samples=10000, centers=centers, cluster_std=0.6)
# #############################################################################
# Compute clustering with MeanShift
# The following bandwidth can be automatically detected using
bandwidth = estimate_bandwidth(X, quantile=0.2, n_samples=500)
ms = MeanShift(bandwidth=bandwidth, bin_seeding=True)
ms.fit(X)
labels = ms.labels_
cluster_centers = ms.cluster_centers_
labels_unique = np.unique(labels)
n_clusters_ = len(labels_unique)
print("number of estimated clusters : %d" % n_clusters_)
# #############################################################################
# Plot result
import matplotlib.pyplot as plt
from itertools import cycle
plt.figure(1)
plt.clf()
colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk')
for k, col in zip(range(n_clusters_), colors):
my_members = labels == k
cluster_center = cluster_centers[k]
plt.plot(X[my_members, 0], X[my_members, 1], col + '.')
plt.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,
markeredgecolor='k', markersize=14)
plt.title('Estimated number of clusters: %d' % n_clusters_)
plt.show()
number of estimated clusters : 3
閱讀更多精彩內容,請關注微信公眾號:統計學習與大資料