import numpy as np
import numpy as pd
import matplotlib
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score,silhouette_samples
from sklearn.datasets import make_blobs
matplotlib.use("TkAgg")
X,y = make_blobs(n_samples=150,n_features=2,centers=3,random_state=150)
# plt.scatter(X[:,0],X[:,1],c=y)
# plt.show()
k_list = [2,3,4,5,6,7]
for k in k_list:
kmean = KMeans(n_clusters=k)
#训练与预测
y_ = kmean.fit_predict(X)
#计算轮廓系数 越接近1越准确
score = silhouette_score(X,y_)
# print(score)
plt.subplot(2,3,k_list.index(k)+1)
plt.scatter(X[:,0],X[:,1],c=y_)
plt.title(f"k:{k},score:{score}")
plt.show()
#k=3 每个点的轮廓系数
kmean=KMeans(n_clusters=3)
y_ = kmean.fit_predict(X)
score1 =silhouette_score(X,y_)
#每个点的轮廓系数
samples =silhouette_samples(X,y_)
# print(score1)
# print(samples.mean())
数据分析与挖掘-Kmeans算法-2.Kmeans轮廓系数
于 2024-06-29 22:27:31 首次发布