# 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.

AI and LLM interview question Q433, Classic ML and deep-learning basics. Beginner, occasional (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/what-is-k-means

## Say it in 30 seconds

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.

## Say it in 2 minutes

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.

Here is a real case. A bank with millions of card customers wants groups of people who spend in similar ways, so it can tune offers for each group. It has no labels for those groups, so k-means is a sensible first pass. Each customer becomes a row of numbers, such as monthly spend and transactions, and the method returns a group for each row.

The weak spots matter as much as the method. Because it starts from guesses, two runs can give two answers, so I run it several times and keep the best. It likes round groups of similar size, and a few extreme customers can pull a centre away from its group. For odd shapes I would look at a density method such as DBSCAN instead.

So my answer is this: k-means finds groups by distance, it is fast and simple, and it is a good first try. I still check the groups by hand before anyone acts on them.

## 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.

- **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. **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. **Assign each item:** Each item joins the group of its nearest centre. Nearness is straight-line distance across all its numbers.
3. **Move each centre:** Each centre moves to the average of the items now in its group.
4. **Stop when stable:** Repeat the last two steps until the centres barely move. Then the groups are final.

*Diagram, The steps of one k-means run: 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.*
1. You hand over the first centres, and the loop starts.
2. Once every point has a group, each centre moves to the mean of its group.
3. When the centres stop moving much, the groups are final.

## 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:

```text
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. **Scale and pick columns:** Put spend, counts and tenure on comparable scales. Drop columns that only repeat each other.
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. **Run several starts:** Keep the run with the lowest inertia. Record the k you chose and why.
4. **Check with people:** Ask the offers team to name each group. A group nobody can name is a warning sign.
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." Better: You pick k up front. It only finds the best groups for the k you gave.
- Trap: "It's supervised, like classification." Better: It has no labels. It groups by distance alone, so it is unsupervised.
- Trap: "Run it once and the groups are right." Better: Starting 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?

A. Scaled both columns to a similar range, then fitted 4 groups.
B. Raw columns: spend up to 1,010 pounds and transactions from 8 to 47, fitted with 4 groups.
C. Ran it 10 times with different starts and kept the run with the lowest inertia.
D. Checked each group with the fraud team before acting on it.

**Answer:** B. Spend runs into the hundreds and thousands, while counts run into the tens, so the distance is mostly spend. Scale the columns first.

**Quick check:** Which choice must you make before k-means starts?

A. The true label of every item
B. The number of groups, k
C. The final position of each centre
D. A score that proves the groups are right

**Answer:** B. K-means uses no labels, and it works out the centres itself. You set k, and the method finds the rest.

## Can you answer these from memory?

**Flash cards**

- **What is k-means?** An unsupervised method that splits data into k groups around k centres.
- **What are the steps?** Pick centres, assign each point to its nearest centre, move the centres, repeat until stable.
- **Does it need labels?** No. It groups by distance alone, so it is unsupervised.
- **What must you choose up front?** k, the number of groups. The method cannot pick it for you.
- **Why run it several times?** Starting guesses change the result, and it can settle on a local minimum.
- **What breaks it?** Unscaled columns, outliers, and groups that are not round or similar in size.

## Likely follow-up questions

- Q411 Supervised vs unsupervised vs reinforcement learning? https://designervenkat.online/interview/ai/supervised-vs-unsupervised-vs-reinforcement-learning
- Q428 What is feature engineering? https://designervenkat.online/interview/ai/what-is-feature-engineering
- Q434 What is the curse of dimensionality? https://designervenkat.online/interview/ai/what-is-the-curse-of-dimensionality
- Q436 How do you tune hyperparameters? https://designervenkat.online/interview/ai/how-do-you-tune-hyperparameters
- Q424 What is data leakage? https://designervenkat.online/interview/ai/what-is-data-leakage

## Learn it in depth

- [Unsupervised learning](https://designervenkat.online/learn/machine-learning/unsupervised-learning)
- [Clustering: finding groups by yourself](https://designervenkat.online/learn/machine-learning/clustering)
- [Exclusive clustering: one point, one group](https://designervenkat.online/learn/machine-learning/exclusive-clustering)
