需求: 基于scikit的API創(chuàng)建模擬數(shù)據(jù)蹭劈,使用BIRCH算法對數(shù)據(jù)進行聚類操作毫捣,并比較n_clusters參數(shù)的作用行瑞。
相關(guān)API:https://scikit-learn.org/stable/modules/generated/sklearn.cluster.Birch.html
參數(shù)threshold: 代表了FC-Tree中的參數(shù)T嘹朗。葉子節(jié)點中每個CF的最大半徑閾值T。決定了每個聚類特征所有樣本形成的超球體的半徑值域诲侮。一般來說如果threshold越小镀虐,說明CF樹在建立的時候規(guī)模會比較大。具體選擇多大沟绪,還是要通過調(diào)參來決定刮便。默認值0.5的效果其實還可以,但如果數(shù)據(jù)方差比較大的時候绽慈,一般需要增大threshold的值恨旱。因為樣本大意味著數(shù)據(jù)比較離散,如果設(shè)置threshold特別小的話坝疼,每個聚類特征中將只有很少的元素搜贤,CF樹會沒完沒了得生產(chǎn)新的聚類特征CF。
參數(shù)branching_factor: 代表了CF-Tree中的參數(shù)B=L钝凶,即允許最大葉子聚類特征CF數(shù)量仪芒,和允許每個樹節(jié)點的最大聚類特征CF數(shù)量一致,都等于branching_factor耕陷。默認值是50掂名,但如果樣本量特別大的時候,比如10萬條數(shù)據(jù)哟沫,那么要相對增多branching_factor的值饺蔑。具體要增大多少?請調(diào)參后再慢慢分析嗜诀。
參數(shù)n_clusters: 聚類類別數(shù)猾警,在BIRCH中是可選的。如果類別數(shù)特別多裹虫,我們又沒有先驗知識的情況下肿嘲,n_clusters用None即可。http://www.cnblogs.com/lc1217/p/6963687.html
參數(shù)compute_labels: 是否輸出聚類結(jié)果; 默認可以筑公。
常規(guī)操作:
from itertools import cycle
from time import time
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import Birch
from sklearn.datasets.samples_generator import make_blobs
## 設(shè)置屬性防止中文亂碼
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
## 產(chǎn)生模擬數(shù)據(jù)
xx = np.linspace(-22, 22, 10)
yy = np.linspace(-22, 22, 10)
xx, yy = np.meshgrid(xx, yy)
n_centres = np.hstack((np.ravel(xx)[:, np.newaxis],
np.ravel(yy)[:, np.newaxis]))
#產(chǎn)生10萬條特征屬性是2雳窟,類別是100,符合高斯分布的數(shù)據(jù)集
X, y = make_blobs(n_samples=100000,n_features=2, centers=n_centres, random_state=28)
1、創(chuàng)建不同的參數(shù)(簇直徑)Birch層次聚類
threshold:簇直徑的閾值匣屡, branching_factor:大葉子個數(shù)
我們也可以加參數(shù)來試一下效果封救,比如加入分支因子branching_factor,給定不同的參數(shù)值捣作,看聚類的結(jié)果誉结。
birch_models = [
Birch(threshold=2, n_clusters=None),
Birch(threshold=0.5, n_clusters=None),
Birch(threshold=1.7, n_clusters=100)
]
2、 畫圖
final_step = [u'直徑=1.7;n_lusters=None',u'直徑=0.5;
n_clusters=None',u'直徑=1.7;n_lusters=100']
plt.figure(figsize=(12,8),facecolor='w')
plt.subplots_adjust(left = 0.02, right = 0.98, bottom = 0.1,top = 0.9)
colors_ = cycle(colors.cnames.keys())
cm = mpl.colors.ListedColormap(colors.cnames.keys())
for ind, (birch_model, info) in enumerate(zip(birch_models, final_step)):
t = time()
birch_model.fit(X)
time_ = time() - t
#獲取模型結(jié)果(label和中心點)
# 所屬類別
labels = birch_model.labels_
# 中心點坐標
centroids = birch_model.subcluster_centers_
n_clusters = len(np.unique(centroids))
print ("Birch算法券躁,參數(shù)信息為:%s惩坑;模型構(gòu)建消耗時間為:%.3f秒掉盅;
聚類中心數(shù)目:%d" % (info, time_, len(np.unique(labels))))
## 畫圖
subinx = 221 + ind
plt.subplot(subinx)
for this_centroid, k, col in zip(centroids, range(n_clusters), colors_):
mask = labels == k
plt.plot(X[mask, 0], X[mask, 1], 'w', markerfacecolor=col, marker='.')
if birch_model.n_clusters is None:
plt.plot(this_centroid[0], this_centroid[1], '*',
markerfacecolor=col, markeredgecolor='k', markersize=2)
plt.ylim([-25, 25])
plt.xlim([-25, 25])
plt.title(u'Birch算法%s,耗時%.3fs' % (info, time_))
plt.grid(False)
## 原始數(shù)據(jù)集顯示
plt.subplot(224)
plt.scatter(X[:, 0], X[:, 1], c=y, s=1, cmap=cm, edgecolors='none')
plt.ylim([-25, 25])
plt.xlim([-25, 25])
plt.title(u'原始數(shù)據(jù)')
plt.grid(False)
plt.show()
如果使用第一組參數(shù)以舒,不設(shè)置類別趾痘,生成了158個聚類中心,和原始數(shù)據(jù)的結(jié)果還不太像蔓钟,說明效果還不太好永票。
當直徑減少以后,運算的時間變長了滥沫。聚類中心的個數(shù)變成了3205個侣集,密密麻麻的聚類中心,效果明顯不對兰绣。
強行設(shè)置聚類中心為100個的時候效果最好世分,和原始數(shù)據(jù)最接近。
所以具體哪個效果好狭魂,哪個效果不好都是需要通過調(diào)參來決定的罚攀。
重點將K-Means算法和Mini Batch K-Means算法的調(diào)參做一做。
04 聚類算法 - 代碼案例一 - K-means聚類
06 聚類算法 - 代碼案例二 - K-Means算法和Mini Batch K-Means算法比較
07 聚類算法 - 代碼案例三 - K-Means算法和Mini Batch K-Means算法效果評估
以上是層次聚類的一種算法演示雌澄。下面開始介紹另一種聚類的思路:密度聚類