K-Means drops its starting centroids at random, and an unlucky drop can leave it stuck with a poor clustering, for example when two centroids land inside the same natural group. K-Means++ is a smarter way to choose the starting centroids. It still uses randomness, but it tilts the odds toward points that are far from every centroid chosen so far.
The recipe, for a list of points and k clusters:
k centroids have been chosen.So that everyone gets the same answer, the random numbers have been drawn in advance. draws holds k numbers, each at least 0 and less than 1. Use them like this:
int(draws[0] * len(points)).draws[c] . Then go through the points in order, keeping a running sum of their values, and pick the first point whose running sum is greater than the target.Task: write kmeans_pp_starts(points, k, draws) and return the indices of the chosen points, in the order they were chosen.
k different positions, so there is always a valid next centroid.The running sum is the standard trick for drawing at random with uneven chances. Lay all the values end to end along a line of length , drop a pin at
draws[c], and take whichever point's stretch the pin lands in. Far-away points own long stretches, so they are hard to miss.