import numpy as np
x = np.random.randint(1,50,[20,1])
y = np.zeros(20)
k = 3
def initcen(x,k): #选取数据空间中的K个对象作为初始中心,每个对象代表一个聚类中心
return x[:k]
def nearest(kc,i): #对于样本中的数据对象,根据它们与这些聚类中心的欧氏距离,按距离最近的准则将它们分到距离它们最近的聚类中心(最相似)所对应的类;
p = abs(kc-i)
q = np.where(p == np.min(p))
return q[0][0]
def xclassify(x,y,kc):
for i in range(x.shape[0]):
y[i]= nearest(kc,x[i])
return y
def kcmean(x,y,kc,k): #更新聚类中心:将每个类别中所有对象所对应的均值作为该类别的聚类中心,计算目标函数的值
l = list(kc)
flag = False
for c in range(k):
m = np.where(y == 0)
n = np.mean(x[m])
if l[c] != n:
l[c] = n
flag = True
print(l,flag)
return(np.array(l),flag)
kc = initcen(x,k) #判断聚类中心和目标函数的值是否发生改变,若不变,则输出结果,若改变,则返回2)
flag = True
print(x,y,kc,flag)
while flag:
y = xclassify(x,y,kc)
kc,flag = kcmean(x,y,kc,k)
print(y,kc)
运行结果:
from sklearn.datasets import load_iris # 导入鸢尾花数据集,鸢尾花花瓣长度数据做聚类并用散点图显示
iris = load_iris()
datas = iris.data
iris_length=datas[:,2]
x = np.array(iris_length) #用鸢尾花花瓣长度做分析
y = np.zeros(x.shape[0])
kc = initcen(x,3)
flag = True
while flag:
y = xclassify(x,y,kc)
kc,flag = kcmean(x,y,kc,3)
print(kc,flag)
import matplotlib.pyplot as plt
plt.scatter(iris_length, iris_length, marker='D', c=y, alpha=0.5) #散点图
plt.show()
运行结果:
from sklearn.cluster import KMeans #用sklearn.cluster.KMeans,鸢尾花花瓣长度数据做聚类并用散点图显示
iris_length = datas[:, 2:3]
k_means = KMeans(n_clusters=3)
result = k_means.fit(iris_length)
kc1 = result.cluster_centers_
y_kmeans = k_means.predict(iris_length)
plt.scatter(iris_length,np.linspace(1,150,150),c=y_kmeans,marker='D') #散点图
plt.show()
运行结果:
k_means1 = KMeans(n_clusters=3) #鸢尾花完整数据做聚类并用散点图显示
result1 = k_means1.fit(datas)
kc2 = result1.cluster_centers_
y_kmeans1 = k_means1.predict(datas)
print(y_kmeans1, kc2)
print(kc2.shape, y_kmeans1.shape, datas.shape)
plt.scatter(datas[:, 0], datas[:, 1], c=y_kmeans1, marker='p')
plt.show()
运行结果: