import numpy as npx = np.random.randint(1,100,[20,1])y = np.zeros(20)k = 3x
def initcenter(x, k):#初始聚类中心数组 return x[:k]kc = initcenter(x,k)kc
def initcenter(x,k):#初始聚类中心数组 return x[:k]def nearest(kc,i): d=(abs(kc - i)) #距离绝对值 w=np.where(d==np.min(d)) return w[0][0] #def xclassify(x,y,kc): for i in range(x.shape[0]):#对数组的每个值进行分类 y[i]=nearest(kc,x[i]) return ykc=initcenter(x,k)y=xclassify(x,y,kc)print(kc,y)
import numpy as npfrom sklearn.datasets import load_iris iris = load_iris()x = iris.data[:,1]y = np.zeros(150)def initcenter(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 xclassify(x,y,kc): for i in range(x.shape[0]): #对数组的每个值进行分类 y[i] = nearest(kc,x[i]) return ydef kcmean(x,y,kc,k): #计算各聚类新均值 l = list(kc) flag = False for c in range(k): print(c) m = np.where(y == c) n=np.mean(x[m]) if l[c] != n: l[c] = n flag = True #聚类中心发生变化 print(l,flag) return (np.array(l),flag)k = 3kc = initcenter(x,k)flag = Trueprint(x,y,kc,flag)#判断聚类中心和目标函数的值是否发生改变,若不变,则输出结果,若改变,则返回2while flag: y = xclassify(x,y,kc) kc, flag = kcmean(x,y,kc,k) print(y,kc,type(kc)) print(x,y)import matplotlib.pyplot as pltplt.scatter(x,x,c=y,s=50,cmap="rainbow");plt.show()
用sklearn.cluster.KMeans,鸢尾花花瓣长度数据做聚类并用散点图显示.
import matplotlib.pyplot as pltimport numpy as npfrom sklearn.datasets import load_irisiris = load_iris()X = iris.dataXfrom sklearn.cluster import KMeansest = KMeans(n_clusters = 3)est.fit(X)kc = est.cluster_centers_y_kmeans = est.predict(X) print(y_kmeans,kc)print(kc.shape,y_kmeans.shape,np.shape)plt.scatter(X[:,0],X[:,1],c=y_kmeans,s=50,cmap='rainbow');plt.show()