大师兄的数据分析学习笔记(三十四):模型评估(三)

2022-11-11  本文已影响0人  superkmi

大师兄的数据分析学习笔记(三十三):模型评估(二)
大师兄的数据分析学习笔记(三十五):总结

三、聚类模型评估

  • RMS(Root Mean Square)RMS = \frac{1}{n}\sqrt{\sum_{i=1}^n(x_i-\overline{x})^2}
    RMS越小聚类效果越好,越大说明每个类和中心距离越远,效果较差。
  • 轮廓系数s(i) = \frac{b(i)-a(i)}{max\{a(i),b(i)\}}
    a(i)为样本i与簇内其它样本的平均距离;
    b(i)为样本i与其它某簇样本的平均距离,多个簇b(i)取最小。
    轮廓系数约接近1聚类效果越好,约接近-1效果越差。
>>>import numpy as np
>>>import matplotlib.pyplot as plt
>>>from sklearn.datasets import make_circles,make_blobs,make_moons
>>>from sklearn.cluster import AgglomerativeClustering,DBSCAN,KMeans
>>>from sklearn.metrics import silhouette_score

>>>n_samples = 1000
>>>circles = make_circles(n_samples=n_samples,factor=0.5,noise=0.05)
>>>moons = make_moons(n_samples=n_samples,noise=0.05)
>>>blobs = make_blobs(n_samples=n_samples,random_state=8,center_box=(-1,1),cluster_std=0.1)
>>>random_data = np.random.rand(n_samples,2),None
>>>colours = "bgrcmyk"
>>>data = [circles,moons,blobs,random_data]
>>>models = [("None",None),("KMeans",KMeans(n_clusters=3)),("DBSCAN",DBSCAN(min_samples=3,eps=0.2)),("Agglomerative",AgglomerativeClustering(n_clusters=3,linkage="ward"))]

>>>fig = plt.figure()

>>>for inx,clt in enumerate(models):
>>>    clt_name,clt_entity = clt
>>>    for i,dataset in enumerate(data):
>>>        X,Y = dataset
>>>        if not clt_entity:
>>>            clt_res = [0 for item in range(len(X))]
>>>        else:
>>>            clt_entity.fit(X)
>>>            clt_res = clt_entity.labels_.astype(int)
>>>        fig.add_subplot(len(models),len(data),inx*len(data)+i+1)
>>>        plt.title(clt_name)
>>>        try:
>>>            print(clt_name,i,silhouette_score(X,clt_res))
>>>        except Exception as e:
>>>            ...
>>>        [plt.scatter(X[p,0],X[p,1],color=colours[clt_res[p]]) for p in range(len(X))]
>>>plt.show()
KMeans 0 0.3916325558787827
KMeans 1 0.42678036476765324
KMeans 2 0.8260921886020176
KMeans 3 0.3858371416901683
DBSCAN 0 0.11129304972156648
DBSCAN 1 0.33236515056456195
DBSCAN 2 0.8260921886020176
Agglomerative 0 0.34487993798844285
Agglomerative 1 0.3885474739703062
Agglomerative 2 0.8260921886020176
Agglomerative 3 0.366701613284125
上一篇下一篇

猜你喜欢

热点阅读