吳裕雄 python 機器學習——層次聚類AgglomerativeClustering模型
阿新 • • 發佈:2019-05-01
figure div fig ted app 中心 import pan clas
import numpy as np import matplotlib.pyplot as plt from sklearn import cluster from sklearn.metrics import adjusted_rand_score from sklearn.datasets.samples_generator import make_blobs def create_data(centers,num=100,std=0.7): X, labels_true = make_blobs(n_samples=num, centers=centers, cluster_std=std)return X,labels_true #層次聚類AgglomerativeClustering模型 def test_AgglomerativeClustering(*data): ‘‘‘ 測試 AgglomerativeClustering 的用法 ‘‘‘ X,labels_true=data clst=cluster.AgglomerativeClustering() predicted_labels=clst.fit_predict(X) print("ARI:%s"% adjusted_rand_score(labels_true,predicted_labels))# 用於產生聚類的中心點 centers=[[1,1],[2,2],[1,2],[10,20]] # 產生用於聚類的數據集 X,labels_true=create_data(centers,1000,0.5) # 調用 test_AgglomerativeClustering 函數 test_AgglomerativeClustering(X,labels_true)
def test_AgglomerativeClustering_nclusters(*data): ‘‘‘ 測試 AgglomerativeClustering 的聚類結果隨 n_clusters 參數的影響‘‘‘ X,labels_true=data nums=range(1,50) ARIs=[] for num in nums: clst=cluster.AgglomerativeClustering(n_clusters=num) predicted_labels=clst.fit_predict(X) ARIs.append(adjusted_rand_score(labels_true,predicted_labels)) ## 繪圖 fig=plt.figure() ax=fig.add_subplot(1,1,1) ax.plot(nums,ARIs,marker="+") ax.set_xlabel("n_clusters") ax.set_ylabel("ARI") fig.suptitle("AgglomerativeClustering") plt.show() # 調用 test_AgglomerativeClustering_nclusters 函數 test_AgglomerativeClustering_nclusters(X,labels_true)
def test_AgglomerativeClustering_linkage(*data): ‘‘‘ 測試 AgglomerativeClustering 的聚類結果隨鏈接方式的影響 ‘‘‘ X,labels_true=data nums=range(1,50) fig=plt.figure() ax=fig.add_subplot(1,1,1) linkages=[‘ward‘,‘complete‘,‘average‘] markers="+o*" for i, linkage in enumerate(linkages): ARIs=[] for num in nums: clst=cluster.AgglomerativeClustering(n_clusters=num,linkage=linkage) predicted_labels=clst.fit_predict(X) ARIs.append(adjusted_rand_score(labels_true,predicted_labels)) ax.plot(nums,ARIs,marker=markers[i],label="linkage:%s"%linkage) ax.set_xlabel("n_clusters") ax.set_ylabel("ARI") ax.legend(loc="best") fig.suptitle("AgglomerativeClustering") plt.show() # 調用 test_AgglomerativeClustering_linkage 函數 test_AgglomerativeClustering_linkage(X,labels_true)
吳裕雄 python 機器學習——層次聚類AgglomerativeClustering模型