Updating centroid locations

In the previous section, we implemented the first part of the k-means algorithm: looking at all points in the dataset and assigning them to the centroid that's geographically closest. The next step in the algorithm is to look at all centroids and update their locations to the mean value of all the points assigned to them.

To make an analogy, you can imagine each point reaching out and grabbing the centroid closest to it. The points give the centroid a tug, trying to pull it closer to them. We've already implemented the reach out and grab portion of the algorithm, and now we'll implement the pull the centroid closer portion.

At a high level, our task is to loop over all the centroids, and for each, determine the ...

Get Hands-on Machine Learning with JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.