Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»AI & Machine Learning»K-Means Clustering in Machine Learning: An Interactive Guide (with Python)
    AI & Machine Learning

    K-Means Clustering in Machine Learning: An Interactive Guide (with Python)

    Anirudh KhuranaBy Anirudh Khurana20 November 2026No Comments31 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    K-means clustering illustration: three coloured clusters of points, each with its centroid marked by a cross
    Share
    Facebook Twitter LinkedIn Pinterest Email

    K-means clustering is an unsupervised machine learning algorithm that splits data into K groups, called clusters, so that points in the same cluster are close to each other. Each cluster has a centre point, the centroid, and every data point belongs to the cluster whose centroid is nearest. You choose K; the algorithm finds the groups.

    Shops use k-means clustering to group customers by how they spend, apps use it to group users by behaviour, and image editors use it to cut a photo down to a handful of colours. K-means clustering is the first clustering algorithm almost everyone learns, it is simple enough to work out by hand in an exam, and it shows up in data science interviews all the time.

    In this guide you will watch k-means work one step at a time in an interactive playground, see exactly when it fails, choose K with the elbow method and the silhouette score, solve a numerical example by hand, and write it in Python with scikit-learn and from scratch. If you have read our decision tree guide, note the big difference: there are no labels here at all.

    Free PDF
    K-means clustering notes with code and interview questions
    11 pages, ready to print or read offline. No sign-up needed.
    Download PDF

    What is k-means clustering?

    Imagine you run a mall and have data on 200 customers: their monthly income and a spending score from 1 to 100. Nobody has labelled these customers. You just want to know whether there are natural groups, such as high earners who spend a lot or low earners who spend carefully, so you can market to each group differently.

    That is a clustering problem, and it is unsupervised learning: unlike regression or classification, there is no correct answer to learn from. K-means finds the groups by itself. You tell it how many groups to look for (K = 5, say), and it places 5 centroids so that every customer is as close as possible to the centroid of their group.

    Key terms

    TermWhat it means
    ClusterA group of data points that are close to each other.
    KThe number of clusters you ask for. You choose it before running k-means.
    CentroidThe centre of a cluster: the mean (average) of all the points in it.
    AssignmentPutting each point in the cluster of its nearest centroid.
    Inertia (WCSS)Within-cluster sum of squares: the total squared distance from every point to its own centroid. Lower means tighter clusters.
    ConvergenceThe point where the clusters stop changing, so the algorithm stops.

    K-means playground: watch it work step by step

    Start with the lessons. Each one loads a dataset and settings and tells you what to look for. The big crosses are the centroids, the dotted lines show the path each centroid has travelled, and the coloured background shows which centroid is closest to each spot on the chart.

    Interactive

    K-means clustering playground

    Real k-means running in your browser. Every press of Next step does one assign or one move.

    Guided lessons

    Loading the chart…

    Starting centroids
    Dataset
    Click on the chart to

    One point per line as x, y, in any units. Up to 500 points. Both columns are rescaled to fit the chart, which also puts them on the same scale.

    A good exercise once you have done the lessons: pick Mall customers, set K to 5, choose Random points as the start, and press New start and then Run to the end several times. Only about half the runs find all five groups. In the others, two centroids get stuck sharing one group, two real groups get merged, and the WCSS jumps up. That is the reason scikit-learn runs k-means several times and keeps the best result.

    How the k-means clustering algorithm works

    K-means clustering repeats two simple steps until nothing changes. This loop is also called Lloyd’s algorithm.

    1. Choose K, the number of clusters.
    2. Initialise: pick K starting centroids. The simplest way is K random data points; the better way is k-means++, covered below.
    3. Assign: put every point in the cluster of its nearest centroid, using straight-line (Euclidean) distance.
    4. Update: move each centroid to the mean of the points now in its cluster.
    5. Repeat steps 3 and 4 until no point changes cluster (or the centroids stop moving, or a maximum number of iterations is reached).

    K-means clustering pseudocode

    choose K
    pick K starting centroids c1 ... cK
    repeat
        for each point x:
            assign x to the cluster j with the smallest distance(x, cj)
        for each cluster j:
            cj = mean of all points assigned to cluster j
    until no assignment changes
    return the centroids and the cluster of every point

    What k-means is minimising

    Both steps work towards one goal: making the clusters as tight as possible. The measure of tightness is the within-cluster sum of squares (WCSS), which scikit-learn calls inertia:

    WCSS = Σj=1..K Σx in cluster j ‖x − cj‖²

    The assign step can only lower WCSS, because each point moves to a closer centroid. The update step can only lower it too, because the mean is the point with the smallest total squared distance to a group of points. Since WCSS never goes up and there is a limited number of ways to split the points, k-means always converges, usually in a handful of rounds. What it does not promise is the best possible answer. It stops at a local minimum that depends on where the centroids started, which is what lesson 3 in the playground shows.

    K-means clustering numerical example (solved by hand)

    Exams often ask you to run k-means by hand on a few points. Here are seven points, with K = 2. The starting centroids are A and D.

    PointABCDEFG
    (x, y)(1, 1)(1.5, 2)(3, 4)(5, 7)(3.5, 5)(4.5, 5)(3.5, 4.5)

    Iteration 1, assign. The centroids are c1 = (1, 1) and c2 = (5, 7). Work out each point’s Euclidean distance to both. For B, the distance to c1 is √((1.5 − 1)² + (2 − 1)²) = √1.25 = 1.12, and to c2 it is √(3.5² + 5²) = 6.10, so B joins cluster 1. Point C is exactly 3.61 from both centroids. A tie like this is broken by a fixed rule; here, as in NumPy’s argmin, it goes to the first cluster. So cluster 1 = {A, B, C} and cluster 2 = {D, E, F, G}.

    Iteration 1, update. c1 = mean of A, B, C = ((1 + 1.5 + 3) / 3, (1 + 2 + 4) / 3) = (1.83, 2.33). c2 = mean of D, E, F, G = ((5 + 3.5 + 4.5 + 3.5) / 4, (7 + 5 + 5 + 4.5) / 4) = (4.12, 5.38).

    Iteration 2. With the new centroids, C is 2.03 from c1 but only 1.78 from c2, so C switches to cluster 2. Now cluster 1 = {A, B} and cluster 2 = {C, D, E, F, G}. The new centroids are c1 = (1.25, 1.5) and c2 = (3.9, 5.1).

    Iteration 3. Every point stays in the same cluster, so the centroids do not move. K-means has converged with clusters {A, B} and {C, D, E, F, G}. Here is the same calculation in Python, printing every distance:

    import numpy as np
    
    # 7 points, K = 2, starting centroids are A and D
    names = ["A", "B", "C", "D", "E", "F", "G"]
    X = np.array([[1, 1], [1.5, 2], [3, 4], [5, 7], [3.5, 5], [4.5, 5], [3.5, 4.5]])
    centroids = np.array([[1, 1], [5, 7]], dtype=float)
    
    for step in range(1, 10):
        dist = np.linalg.norm(X[:, None, :] - centroids[None, :, :], axis=2)   # distance to each centroid
        labels = dist.argmin(axis=1)
        print(f"Iteration {step}")
        for n, d, l in zip(names, dist.round(2), labels):
            print(f"  {n}: d1={d[0]:<5} d2={d[1]:<5} -> cluster {l + 1}")
        new = np.array([X[labels == k].mean(axis=0) for k in range(2)])
        print("  new centroids:", new.round(2).tolist())
        if np.allclose(new, centroids):
            print("Centroids did not move. Converged.")
            break
        centroids = new

    Output:

    Iteration 1
      A: d1=0.0   d2=7.21  -> cluster 1
      B: d1=1.12  d2=6.1   -> cluster 1
      C: d1=3.61  d2=3.61  -> cluster 1
      D: d1=7.21  d2=0.0   -> cluster 2
      E: d1=4.72  d2=2.5   -> cluster 2
      F: d1=5.32  d2=2.06  -> cluster 2
      G: d1=4.3   d2=2.92  -> cluster 2
      new centroids: [[1.83, 2.33], [4.12, 5.38]]
    Iteration 2
      A: d1=1.57  d2=5.38  -> cluster 1
      B: d1=0.47  d2=4.28  -> cluster 1
      C: d1=2.03  d2=1.78  -> cluster 2
      D: d1=5.64  d2=1.85  -> cluster 2
      E: d1=3.14  d2=0.73  -> cluster 2
      F: d1=3.77  d2=0.53  -> cluster 2
      G: d1=2.73  d2=1.08  -> cluster 2
      new centroids: [[1.25, 1.5], [3.9, 5.1]]
    Iteration 3
      A: d1=0.56  d2=5.02  -> cluster 1
      B: d1=0.56  d2=3.92  -> cluster 1
      C: d1=3.05  d2=1.42  -> cluster 2
      D: d1=6.66  d2=2.2   -> cluster 2
      E: d1=4.16  d2=0.41  -> cluster 2
      F: d1=4.78  d2=0.61  -> cluster 2
      G: d1=3.75  d2=0.72  -> cluster 2
      new centroids: [[1.25, 1.5], [3.9, 5.1]]
    Centroids did not move. Converged.

    K-means clustering in Python with scikit-learn

    Now the mall customers from the playground: 200 customers with a monthly income (in thousand rupees) and a spending score. We ask for 5 clusters, look at the centroids, and then put two new customers into clusters.

    import numpy as np
    from sklearn.cluster import KMeans
    
    # 200 mall customers: monthly income (thousand rupees) and spending score (1 to 100)
    rng = np.random.default_rng(42)
    groups = [(25, 20, 30), (25, 80, 40), (55, 50, 50), (85, 20, 40), (85, 80, 40)]  # income, score, count
    X = np.vstack([np.column_stack([rng.normal(inc, 7, n), rng.normal(score, 7, n)]) for inc, score, n in groups])
    
    kmeans = KMeans(n_clusters=5, n_init=10, random_state=42)
    labels = kmeans.fit_predict(X)
    
    print("Cluster sizes:", np.bincount(labels))
    print("Centroids (income, score):")
    print(kmeans.cluster_centers_.round(1))
    print("Inertia (WCSS):", round(kmeans.inertia_, 1))
    print("Iterations:", kmeans.n_iter_)
    
    new_customers = np.array([[90, 85], [30, 25]])
    print("New customers go to clusters:", kmeans.predict(new_customers))

    Output:

    Cluster sizes: [50 40 30 40 40]
    Centroids (income, score):
    [[54.7 49.4]
     [85.5 80.2]
     [25.1 20.8]
     [85.6 20.4]
     [23.4 80.1]]
    Inertia (WCSS): 17560.6
    Iterations: 4
    New customers go to clusters: [1 2]

    The five centroids read like a marketing plan. One group has an income around ₹55,000 and a middling score of 49. Two high earners’ groups sit near ₹85,000, one spending a lot (score 80) and one spending little (score 20). The two low-income groups near ₹24,000 split the same way. The first new customer (₹90,000, score 85) joins the high income, high spending group, cluster 1, and the second (₹30,000, score 25) joins the low income, low spending group, cluster 2.

    Two details often confuse people. The cluster numbers are arbitrary: run it with another random_state and “cluster 1” might be called “cluster 3”. And n_init=10 means scikit-learn ran k-means 10 times from different starts and kept the run with the lowest inertia.

    KMeans parameters you should know

    ParameterWhat it doesDefault
    n_clustersK, the number of clusters8
    initHow starting centroids are chosen"k-means++"
    n_initHow many times to run from different starts; the best run is kept"auto" (1 with k-means++, 10 with random)
    max_iterMaximum rounds of assign and update per run300
    tolHow small the centroid movement must be to count as converged1e-4
    random_stateFixes the randomness so results can be repeatedNone

    Useful attributes after fitting: cluster_centers_ (the centroids), labels_ (the cluster of each training point), inertia_ (WCSS) and n_iter_ (rounds taken). predict() assigns new points to the nearest centroid. The full list is in the official scikit-learn KMeans documentation.

    How to choose K: the elbow method and silhouette score

    K-means will give you exactly as many clusters as you ask for, so choosing K is the most important decision you make. Two common tools help.

    The elbow method. Run k-means for K = 1, 2, 3 and so on, and plot WCSS against K. WCSS always falls as K grows, and it reaches 0 when every point is its own cluster, so you cannot just pick the lowest value. Instead, look for the “elbow”: the K after which adding clusters only lowers WCSS a little.

    The silhouette score. For each point, compare a, its average distance to the other points in its own cluster, with b, its average distance to the points in the nearest other cluster. Its silhouette is (b − a) / max(a, b), which runs from −1 to 1. Average this over all points: close to 1 means compact, well-separated clusters, around 0 means overlapping clusters, and negative means many points are in the wrong cluster. Pick the K with the highest average. scikit-learn calculates it with silhouette_score.

    Interactive

    Choose K: elbow and silhouette side by side

    K-means runs for K = 1 to 10 on the chosen dataset. Move the slider to see the clusters for each K.

    Loading the chart…

    On the mall data, both methods agree: the elbow is clearly at K = 5 and the silhouette peaks there too. On Three groups both point to 3. Now try Uneven sizes and Moons. On Uneven sizes there is no sharp elbow, and the silhouette prefers K = 2, which lumps the two small groups together. On Moons, no value of K separates the two moons. These tools assume k-means is the right model for the data; they cannot tell you that it is not.

    Here is the same check in Python on the mall data:

    import numpy as np
    from sklearn.cluster import KMeans
    from sklearn.metrics import silhouette_score
    
    rng = np.random.default_rng(42)
    groups = [(25, 20, 30), (25, 80, 40), (55, 50, 50), (85, 20, 40), (85, 80, 40)]
    X = np.vstack([np.column_stack([rng.normal(inc, 7, n), rng.normal(score, 7, n)]) for inc, score, n in groups])
    
    print(" K |   WCSS   | silhouette")
    for k in range(1, 10):
        km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X)
        sil = silhouette_score(X, km.labels_) if k > 1 else float("nan")
        print(f"{k:2d} | {km.inertia_:8.0f} | {sil:.3f}")

    Output:

     K |   WCSS   | silhouette
     1 |   291347 | nan
     2 |   172512 | 0.391
     3 |   104377 | 0.502
     4 |    48400 | 0.622
     5 |    17561 | 0.706
     6 |    16047 | 0.597
     7 |    14511 | 0.549
     8 |    12864 | 0.475
     9 |    11521 | 0.400

    WCSS drops from 48,400 at K = 4 to 17,561 at K = 5, then only to 16,047 at K = 6: that is the elbow. The silhouette score is highest at K = 5 (0.706). In real projects, also ask whether the clusters make sense for the business. Five customer groups that a marketing team can actually act on beat seven groups with a slightly better score.

    Random initialisation vs k-means++

    Because k-means only finds a local minimum, the starting centroids matter. With plain random starts, two centroids often land in the same natural group, as in lesson 3, and k-means cannot recover. K-means++ fixes most of this with a smarter start:

    1. Pick the first centroid at random from the data points.
    2. For every point, find its distance D to the nearest centroid chosen so far.
    3. Pick the next centroid at random, with each point’s chance proportional to D². Points far from all current centroids are much more likely to be picked.
    4. Repeat until there are K centroids, then run normal k-means.

    Let us measure the difference. The code runs k-means once (n_init=1) from 50 different seeds with each method, on data with 8 groups:

    import numpy as np
    from sklearn.cluster import KMeans
    from sklearn.datasets import make_blobs
    
    X, _ = make_blobs(n_samples=600, centers=8, cluster_std=0.6, random_state=11)
    
    for init in ["random", "k-means++"]:
        inertias = [KMeans(n_clusters=8, init=init, n_init=1, random_state=s).fit(X).inertia_ for s in range(50)]
        inertias = np.array(inertias)
        best = inertias.min()
        print(f"{init:10s} best={best:7.1f}  worst={inertias.max():7.1f}  "
              f"runs within 1% of best: {np.mean(inertias < best * 1.01):.0%}")
    
    km = KMeans(n_clusters=8, init="k-means++", n_init=10, random_state=0).fit(X)
    print("k-means++ with n_init=10:", round(km.inertia_, 1))

    Output:

    random     best=  395.0  worst= 5854.3  runs within 1% of best: 6%
    k-means++  best=  394.7  worst=  443.4  runs within 1% of best: 58%
    k-means++ with n_init=10: 394.7

    Random starts found a good answer only 6% of the time, and the worst run had an inertia of 5,854, about 15 times the best. K-means++ landed within 1% of the best in 58% of runs, and its worst run was only 12% worse. Combine k-means++ with several restarts (n_init=10) and you get the best answer reliably. That is why k-means++ is the default in scikit-learn. The k-means++ article on Wikipedia explains why it is guaranteed to be close to the best answer on average.

    Always scale your features before k-means

    K-means works on distances, so a feature with big numbers drowns out a feature with small numbers. Age runs from about 20 to 60, but annual income in rupees runs into lakhs. Without scaling, a 10-year age difference counts for almost nothing next to a ₹10,000 income difference. In this example the real groups differ only by age:

    import numpy as np
    from sklearn.cluster import KMeans
    from sklearn.preprocessing import StandardScaler
    from sklearn.metrics import adjusted_rand_score
    
    # Two real groups of customers that differ by AGE; income is just noise
    rng = np.random.default_rng(0)
    age = np.concatenate([rng.normal(25, 3, 150), rng.normal(50, 3, 150)])
    income = rng.normal(800000, 250000, 300)          # rupees per year
    X = np.column_stack([age, income])
    true_groups = np.repeat([0, 1], 150)
    
    raw = KMeans(n_clusters=2, n_init=10, random_state=0).fit_predict(X)
    scaled = KMeans(n_clusters=2, n_init=10, random_state=0).fit_predict(StandardScaler().fit_transform(X))
    
    print("Agreement with the real groups (1.0 = perfect, 0 = random):")
    print("  without scaling:", round(adjusted_rand_score(true_groups, raw), 3))
    print("  with scaling:   ", round(adjusted_rand_score(true_groups, scaled), 3))

    Output:

    Agreement with the real groups (1.0 = perfect, 0 = random):
      without scaling: -0.002
      with scaling:    1.0

    Without scaling, k-means splits the customers by income, which is just noise here, and the adjusted Rand score of −0.002 means the result is no better than random. After StandardScaler puts both features on the same scale, it finds the two age groups perfectly (1.0). Make scaling a habit: put StandardScaler and KMeans in a Pipeline. The same rule applies to other distance-based models, like the support vector machine.

    K-means clustering from scratch with NumPy

    The whole algorithm fits in about 15 lines. The assignment step is one argmin over a distance matrix, and the update step is a mean per cluster. If a cluster ends up empty, we keep its old centroid. We run it from 10 random starts and keep the best, just like n_init=10.

    import numpy as np
    from sklearn.cluster import KMeans
    from sklearn.datasets import make_blobs
    
    def kmeans(X, k, iters=100, seed=0):
        rng = np.random.default_rng(seed)
        centroids = X[rng.choice(len(X), k, replace=False)]           # k random points as start
        for i in range(iters):
            dist = ((X[:, None, :] - centroids[None, :, :]) ** 2).sum(axis=2)
            labels = dist.argmin(axis=1)                              # assignment step
            new = np.array([X[labels == j].mean(axis=0) if np.any(labels == j) else centroids[j]
                            for j in range(k)])                       # update step
            if np.allclose(new, centroids):
                break
            centroids = new
        inertia = ((X - centroids[labels]) ** 2).sum()
        return centroids, labels, inertia, i + 1
    
    X, _ = make_blobs(n_samples=500, centers=4, cluster_std=0.8, random_state=3)
    
    best = min((kmeans(X, 4, seed=s) for s in range(10)), key=lambda r: r[2])   # 10 restarts
    c, labels, inertia, n_iter = best
    sk = KMeans(n_clusters=4, n_init=10, random_state=0).fit(X)
    
    print("Our inertia:         ", round(inertia, 2), "after", n_iter, "iterations")
    print("scikit-learn inertia:", round(sk.inertia_, 2))
    print("Our centroids:\n", c[np.lexsort(c.T)].round(2))
    print("sklearn centroids:\n", sk.cluster_centers_[np.lexsort(sk.cluster_centers_.T)].round(2))

    Output:

    Our inertia:          645.42 after 3 iterations
    scikit-learn inertia: 645.42
    Our centroids:
     [[-7.63 -5.71]
     [-4.12  0.15]
     [ 0.96  4.25]
     [ 7.77  8.05]]
    sklearn centroids:
     [[-7.63 -5.71]
     [-4.12  0.15]
     [ 0.96  4.25]
     [ 7.77  8.05]]

    Our version reaches the same inertia (645.42) and exactly the same centroids as scikit-learn. scikit-learn is faster on big data because it uses optimised C code and, for dense data, Elkan’s algorithm or a tuned Lloyd loop. Writing k-means clustering from memory is a common interview test, so it is worth practising.

    Real example: image compression with k-means clustering

    Here is k-means clustering on real data. Every pixel in a colour photo is a point in 3D space: its red, green and blue values. Run k-means on the pixels and each centroid becomes one colour. Replace every pixel with its centroid and you have the same photo drawn with only K colours. This is called colour quantisation, and it is an easy way to see clustering at work.

    import numpy as np
    from sklearn.cluster import KMeans
    from sklearn.datasets import load_sample_image
    
    image = load_sample_image("china.jpg")              # 427 x 640 photo that ships with scikit-learn
    pixels = image.reshape(-1, 3) / 255.0               # every pixel is a point in RGB space
    print("Pixels:", len(pixels), "| unique colours:", len(np.unique(image.reshape(-1, 3), axis=0)))
    
    sample = pixels[np.random.default_rng(0).choice(len(pixels), 5000, replace=False)]
    for k in [4, 8, 16]:
        km = KMeans(n_clusters=k, n_init=4, random_state=0).fit(sample)
        labels = km.predict(pixels)
        compressed = km.cluster_centers_[labels].reshape(image.shape)   # repaint each pixel with its centroid
        error = np.abs(compressed - image / 255.0).mean() * 255
        print(f"K={k:2d}: {k} colours, average error {error:.1f} out of 255")

    Output:

    Pixels: 273280 | unique colours: 96615
    K= 4: 4 colours, average error 17.4 out of 255
    K= 8: 8 colours, average error 11.2 out of 255
    K=16: 16 colours, average error 8.0 out of 255
    K-means clustering image compression: a pagoda photo with 96,615 colours, then with 16 colours and with 4 colours
    The same photo with all its colours, with 16 colours, and with 4 colours. Photo by danielbuechele (CC BY 2.0), from scikit-learn’s sample images, recoloured with k-means.

    The photo has 96,615 different colours. With 16 the average error per colour channel is only 8 out of 255 and the picture still looks natural; you mostly notice it in the sky. With 4 colours the error doubles and the scene turns into a flat poster. We fitted k-means on a random sample of 5,000 pixels instead of all 273,280 to keep it fast, then used predict() to colour every pixel. For very large datasets, MiniBatchKMeans does the same job faster. scikit-learn has its own colour quantisation example if you want to go further.

    Advantages and limitations of k-means clustering

    Advantages

    • Simple to understand, explain and implement.
    • Fast: each round is roughly O(n × K × d) for n points and d features, so it scales to large datasets, especially with MiniBatchKMeans.
    • Always converges, usually in a few rounds.
    • The centroids are easy to interpret as “typical members” of each group.

    Limitations

    • You must choose K in advance.
    • It assumes round (convex) clusters of similar size and spread; curved shapes and very uneven groups go wrong, as lessons 5 and 6 show.
    • Results depend on the starting centroids; use k-means++ and several restarts.
    • Sensitive to outliers, because one extreme point pulls the mean towards it. K-medoids, which uses real data points as centres, is more robust.
    • Needs scaled, numeric features; categorical data needs a variant such as k-modes.
    • Every point is forced into a cluster, even noise.

    Alternatives when k-means does not fit

    AlgorithmUse it whenNeeds K?
    DBSCANClusters have odd shapes, or you want outliers flagged as noiseNo (needs a distance radius)
    Gaussian mixture modelClusters are oval or different sizes, or you want soft (probability) assignmentsYes
    Hierarchical (agglomerative)You want a tree of clusters (dendrogram) and small to medium dataNo, cut the tree later
    K-medoidsThere are outliers, or you need any distance measureYes
    Mini-batch k-meansData is very largeYes

    K-means vs KNN

    The names sound similar and both use distances, so they are often mixed up in interviews.

    K-meansK-nearest neighbours (KNN)
    TypeUnsupervised clusteringSupervised classification or regression
    Needs labels?NoYes
    What K meansNumber of clustersNumber of neighbours to look at
    TrainingIteratively finds centroidsNone: it just stores the data
    PredictionNearest centroidMajority vote (or average) of the K nearest training points

    Applications of k-means clustering

    • Customer segmentation: grouping shoppers by income, spending, visits or basket size for targeted offers.
    • Image compression and segmentation: reducing colours, or separating a photo into regions.
    • Document clustering: grouping news articles or support tickets by topic, using text vectors.
    • Anomaly detection: flagging points that are far from every centroid, such as unusual transactions.
    • Feature engineering: using the cluster number or the distance to each centroid as new features for a supervised model.
    • Delivery and store planning: grouping addresses to decide where to put warehouses or delivery hubs.

    K-means clustering interview questions and answers

    These are the k-means questions that come up most in data science and machine learning interviews, with short answers you can say out loud.

    1. What is k-means clustering?

    An unsupervised algorithm that partitions data into K clusters. It places K centroids and assigns each point to the nearest one, then moves each centroid to the mean of its points, repeating until the clusters stop changing.

    2. Explain the steps of the k-means algorithm.

    Choose K, initialise K centroids, assign each point to its nearest centroid, update each centroid to the mean of its assigned points, and repeat the assign and update steps until assignments stop changing or a maximum number of iterations is reached.

    3. What objective does k-means minimise?

    The within-cluster sum of squares (WCSS), also called inertia: the sum of squared Euclidean distances from each point to its cluster centroid.

    4. Does k-means always converge? Does it find the global optimum?

    It always converges, because neither step can increase WCSS and the number of possible partitions is finite. But it only reaches a local minimum, which depends on the starting centroids.

    5. How do you choose the value of K?

    Use the elbow method on a plot of WCSS against K, the silhouette score, or the gap statistic, together with domain knowledge about how many groups are useful.

    6. What is the elbow method?

    You plot WCSS for a range of K values and pick the K at the bend of the curve, after which adding clusters gives only small reductions in WCSS.

    7. What is the silhouette score?

    For each point, s = (b − a) / max(a, b), where a is the mean distance to points in its own cluster and b is the mean distance to points in the nearest other cluster. The average ranges from −1 to 1; higher means better separated clusters.

    8. What is k-means++?

    An initialisation method that picks the first centroid at random and each next centroid with probability proportional to its squared distance from the nearest centroid already chosen. It spreads the centroids out and gives better, more consistent results.

    9. Why should you scale features before k-means?

    Because k-means uses Euclidean distance, features with larger ranges dominate the distance. Standardising puts all features on a comparable scale.

    10. What are the main limitations of k-means?

    You must choose K, it assumes convex clusters of similar size and density, it is sensitive to initialisation and outliers, it needs numeric scaled features, and it assigns every point to some cluster.

    11. How does k-means handle outliers?

    Poorly. Outliers pull centroids towards them because the centroid is a mean. You can remove outliers first, or use K-medoids or DBSCAN.

    12. What is the difference between k-means and KNN?

    K-means is unsupervised clustering where K is the number of clusters. KNN is supervised classification or regression where K is the number of neighbours used to predict a label.

    13. What is the difference between k-means and k-medoids?

    K-means uses the mean of the points as the centre, which may not be an actual data point. K-medoids uses an actual data point (the medoid) and can work with any distance, which makes it more robust to outliers.

    14. What is the time complexity of k-means?

    About O(n × K × d × i) for n points, K clusters, d features and i iterations. It is linear in the number of points, which is why it scales well.

    15. What happens if a cluster becomes empty?

    Its centroid has no points to average. Implementations handle it differently: keep the old centroid, or move it to a point far from the others, as scikit-learn does.

    16. What is mini-batch k-means?

    A variant that updates the centroids using small random batches of data instead of the whole dataset each round. It is much faster on large data, with slightly worse inertia.

    17. Can k-means be used for categorical data?

    Not directly, because means and Euclidean distances do not make sense for categories. Use k-modes for categorical data or k-prototypes for mixed data.

    18. How can k-means help a supervised model?

    The cluster label, or the distance to each centroid, can be added as a feature. K-means can also be used to compress data or choose representative samples.

    Test yourself: k-means clustering quiz

    Ten questions on everything above. Eight or more right means you are ready for k-means questions in an interview.

    Quiz

    K-means clustering quiz

    10 questions, about three minutes.

    Download the free k-means clustering notes (PDF)

    Everything on this page in a printable format: the algorithm and pseudocode, the solved numerical example, the elbow and silhouette methods, k-means++, all seven code examples with their outputs, and the interview questions.

    Free PDF

    K-means clustering notes by Code and Debug

    11 pages, no sign-up needed.

    Download PDF

    Frequently asked questions

    Is k-means supervised or unsupervised?

    K-means is unsupervised. It does not use labels; it groups points only by how close they are to each other.

    What does K mean in k-means clustering?

    K is the number of clusters you want. You choose it before running the algorithm, often with the elbow method or the silhouette score.

    How do I find the optimal number of clusters?

    Run k-means for a range of K values. Plot WCSS and look for the elbow, and compute the silhouette score and pick the highest. Then check that the clusters make sense for your problem.

    What is inertia in k-means?

    Inertia is the sum of squared distances from each point to the centroid of its cluster, also called WCSS. scikit-learn stores it in the inertia_ attribute. Lower means tighter clusters.

    Why does k-means give different results each time?

    The starting centroids are chosen randomly, and k-means can stop at different local minima. Set random_state to repeat a result, and use k-means++ with n_init greater than 1 to get the best one.

    When should I not use k-means?

    Avoid it when clusters are curved or very different in size or density, when there are many outliers, or when your features are categorical. DBSCAN, Gaussian mixture models or k-modes are better choices there.

    What to learn next

    You now know how k-means clustering works, how to choose K and when to use something else. Good next topics:

    • Decision tree in machine learning, a supervised model you can grow step by step in its own playground.
    • Support vector machine (SVM), another distance-based model where feature scaling matters.
    • Confusion matrix in machine learning, for when you move from clusters to labelled classification.
    • How to learn AI and ML from scratch, our full roadmap with a personal study planner.
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleDecision Tree in Machine Learning: An Interactive Guide (with Python)
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    AI & Machine Learning

    Decision Tree in Machine Learning: An Interactive Guide (with Python)

    18 November 2026
    AI & Machine Learning

    Support Vector Machine (SVM) in Machine Learning: An Interactive Guide

    16 November 2026
    AI & Machine Learning

    Confusion Matrix in Machine Learning: An Interactive Guide

    21 October 2026
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (7)
    • Data Structures & Algorithms (241)
      • Beginner (82)
      • Expert (52)
      • Intermediate (106)
    • Interview Questions (5)
    • Pandas (1)
    • Python (1)
    • Resume (1)
    • SQL (1)
    Recent Posts

    K-Means Clustering in Machine Learning: An Interactive Guide (with Python)

    20 November 2026

    Decision Tree in Machine Learning: An Interactive Guide (with Python)

    18 November 2026

    Support Vector Machine (SVM) in Machine Learning: An Interactive Guide

    16 November 2026

    100 OOPs Interview Questions and Answers (Freshers to Experienced)

    16 November 2026

    100 Computer Networks Interview Questions and Answers (Freshers to Experienced)

    15 November 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.