首页 > 编程语言 > 详细

吴裕雄 python 机器学习——层次聚类AgglomerativeClustering模型

时间:2019-05-01 10:48:55      阅读:496      评论:0      收藏:0      [点我收藏+]
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模型

原文:https://www.cnblogs.com/tszr/p/10799038.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!