Skip to content

    K-Means Clustering

    Machine Learning · Intermediate

    Definition

    K-Means groups unlabeled data into K clusters by assigning points to the nearest centroid.

    Used for customer segmentation, image compression and anomaly detection.

    Diagram

    ● cluster 1▲ cluster 2■ cluster 3✕ centroids

    Flowchart

    Choose KPlace K centroidsAssign points to nearestMove centroids to meanRepeat until stable

    Example: Cluster points

    from sklearn.cluster import KMeans
    X=[[1,1],[1,2],[8,8],[9,8]]
    print(KMeans(2, n_init=10, random_state=0).fit(X).labels_)

    Key points

    • Unsupervised
    • Elbow method chooses K
    • Sensitive to scaling and start points

    Interview questions

    How to choose K?

    Elbow method or silhouette score.

    More Machine Learning topics