''' 聚類之均值漂移:首先假定樣本空間中的每個聚類均服從某種已知的概率分布規則,然后用不同的概率密度函數擬合樣本中的統計直方圖, 不斷移動密度函數的中心(均值)的位置,直到獲得最佳擬合效果為止。這些概率密度函數的峰值點就是聚類的中心, 再根據每個樣本距離各個中心的距離,選擇最近聚類中心所屬的類別作為該樣本的類別。 均值漂移算法的特點: 1.聚類數不必事先已知,算法會自動識別出統計直方圖的中心數量。 2.聚類中心不依據於最初假定,聚類划分的結果相對穩定。 3.樣本空間應該服從某種概率分布規則,否則算法的准確性會大打折扣。 均值漂移算法相關API: # 量化帶寬,決定每次調整概率密度函數的步進量 # n_samples:樣本數量 # quantile:量化寬度(直方圖一條的寬度) # bw為量化帶寬對象 bw = sc.estimate_bandwidth(x, n_samples=len(x), quantile=0.1) # 均值漂移聚類器 model = sc.MeanShift(bandwidth=bw, bin_seeding=True) model.fit(x) 案例:加載multiple3.txt,使用均值漂移算法對樣本完成聚類划分。 ''' import numpy as np import matplotlib.pyplot as mp import sklearn.cluster as sc # 讀取數據,繪制圖像 x = np.loadtxt('./ml_data/multiple3.txt', unpack=False, dtype='f8', delimiter=',') print(x.shape) # 基於MeanShift完成聚類 bw = sc.estimate_bandwidth(x, n_samples=len(x), quantile=0.1) model = sc.MeanShift(bandwidth=bw, bin_seeding=True) model.fit(x) # 完成聚類 pred_y = model.predict(x) # 預測點在哪個聚類中 print(pred_y) # 輸出每個樣本的聚類標簽 # 獲取聚類中心 centers = model.cluster_centers_ print(centers) # 繪制分類邊界線 l, r = x[:, 0].min() - 1, x[:, 0].max() + 1 b, t = x[:, 1].min() - 1, x[:, 1].max() + 1 n = 500 grid_x, grid_y = np.meshgrid(np.linspace(l, r, n), np.linspace(b, t, n)) bg_x = np.column_stack((grid_x.ravel(), grid_y.ravel())) bg_y = model.predict(bg_x) grid_z = bg_y.reshape(grid_x.shape) # 畫圖顯示樣本數據 mp.figure('MeanShift', facecolor='lightgray') mp.title('MeanShift', fontsize=16) mp.xlabel('X', fontsize=14) mp.ylabel('Y', fontsize=14) mp.tick_params(labelsize=10) mp.pcolormesh(grid_x, grid_y, grid_z, cmap='gray') mp.scatter(x[:, 0], x[:, 1], s=80, c=pred_y, cmap='brg', label='Samples') mp.scatter(centers[:, 0], centers[:, 1], s=300, color='red', marker='+', label='cluster center') mp.legend() mp.show() 輸出結果: (200, 2) [1 1 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 1 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 3 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 1 3 0 1 2 3 0 1 2 3 2 1 2 3 0 1 2 3 0 1 1 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0] [[6.87444444 5.57638889] [1.86416667 2.03333333] [3.45088235 5.27323529] [5.90964286 2.40357143]]