2021-08-04

该博客介绍了如何使用K-means算法进行数据聚类,并通过肘部法则选择最佳聚类数。作者展示了从生成样本数据到评估模型效果的全过程,包括计算平均畸变、调整后的兰德指数、同质化得分和轮廓系数等指标。最后,通过可视化展示了聚类结果。
摘要由CSDN通过智能技术生成

K-means

import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from scipy.spatial.distance import cdist
from sklearn import metrics  # 导入sklearn效果评估模块

# 导入相关数据           C:\Users\m50018197\Desktop\est.txt
# Generate sample data
from sklearn.datasets import make_blobs

np.random.seed(0)

centers = [[1, 1], [-1, -1], [1, -1]]  # 初始化三个中心
n_clusters = len(centers)  # 聚类的数目为3
# 产生3000组两维的数据,以上边三个点为中心,以(-10,10)为边界,数据集的标准差是0.7
X, y_true = make_blobs(n_samples=30, centers=3, cluster_std=0.7)

print(y_true)
# # 确定要聚类的数目:肘部法则
plt.figure()
plt.axis([0, 10, 0, 2.5])
plt.grid(True)

K = range(1, 10)
meandistortions = []
for k in K:
    kmeans = KMeans(n_clusters=k)
    kmeans.fit(X)
    meandistortions.append(sum(np.min(cdist(X, kmeans.cluster_centers_, 'euclidean'), axis=1)) / X.shape[0])
plt.plot(K, meandistortions, 'bx-')
plt.xlabel('k')
plt.ylabel('meandistortions')
plt.title('best K of the model');

# 训练聚类模型
n_clusters = 3  # 设置聚类数量
model_kmeans = KMeans(n_clusters=n_clusters, random_state=0)  # 建立聚类模型对象
model_kmeans.fit(X)  # 训练聚类模型
y_pre = model_kmeans.predict(X)  # 预测聚类模型

# 模型效果评估
n_samples, n_features = X.shape  # 总样本量,总特征数
inertias = model_kmeans.inertia_  # 样本距离最近的聚类中心的总和
adjusted_rand_s = metrics.adjusted_rand_score(y_true, y_pre)  # 调整后的兰德指数
homogeneity_s = metrics.homogeneity_score(y_true, y_pre)  # 同质化得分
silhouette_s = metrics.silhouette_score(X, y_pre, metric='euclidean')  # 平均轮廓系数

# 模型效果可视化
centers = model_kmeans.cluster_centers_  # 各类别中心
colors = ['#4EACC5', '#FF9C34', '#4E9A06']  # 设置不同类别的颜色
plt.figure()  # 建立画布
for i in range(n_clusters):  # 循环读取类别
    index_sets = np.where(y_pre == i)  # 找到相同类的索引集合、
    cluster = X[index_sets]  # 将相同类的数据划分为一个聚类子集
    plt.scatter(cluster[:, 0], cluster[:, 1], c=colors[i], marker='.')  # 展示聚类子集内的样本点
    plt.plot(centers[i][0], centers[i][1], 'o', markerfacecolor=colors[i]
             , markeredgecolor='k', markersize=6)  # 展示各聚类子集的中心

plt.show()  # 展示图像
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值