层次聚类法
运行结果
Kmeans方法
数据点的分布
聚类结果
代码
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage,dendrogram,fcluster
from sklearn.cluster import KMeans
def hierarchy_way():
#生成数据
data = []
for i in range(1,11):
data.append(np.random.randint(10*(i-1),10*i,size=(5,)))
#画图
mergings = linkage(data,method="average")
print(data)
fig = plt.figure(figsize=(10,6))
dendrogram(mergings)
plt.show()
def Kmeans_way():
#生成数据
x = []
y = []
for i in range(1,10,3):
tx = np.random.randn(50,)
ty = np.random.randn(50,)
x += [item+i for item in tx]
y += [item+i for item in ty]
point = []
for i in range(len(x)):
t = [ x[i],y[i] ]
point.append(t)
model = KMeans(n_clusters=3)
model.fit(point)#分组
centers = model.cluster_centers_
print(centers)
labels = model.labels_
print(labels)
center_x = centers[:,0]
center_y = centers[:,1]
plt.scatter(x,y,c=labels)
plt.scatter(center_x,center_y,marker='X',s=100,c='r')
plt.show()
if __name__ == '__main__':
Kmeans_way()
说明
通过随机函数生成数据进行聚类分析,了解了Python关于聚类分析的相关库。
然后…哎呀~谁的头发