Clustering groups data without target labels. In k-means, you choose the number of groups Each group has a centre called a centroid. The aim is to minimise the total squared distance from each point to its assigned centre
Start with centres and alternate two steps:
- Assign every point to its nearest centre. With the centres fixed, this gives the smallest squared distance for every point.
- Move each centre to the mean of its assigned points. With the groups fixed, the mean minimises the sum of squared distances within its group. An empty group has no mean, so you can leave its centre in place.
For a small example, put points on a line and start centres at and At first only joins the left group. The right centre moves to so on the next assignment and switch to the left. Continue until the assignments stop changing.
Neither step increases but the final groups can depend on the starting centres. Try several starts with the same and keep the one with the lowest Increasing can only lower or leave unchanged the best possible a centre per point gives zero. Look for a point where adding another group helps much less (an elbow), and check that the resulting groups are useful.
Distance depends on your units: changing one feature from metres to centimetres makes its squared differences times larger. Put features on comparable scales if the units should not decide the groups. Even with sensible scales, k-means favours groups that fit around centres; it gives each point exactly one label, even when two groups overlap.