吳裕雄 python 機器學習——密度聚類DBSCAN模型

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 #密度聚類DBSCAN模型
def test_DBSCAN(*data): X,labels_true=data clst=cluster.DBSCAN() predicted_labels=clst.fit_predict(X) print("ARI:%s"% adjusted_rand_score(labels_true,predicted_labels)) print("Core sample num:%d"%len(clst.core_sample_indices_)) # 用於產生聚類的中心點
centers=[[1,1],[2,2],[1,2],[10,20]] # 產生用於聚類的數據集
X,labels_true=create_data(centers,1000,0.5) # 調用 test_DBSCAN 函數
test_DBSCAN(X,labels_true)

def test_DBSCAN_epsilon(*data): ''' 測試 DBSCAN 的聚類結果隨 eps 參數的影響 ''' X,labels_true=data epsilons=np.logspace(-1,1.5) ARIs=[] Core_nums=[] for epsilon in epsilons: clst=cluster.DBSCAN(eps=epsilon) predicted_labels=clst.fit_predict(X) ARIs.append( adjusted_rand_score(labels_true,predicted_labels)) Core_nums.append(len(clst.core_sample_indices_)) ## 繪圖
    fig=plt.figure() ax=fig.add_subplot(1,2,1) ax.plot(epsilons,ARIs,marker='+') ax.set_xscale('log') ax.set_xlabel(r"$\epsilon$") ax.set_ylim(0,1) ax.set_ylabel('ARI') ax=fig.add_subplot(1,2,2) ax.plot(epsilons,Core_nums,marker='o') ax.set_xscale('log') ax.set_xlabel(r"$\epsilon$") ax.set_ylabel('Core_Nums') fig.suptitle("DBSCAN") plt.show() # 調用 test_DBSCAN_epsilon 函數
test_DBSCAN_epsilon(X,labels_true)

def test_DBSCAN_min_samples(*data): ''' 測試 DBSCAN 的聚類結果隨 min_samples 參數的影響 ''' X,labels_true=data min_samples=range(1,100) ARIs=[] Core_nums=[] for num in min_samples: clst=cluster.DBSCAN(min_samples=num) predicted_labels=clst.fit_predict(X) ARIs.append( adjusted_rand_score(labels_true,predicted_labels)) Core_nums.append(len(clst.core_sample_indices_)) ## 繪圖
    fig=plt.figure() ax=fig.add_subplot(1,2,1) ax.plot(min_samples,ARIs,marker='+') ax.set_xlabel( "min_samples") ax.set_ylim(0,1) ax.set_ylabel('ARI') ax=fig.add_subplot(1,2,2) ax.plot(min_samples,Core_nums,marker='o') ax.set_xlabel( "min_samples") ax.set_ylabel('Core_Nums') fig.suptitle("DBSCAN") plt.show() # 調用 test_DBSCAN_min_samples 函數
test_DBSCAN_min_samples(X,labels_true)

相關文章
相關標籤/搜索