美文网首页机器学习
K平均聚类算法-Python

K平均聚类算法-Python

作者: 灵妍 | 来源:发表于2018-03-29 14:56 被阅读13次
    1、数据预处理
    # Importing the libraries
    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    # Importing the dataset
    dataset = pd.read_csv('Mall_Customers.csv')
    X = dataset.iloc[:, 3:5].values
    

    聚类问题的数据预处理非常简单,只要导入标准库和数据集就可以了。
    这里的商业案例是通过顾客的年度收入和消费指数将此商场的顾客划分为不同的类别。

    2、选择合适的群个数
    # Using the elbow method to find the optimal number of clusters
    from sklearn.cluster import KMeans
    wcss = []
    for i in range(1,11):
        kmeans = KMeans(n_clusters = i, max_iter = 300, n_init = 10, init = 'k-means++', random_state = 0)
        kmeans.fit(X)
        wcss.append(kmeans.inertia_)
    plt.plot(range(1,11), wcss)
    plt.title('The Elbow Method')
    plt.xlabel('Number of Clusters')
    plt.ylabel('WCSS')
    plt.show()
    
    elbow法则.PNG

    这里通过循环语句构建不同的K-Means模型,然后算出不同模型的组间距,利用plt包画出来。
    根据手肘法则得到K=5是最合适的,此时的组间距变化最大。

    3、构造K-Means模型
    kmeans = KMeans(n_clusters = 5, max_iter = 300, n_init = 10, init = 'k-means++', random_state = 0)
    y_kmeans = kmeans.fit_predict(X)
    
    ![结果.PNG](https://img.haomeiwen.com/i1512748/7b16ff2eed847268.PNG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

    这里KMeans的第一个参数是确定组数,第二个参数确定最大迭代次数,第三个参数未知,第四个参数确定初始化方法,避免随机陷阱,这里不用随机方法,第五个确定随机数的生成方式。
    对于聚类算法拟合和预测是一起的。

    4、可视化
    # Visualizing the clusters
    plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 100, c = 'red', label = 'Careful')
    plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 100, c = 'blue', label = 'Standard')
    plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 100, c = 'green', label = 'Target')
    plt.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], s = 100, c = 'cyan', label = 'Careless')
    plt.scatter(X[y_kmeans == 4, 0], X[y_kmeans == 4, 1], s = 100, c = 'magenta', label = 'Sensible')
    plt.scatter(kmeans.cluster_centers_[:, 0],  kmeans.cluster_centers_[:, 1], s = 300, c = 'yellow', label = 'Centroids')
    plt.title('Clusters of clients')
    plt.xlabel('Annual Income (k$)')
    plt.ylabel('Spending Score (1-100)')
    plt.legend()
    plt.show()
    
    结果.PNG

    这里利用X,也就是数据对应的y_kmeans筛选出行数,确定点的X轴和Y轴坐标,label属性对应legend的标记。我们最终把用户分为小心,标准,核心,明智,大意五类。
    这里的kmeans_cluster_centers_代表kmeans这个聚类器的中心点。

    相关文章

      网友评论

        本文标题:K平均聚类算法-Python

        本文链接:https://www.haomeiwen.com/subject/mmmmcftx.html