K-Means聚类 案例:鸢尾花分类

实例代码

import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.datasets import load_iris
from sklearn.metrics import silhouette_score, silhouette_samples, calinski_harabasz_score, adjusted_rand_score

iris = load_iris()
data = iris.data
print(f"iris.feature_names: {iris.feature_names}")
print(f"data features: \n{data[0:3]}")
print(f"data.shape: {data.shape}")
print(f"iris.target: {iris.target}")

x = data

# 实例化Kmeans 算法模型,使用三个簇尝试聚类
cluster = KMeans(n_clusters=3, random_state=0)

# 使用数据集x进行训练
cluster = cluster.fit(x)

# 调用属性lables_,查看聚类结果
print(f"kmeans聚类结果: \n{cluster.labels_}")
# 查看预测结果的数据结构
print(f"预测结果的数据结构: {cluster.labels_.shape}")

# 查看数组中存在的类别(对一维数组去重)
print(f"预测结果中存在的类别: {np.unique(cluster.labels_)}")
# 查看每一分类结果的数量
print(f"聚类结果分布: \n{pd.value_counts(cluster.labels_)}")
# 聚类结果分布以百分比形式显示
print(f"聚类结果分布(百分比): \n{pd.value_counts(cluster.labels_, normalize=True)}")

# 查看质心
print(f"查看聚类质心: \n{cluster.cluster_centers_}")

# 评估指标
# 兰德系数
print(f"兰德系数: {adjusted_rand_score(iris.target, cluster.labels_)}")

# 轮廓系数
print(f"轮廓系数: {silhouette_score(x, cluster.labels_)}")

# 卡林斯基-哈拉巴斯指数
print(f"卡林斯基-哈拉巴斯指数: {calinski_harabasz_score(x, cluster.labels_)}")

# 基于轮廓系数来选择最佳的n_clusters
print("基于轮廓系数来选择最佳的n_clusters:")
for n_clusters in [2, 3, 4, 5, 6, 7, 8]:
    n_clusters = n_clusters
    # 设置画布
    fig, ax1 = plt.subplots(1)
    # 设置画布尺寸
    fig.set_size_inches(18, 7)
    # 设置画布X轴
    ax1.set_xlim([-0.1, 1])
    # 设置画布Y轴:X.shape[0]代表着柱状的宽度,(n_clusters + 1) * 10代表着柱与柱之间的间隔
    ax1.set_ylim([0, x.shape[0] + (n_clusters + 1) * 10])
    # 模型实例化
    clusterer = KMeans(n_clusters=n_clusters, random_state=100)
    # 开始训练模型
    clusterer = clusterer.fit(x)
    # 提取训练结果中的预测标签
    cluster_labels = clusterer.labels_
    # 提取训练结果中的轮廓系数均值
    silhouette_avg = silhouette_score(x, cluster_labels)
    # 打印出当前的簇数与轮廓系数均值
    print("\t簇数为", n_clusters,
          ",轮廓系数均值为", silhouette_avg)
    # 提取每一个样本的轮廓系数
    sample_silhouette_values = silhouette_samples(x, cluster_labels)
    # 设置Y轴的起始坐标
    y_lower = 10
    # 添加一个循环,把每一个样本的轮廓系数画在图中
    for i in range(n_clusters):
        # 提取第i个簇下的所有样本轮廓系数
        ith_cluster_silhouette_values = sample_silhouette_values[cluster_labels == i]
        # 对样本的轮廓系数进行排序(降序)
        ith_cluster_silhouette_values.sort()
        # 设置当前簇的柱状宽度(使用样本数量)以便于设置下一个簇的起始坐标
        size_cluster_i = ith_cluster_silhouette_values.shape[0]
        # 设置Y轴第i个簇的起始坐标
        y_upper = y_lower + size_cluster_i
        # 设置颜色
        color = cm.nipy_spectral(float(i) / n_clusters)
        # 画图
        ax1.fill_betweenx(np.arange(y_lower, y_upper)
                          , ith_cluster_silhouette_values
                          , facecolor=color
                          , alpha=0.7
                          )
        ax1.text(-0.05
                 , y_lower + 0.5 * size_cluster_i
                 , str(i))
        y_lower = y_upper + 10
    # 设置图的标题
    ax1.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])
    plt.show()

原文链接

K-Means聚类 案例
最通俗的话解释KNN,KMeans算法

posted @ 2023-07-05 15:56  柳叶昶  阅读(86)  评论(0编辑  收藏  举报