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() # 展示图像