esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
Let’s talk

I’ll build the agent for it.

What Is K-Means?

What k-means is, the steps it repeats, how to choose k, and where it goes wrong, explained simply for your AI interview.

In short

K-means is a method that splits unlabelled data into k groups. It places k centre points, assigns each item to its nearest centre, moves each centre to the middle of its group, and repeats until the centres stop moving much. It is quick, but the result depends on the starting guesses.

11 min readBeginnerOccasional · estimateFacts checked 27 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

K-means sorts unlabelled data into k groups, and I choose k. It places k centre points, gives each item to its nearest centre, moves each centre to the middle of its group, and repeats until the centres settle. A bank could use it to group card customers by spend and how often they pay. It's quick, but the starting guesses change the answer, and the numbers need scaling first. So I run it more than once and check the groups by hand.

What is k-means, in plain words?

K-means is a way to sort data into a set number of groups when nobody has labelled the answers. You pick the number, called k. The method places k centre points, puts each item in the group of its nearest centre, and moves each centre to the middle of its group. Then it repeats.

Picture a courier firm with 300 delivery addresses and room for four depots. A dispatcher puts four depots on the map, sends each address to its nearest depot, then moves each depot to the middle of its addresses. She repeats that until the depots stop moving. That is k-means with k set to 4.

The real AI case is a bank with millions of card customers. It wants groups of people who spend in similar ways, so it can tune offers for each group. Each customer becomes a row of numbers, such as monthly spend and transactions, and the method returns a group for each row. Google's course says k-means is the most widely used of the clustering methods.

Key words

Cluster
A group of items that sit close together by the numbers you gave.
Centroid
The middle of a group: the average of its members. Often not a real customer.
k
The number of groups you choose before the method starts.
Inertia
The within-cluster sum of squares: how far each item sits from its own centre, squared and added up. Lower means tighter groups.

How does k-means work, step by step?

The algorithm is often called Lloyd's algorithm. Amazon's guide to its own k-means service describes the goal in one sentence:

  • “It attempts to find discrete groupings within data, where members of a group are as similar as possible to one another and as different as possible from members of other groups.”

    Amazon Web Services

  1. 1

    Pick starting centres

    Choose k starting points. The simplest way is to take k items from the data, so the first centres are only guesses.

  2. 2

    Assign each item

    Each item joins the group of its nearest centre. Nearness is straight-line distance across all its numbers.

  3. 3

    Move each centre

    Each centre moves to the average of the items now in its group.

  4. 4

    Stop when stable

    Repeat the last two steps until the centres barely move. Then the groups are final.

The steps of one k-means run

Pick k starting centres

You choose k, and the first guesses.

Repeat until stable

Assign each point

Each point joins its nearest centre.

Move each centre

Each centre moves to its group's mean.

Stable groups

Centres barely move now.

  1. 1You hand over the first centres, and the loop starts.
  2. 2Once every point has a group, each centre moves to the mean of its group.
  3. 3When the centres stop moving much, the groups are final.
The chart shows one pass. The first centres are guesses. Each pass assigns every point and then moves each centre, and the loop repeats until the centres stop moving much.

How do you choose k?

You choose k before the run. The scikit-learn guide says it plainly: "This algorithm requires the number of clusters to be specified." The method cannot find the right number of groups for you.

A common approach is to try several values of k and compare the results. Inertia, the within-cluster sum of squared distances, tends to fall as k rises, so the lowest inertia is not the right answer. A common rule of thumb is to look for an elbow on a chart: the point where adding a group stops helping much. A silhouette score is another check, because it rewards groups that are tight and well apart. scikit-learn's examples use it for exactly this: "In this example the silhouette analysis is used to choose an optimal value for n_clusters."

Tip

Asked how to pick k? Say you try a few values, use a score such as silhouette, then check the groups make sense to someone who knows the business. A score cannot tell you what the business needs.

What does a small worked example look like?

Here is a made-up bank with eight card customers. Each has monthly card spend and transactions per month. Spend runs into the hundreds and thousands, while the counts run into the tens. So the distance between two customers is mostly a spend gap. That is the hard part, and the fix is to scale the columns to similar ranges before you start. The code skips scaling to stay short, and it starts with two customers as the first guesses.

Python
# A made-up bank groups 8 card customers by monthly card spend (pounds) and
# transactions per month. Two starting customers act as the first centres.
customers = [(120, 8), (150, 10), (135, 9), (160, 11),
             (940, 42), (1010, 47), (880, 39), (990, 44)]

