K-means clustering

Unsupervised · Clustering K-means groups data into K clusters without any labels. Each cluster has a centre point (the centroid). Every item joins its nearest centre, then each centre moves to the middle of its group. This repeats until the groups stop changing.

Everyday analogy

Placing 3 water tanks in a village so every house is close to one. Put the tanks anywhere, let each house use its nearest tank, then move each tank to the middle of its houses. Repeat until nothing moves.

Example

Used for: customer segmentation for marketing, grouping similar news articles, compressing image colours, planning store or warehouse locations.

✖✖✖✖ = centre of each group (found automatically, no labels needed)
K-means finds K groups by repeatedly moving each centre to the middle of its points.

Three customer groups found automatically

Visits per month →Amount spent →Occasional buyersBig-basket shoppersFrequent small buyers

✕ = the centre (centroid) of each group. The group names are added by people after looking at the clusters.

How it works, step by step

  1. Choose K, the number of groups you want.
  2. Place K centre points at random.
  3. Assign every item to its nearest centre.
  4. Move each centre to the average position of the items assigned to it.
  5. Repeat steps 3 and 4 until the centres stop moving.

Worked example

A supermarket runs K-means with K = 3 on customers' monthly visits and spending. It finds three groups, which the marketing team names "occasional buyers", "big-basket shoppers" and "frequent small buyers", and sends each group different offers.

✓ Good for

  • Simple, fast and works on large datasets
  • Needs no labels at all
  • Easy to explain the resulting groups

⚠ Watch out for

  • You must choose K yourself (the "elbow method" helps)
  • Works best when groups are roughly round and similar in size
  • Outliers and random starting points can change the result

Try it yourself

About 10 min

Group customers by hand

  1. Write 12 customers with two numbers: visits per month and average spend.
  2. Plot them in a spreadsheet scatter chart.
  3. Circle 3 groups and give each a name, e.g. loyal big spenders.

What you should see: That's clustering: finding groups without being told what they are.

Use any free AI chatbot (ChatGPT, Claude, Gemini or Copilot). Never paste private or confidential information.

Build it for real · guided projectFind customer groups with K-means clusteringAbout 45 min · Copy-paste code · step by step
Test what you learned

Take a quick quiz, or look up any word in the glossary.