K-means聚类:最常用的机器学习聚类算法,且为典型的基于距离的聚类算法。
-
K均值:基于原型的、划分的距离技术,它试图发现用户指定个数(K)的簇以欧式距离作为相似度测度
Kmeans聚类
案例分析:make_blobs聚类数据生成器
# 导入模块from sklearn.cluster import KMeansfrom sklearn.datasets import make_blobs
# 创建数据x,y_true = make_blobs(n_samples = 300, # 生成300条数据 centers = 4, # 四类数据 cluster_std = 0.5, # 方差一致 random_state = 0)print(x[:5])print(y_true[:5])# n_samples → 待生成的样本的总数。# n_features → 每个样本的特征数。# centers → 类别数# cluster_std → 每个类别的方差,如多类数据不同方差,可设置为[1.0,3.0](这里针对2类数据)# random_state → 随机数种子# x → 生成数据值, y → 生成数据对应的类别标签plt.figure(figsize =(10,6))plt.scatter(x[:,0],x[:,1],s = 10,alpha = 0.8)plt.grid()
[[ 1.03992529 1.92991009] [-1.38609104 7.48059603] [ 1.12538917 4.96698028] [-1.05688956 7.81833888] [ 1.4020041 1.726729 ]] [1 3 0 3 1]
# 构建K均值模型
# 构建模型,并预测出样本的类别y_kmeans# kmeans.cluster_centers_:得到不同簇的中心点kmeans = KMeans(n_clusters = 4) # 这里为4簇kmeans.fit(x)y_kmeans = kmeans.predict(x)centroids = kmeans.cluster_centers_
# 绘制图表plt.figure(figsize =(10,6))plt.scatter(x[:,0],x[:,1],c = y_kmeans, cmap = 'Dark2', s= 50,alpha = 0.5,marker='x')plt.scatter(centroids[:,0],centroids[:,1],c = [0,1,2,3], cmap = 'Dark2',s= 70,marker='o')plt.title('K-means 300 pointsn')plt.xlabel('Value1')plt.ylabel('Value2')plt.grid()



