美文网首页
Clustering

Clustering

作者: Bounty_Hunter | 来源:发表于2019-07-26 15:36 被阅读0次

    Clustering

    算法概念

    算法类型

    K-means算法是非监督学习聚类(clustering)中的经典算法,数据挖掘的十大经典算法之一。

    算法目标

    接收参数K,然后将事先输入的n个数据划分为K个聚类以便使得所获得的聚类满足:

    同一聚类中的对象相似度较高,而不同聚类中的对象相似度较低。

    算法思想

    以空间中K个点作为中心进行聚类,对最靠近它们的对象进行归类;通过迭代的方法,逐渐更新各聚类中心的值,直至得到最好的聚类结果。

    算法描述:

    1. 适当选择c个类的初始中心
    2. 在第K次迭代中,对任意一个样本,求其到c各中心的距离,将该样本归类到距离最短的中心所在的类。
    3. 利用均值等方法更新该类的中心值
    4. 对所有的c个聚类中心,如果利用b、c的迭代更新后,值保持不变,则迭代结束;否则继续迭代。

    计算相似程度

    每个数据点都是向量xi,数据的每个特征值作为向量的一个元素,使用到其他数据点xj的向量距离来计算相似性
    d(x_{i},x_{j} = || x_{i}-x_{j} ||_{2}

    用 sk-learn 库实现

    生成聚类数据

    sklearn.datasets.make_blobs(n_samples=100, n_features=2, centers=None, cluster_std=1.0, center_box=(-10.0, 10.0), shuffle=True, random_state=None

    生成符合高斯分布的聚类数据。

    • n_samples 待生成的样本的总数。
    • n_features是每个样本的特征数。
    • centers 表示聚类类别数。
    • cluster_std 表示每个类别的方差,例如我们希望生成2类数据,其中一类比另一类具有更大的方差,可以将cluster_std设置为[1.0,3.0]
    • center_box 每个聚类中心的边界框。
    from sklearn.datasets import make_blobs
    
    X,y=make_blobs(n_samples=100,n_features=2,centers=3)
    

    使用 K-MEANS 归类

    参数(parameters)

    • n_clusters

      k值

    属性(attributes)

    • cluster_centers_

      集群中心的坐标

    • labels_

      每个数据的分类标签

    • inertia_

      样本到其最近聚类中心的平方距离之和。

    函数(functions)

    • score(X)

      计算群集质量

    from sklearn.cluster import KMeans
    
    # Create the kmeans object
    kmeans = KMeans(n_clusters = 3)
    
    # Calculate the cluster assignment
    kmeans.fit(X)
    
    # Get the cluster labels
    clusters = kmeans.labels_
    

    画聚类结果的散点图

    plt.scatter()

    import matplotlib.cm as cm
    import matplotlib.pyplot as plt
    plt.figure(figsize=(6, 6))
    
    # Show the points again but make them transperant
    plt.scatter(X[:, 0], X[:, 1], c=[cm.tab10(float(i) /10) for i in clusters], alpha = 0.4)
    
    plt.title("K-means Clustered data")
    
    plt.show()
    

    选择 K 值

    hype parameter K值 需要在使用 Kmeans之前决定,最简单的做法是用 elbow method

    1. 设置k值范围
    2. 对k的每个值执行k-means
    3. 计算群集质量
    4. 找出群集质量没有显着提高的点
    # 这里K 值在1 到10 中选
    k_range = np.arange(1,11)
    # 存每个 K 值对应的聚类结果分数
    k_scores = []
    
    for k in k_range:
        kmeans = KMeans(n_clusters = k)
        
        kmeans.fit(X)
        
        k_scores.append(kmeans.score(X))
      
    # 画 k-score 图
    plt.figure()
    plt.plot(k_scores)
    plt.xticks(np.arange(0, 10), k_range)
    plt.title("Cluster Quality vs Number of Clusters")
    plt.xlabel("Number of Clusters")
    plt.ylabel("Quality")
    plt.show()
    

    相关文章

      网友评论

          本文标题:Clustering

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