def mean(points):
    return tuple(sum(p[i] for p in points) / len(points) for i in range(2))

def dist2(a, b):
    return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2

centres = [customers[0], customers[1]]
for step in range(1, 10):
    groups = [[], []]
    for c in customers:
        nearest = min(range(2), key=lambda j: dist2(c, centres[j]))
        groups[nearest].append(c)
    new = [mean(g) for g in groups]
    print(f"step {step}: sizes {len(groups[0])} and {len(groups[1])}, "
          f"centres {[tuple(round(x) for x in n) for n in new]}")
    if new == centres:
        break
    centres = new

Output

step 1: sizes 2 and 6, centres [(128, 8), (688, 32)]
step 2: sizes 4 and 4, centres [(141, 10), (955, 43)]
step 3: sizes 4 and 4, centres [(141, 10), (955, 43)]

Step 1 splits the customers 2 and 6. Both starting guesses were low spenders, so the first centres sit badly. By step 2 the groups are 4 and 4, with centres near 141 pounds and 10 transactions for the first group, and 955 pounds and 43 transactions for the second. Step 3 changes nothing, so the run stops. The first split is poor because both starting guesses were low spenders. scikit-learn notes the result is highly dependent on how the centroids start, so one run is not enough to trust.

Where does k-means go wrong?

  • Bad starting guesses

    Two runs can end in different answers. Run it several times and keep the best, or use the k-means++ start that scikit-learn offers.

  • Only round groups

    It assumes groups are roughly round and of similar size. Long, curved or ring-shaped groups get cut in the wrong place.

  • Outliers

    A few extreme customers can drag a centre away from the group it should describe.

  • Unscaled numbers

    The column with the biggest numbers decides the distance. Scale the columns first.

  • Choosing k

    You set k yourself. A wrong k gives tidy but misleading groups.

  • “Centroid-based clustering algorithms are efficient but sensitive to initial conditions and outliers.”

    Google Developers

  • “Given enough time, K-means will always converge, however this may be to a local minimum.”

    scikit-learn

A density method such as DBSCAN can help with odd shapes, because its clusters can take almost any form. scikit-learn's comparison says k-means assumes clusters are convex shaped, while clusters found by DBSCAN can be any shape.

How would you group two million card customers for a bank?

Start with the goal and an owner. The goal is offers for each group. The owner is the team that will name the groups and act on them. Then work through these steps:

  1. 1

    Scale and pick columns

    Put spend, counts and tenure on comparable scales. Drop columns that only repeat each other.

  2. 2

    Use a faster version

    Fit on a sample, or use the mini-batch version. scikit-learn says mini-batch results are generally only slightly worse than the standard algorithm, so check them against a full run.

  3. 3

    Run several starts

    Keep the run with the lowest inertia. Record the k you chose and why.

  4. 4

    Check with people

    Ask the offers team to name each group. A group nobody can name is a warning sign.

  5. 5

    Watch for drift

    Spending habits change, so re-run every quarter and compare the new groups with the old ones.

What does the interviewer want to hear?

A strong answer covers

  • K-means groups unlabelled data by distance, with k set up front.
  • The steps: pick centres, assign each point, move the centres, repeat until stable.
  • You must choose k, and the result depends on the starting guesses.
  • Scale the columns first, and watch for outliers and round-shape assumptions.
  • How you check the groups: a score, then a person who knows the business.
  • When to pick another method, such as DBSCAN for odd shapes.

Common traps

  • Trap"K-means finds the right number of groups."

    BetterYou pick k up front. It only finds the best groups for the k you gave.

  • Trap"It's supervised, like classification."

    BetterIt has no labels. It groups by distance alone, so it is unsupervised.

  • Trap"Run it once and the groups are right."

    BetterStarting guesses change the result, so run it several times and compare.

Can you spot the problem?

Spot the problem

A fraud team runs k-means on raw card data. Which setup is the problem?

Quick check

Which choice must you make before k-means starts?

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q411Supervised vs unsupervised vs reinforcement learning?10 min
  2. Q428What is feature engineering?9 min
  3. Q434What is the curse of dimensionality?10 min
  4. Q436How do you tune hyperparameters?10 min
  5. Q424What is data leakage?11 min

Learn it in depth

Last updated on 27 November 2026

Grouping customers or claims in your product?

Venkat designs and builds AI products and agents (the UI and the system behind it), so book a short call and say what you need. No promises, no numbers.