聚类--K均值算法:自主实现与sklearn.cluster.KMeans调用


import
numpy as np x=np.random.randint(1,100,[20,1]) y=np.zeros(20) k=3 def initcenter(x,k): return x[:k] kc=initcenter(x,k) kc 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 y def kcmean(x,y,kc,k): l=list(kc) flag=False for c in range(k): print(c) m=np.where(y==c) print(m,x[m]) n=np.mean(x[m]) print(kc[c],n) if l[c]!=n: kc[c]=n print(type(kc),kc[c]) l[c]=n flag=True print(l,flag) return(np.array(l),flag) flag=True print("x值为",x,"y值为",y,"kc值为",kc,"flag值为",flag) while 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 plt plt.scatter(x,x,c=x,s=50,cmap="rainbow"); plt.show() import numpy as np from 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 y def 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 = 3 kc = initcenter(x,k) 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)) print(x,y) import matplotlib.pyplot as plt plt.scatter(x,x,c=y,s=50,cmap="Paired"); plt.show() #用sklearn.cluster.KMeans,鸢尾花花瓣长度数据做聚类并用散点图显示 import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import load_iris iris = load_iris() X = iris.data X from sklearn.cluster import KMeans est = 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()

截图

posted on 2018-10-31 21:35  阿占  阅读(170)  评论(0编辑  收藏  举报

导航