import numpy as np
from sklearn.datasets import load_iris
iris=load_iris()
x=iris.data[:,1]
y=np.zeros(150)
def initcent(x,k): #初始聚类中心数组
return x[0:k].reshape(k)
def nearest(kc,i): #数组中的值,与聚类中心最小距离所在类别的索引号
d=(abs(kc-i))
w=np.where(d==np.min(d))
return w[0][0]
def kcmean (x,y,kc,k): #计算各聚类新均值
l=list(kc)
flag=False
for c in range(k):
m=np.where(y==c)
n=np.mean(x[m])
if l[c] !=n:
l[c]=n
flag=True #聚类中心发生变化
return (np.array(l),flag)
def xclassify(x,y,kc):
for i in range (x.shape[0]): #对数组的每个值分类
y[i]=nearest(kc,x[i])
return y
flag = True
print(x,y,kc,flag)
while flag:
y = xclassify(x,y,kc)
kc,flag = kcmean(x,y,kc,k)
print(y,kc,type(kc))
![](https://img2018.cnblogs.com/blog/1482929/201810/1482929-20181025161622930-943528994.png)
import matplotlib.pyplot as plt
plt.scatter(x,x,c=y,s=50,cmap='rainbow',marker='p',alpha=0.5);
plt.show()
![](https://img2018.cnblogs.com/blog/1482929/201810/1482929-20181025161745731-624810130.png)