聚类--K均值算法:自主实现与sklearn.cluster.KMeans调用
Posted 844115-l
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了聚类--K均值算法:自主实现与sklearn.cluster.KMeans调用相关的知识,希望对你有一定的参考价值。
1.用python实现K均值算法
import numpy as np x = np.random.randint(1,100,[20,1]) y = np.zeros(20) k = 3 x y
1(1) 选取数据空间中的K个对象作为初始中心,每个对象代表一个聚类中心;
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] kc = initcenter(x,k) nearest(kc,14)
1.(2) 对于样本中的数据对象,根据它们与这些聚类中心的欧氏距离,按距离最近的准则将它们分到距离它们最近的聚类中心(最相似)所对应的类;
for i in range(x.shape[0]): y[i] = nearest(kc,x[i]) print(y)
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 y kc = initcenter(x,k) y = xclassify(x,y,kc) print(kc,y)
m = np.where(y == 0) m
np.mean(x[m])
kc[0]=24 kc
2. 鸢尾花花瓣长度数据做聚类并用散点图显示
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 kcmean(x, y, kc, k): #计算各聚类新均值 l = list(kc) flag = False for c in range(k): print(c) m = np.where(y ==c)
if m[0].shape != (0,): n = np.mean(x[m]) if l[c] != n: l[c] = n flag = True #聚类中心发生改变 return (np.array(1),flag)
def xclassify(x,y,kc): for i in range(x.shape[0]): #对数组的每个值分类 y[i] = nearest(kc,x[i]) return y k = 3 kc = initcenter(x,k) falg = True print(x, y, kc, flag) while flag: y = xclassify(x, y, kc) xc, flag = kcmean(x, y, kc, k) print(y,kc)
运行结果:
import matplotlib.pyplot as plt plt.scatter(x, x, c=y, s=50, cmap=‘rainbow‘,marker=‘p‘,alpha=0.5); plt.show()
3.用sklearn.cluster.KMeans,鸢尾花花瓣长度数据做聚类并用散点图显示
import numpy as np from sklearn.cluster import KMeans from sklearn.datasets import load_iris import matplotlib.pyplot as plt iris_data = load_iris() X=iris_data.data # 花瓣长度 petal_length = X[:, 2:3] x= petal_length print(x) k_means = KMeans(n_clusters=3) est = k_means.fit(x) kc = est.cluster_centers_ y_kmeans = k_means.predict(x) plt.scatter(x,np.linspace(1,150,150),c=y_kmeans,marker=‘o‘,cmap=‘rainbow‘,linewidths=4) plt.show()
运行结果:
4.鸢尾花完整数据做聚类并用散点图显示
from sklearn.cluster import KMeans import numpy as np from sklearn.datasets import load_iris import matplotlib.pyplot as plt data = load_iris() iris = data.data petal_len = iris print(petal_len) k_means = KMeans(n_clusters=3) #三个聚类中心 result = k_means.fit(petal_len) #Kmeans自动分类 kc = result.cluster_centers_ #自动分类后的聚类中心 y_means = k_means.predict(petal_len) #预测Y值 plt.scatter(petal_len[:,0],petal_len[:,2],c=y_means, marker=‘p‘,cmap=‘rainbow‘) plt.show()
运行结果:
以上是关于聚类--K均值算法:自主实现与sklearn.cluster.KMeans调用的主要内容,如果未能解决你的问题,请参考以下文章
聚类--K均值算法:自主实现与sklearn.cluster.KMeans调用
聚类--K均值算法:自主实现与sklearn.cluster.KMeans调用
聚类--K均值算法:自主实现与sklearn.cluster.KMeans调用
聚类--K均值算法:自主实现与sklearn.cluster.KMeans调用