sklearn机器学习之Kmeans根据轮廓系数选择参数n

阅读: 评论:0

sklearn机器学习之Kmeans根据轮廓系数选择参数n

sklearn机器学习之Kmeans根据轮廓系数选择参数n

1.导入相应包

from sklearn.cluster import KMeans
ics import silhouette_samples, silhouette_score
from matplotlib import pyplot as plt
from matplotlib import cm
import numpy as np
from sklearn.datasets import make_blobs

2.生成数据集

X, y = make_blobs(n_features=2, centers=4, n_samples=500, random_state=1)

3.绘图(比较复杂,看注释)

#绘制在n_clusters不同情况下的轮廓图与效果图
for n_clusters in [2, 3, 4, 5, 6, 7]:n_clusters = n_clusters#创建画布fig, (ax1, ax2) = plt.subplots(1, 2)#设置画布大小fig.set_size_inches(18, 7)#设置横轴和纵轴作图范围,注意和xticks区别ax1.set_xlim([-0.1, 1])#这里是样本数加间隔数(这里设置为10)ax1.set_ylim([0, X.shape[0] + (n_clusters + 1) * 10])#建立模型并训练clusterer = KMeans(n_clusters=n_clusters, random_state=10).fit(X)#得到标签cluster_labels = clusterer.labels_#获得平均轮廓系数silhouette_avg = silhouette_score(X, cluster_labels)#输出print("For n_clusters =", n_clusters,"The average silhouette_score is", silhouette_avg)#获得每个样本的轮廓系数sample_silhouette_values = silhouette_samples(X, cluster_labels)#为了不贴着x轴画图,设置距离10cmy_lower = 10#画出每个簇的轮廓图for i in range(n_clusters):#第i个簇的值ith_cluster_silhouette_values = sample_silhouette_values[cluster_labels == i]#排序ith_cluster_silhouette_values.sort()#设置y曲线长度size_cluster_i = ith_cluster_silhouette_values.shape[0]y_upper = y_lower + size_cluster_i#设置colormapcolor = cm.nipy_spectral(float(i) / n_clusters)#绘制轮廓这里fill_betweenx是通过x坐标长度绘制,fill_betweeny则是按y坐标来绘制ax1.fill_betweenx(np.arange(y_lower, y_upper), ith_cluster_silhouette_values, facecolor=color, alpha=0.7)#写上文字前两参数时坐标,后面是文字(-0.05, y_lower + 0.5 * size_cluster_i, str(i))#设置下一个的y_lowery_lower = y_upper + 10ax1.set_title("The silhouette plot for the various clusters.")ax1.set_xlabel("The silhouette coefficient values")ax1.set_ylabel('Cluster label')#绘制虚直线ax1.axvline(x=silhouette_avg, color='red', linestyle="--")ax1.set_yticks([])ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)ax2.scatter(X[:, 0], X[:, 1], marker='o', s=8, c=colors)centers = clusterer.cluster_centers_ax2.scatter(centers[:, 0], centers[:, 1], marker='x', c='red', alpha=1, s=200)ax2.set_title("The visualization of the clustered data.")ax2.set_xlabel("Feature space for the 1st feature")ax2.set_ylabel("Feature space for the 2nd feature")#设置大标题plt.suptitle(("Silhouette analysis for KMeans clustering on sample data with n_clusters = %d" % n_clusters),fontsize=14, fontweight='bold')plt.show()

绘制图像如下:





本文发布于:2024-02-01 11:13:40,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170675722236208.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:系数   轮廓   机器   参数   sklearn
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23