Python课本 朱荣 实例代码修改+怎么看层次聚类树图

原实例在IDLE中可以运行(需相应配置)

若在Spyder中运行,则需改成以下代码:
课本P197页 实例6-4 的代码修改为:

#from sklearn.datasets.samples_generator import make_blobs
from sklearn.datasets import make_blobs
from sklearn.cluster import AgglomerativeClustering
import matplotlib.pyplot as plt
from sklearn import metrics

#生成数据
X,lables_true=make_blobs(n_samples=1000,centers=[[1,1],[-1,-1],[1,-1]])

#层次类聚
ccj=AgglomerativeClustering(n_clusters=3)

#训练数据
y_pred=ccj.fit_predict(X)

#每个数据的分类
lables=ccj.labels_

#划分子图
figure=plt.figure()
axes1=figure.add_subplot(2,1,1)
axes2=figure.add_subplot(2,1,2)

#绘制子图
x0=X[lables==0]
x1=X[lables==1]
x2=X[lables==2]

axes1.scatter(x0[:,0],x0[:,1],c="r",marker='D',label='label0')
axes1.scatter(x0[:,0],x0[:,1],c="g",marker='*',label='label1')
axes1.scatter(x0[:,0],x0[:,1],c="b",marker='+',label='label2')
axes1.legend()

#绘制子图2
axes2.scatter(X[:,0],X[:,1],c=lables)
plt.show()
print("聚类得分:",metrics.calinski_harabasz_score(X, y_pred))


附上几个网页:
教你怎么看聚类分析的树状图 - 百度经验

Guess you like

Origin blog.csdn.net/CSDN_YJX/article/details/120736488