@K-means,聚类算法(简) 分为两个聚类
用的是Spyder编辑器
用到绘图库
和numpy
import numpy as np
import matplotlib.pyplot as plt
x=np.array([[1,2],[1.5,1.8],[5,8],[8,8],[1,0.6],[9,10]])
np.random.seed(5)
x=np.random.rand(10000).reshape(-1,2)
k=2
medoids=[x[1],x[2]]
max_iter=100
for t in range(max_iter): #迭代次数
cluster1=[]
cluster2=[]
#计算所有点与中心点的距离,根据就近原则将点分配到最近的那个中心所对应的簇
for i in range(len(x)):
d1=np.sum(np.square(x[i]-medoids[0]))
d2=np.sum(np.square(x[i]-medoids[1]))
if d1<=d2:
cluster1.append(x[i])
else:
cluster2.append(x[i])
medoids=[np.mean(cluster1,axis=0),np.mean(cluster2,axis=0)]
print(medoids)
cluster1=np.array(cluster1)
cluster2=np.array(cluster2)
plt.plot(cluster1[:,0],cluster1[:,1],'r*')
plt.plot(cluster2[:,0],cluster2[:,1],'g*')