K-means clustering

JavaScript, Algorithm, Array · Dec 29, 2020

Groups the given data into k clusters, using the k-means clustering algorithm.

const kMeans = (data, k = 1) => {
  const centroids = data.slice(0, k);
  const distances = Array.from({ length: data.length }, () =>
    Array.from({ length: k }, () => 0)
  );
  const classes = Array.from({ length: data.length }, () => -1);
  let itr = true;

  while (itr) {
    itr = false;

    for (let d in data) {
      for (let c = 0; c < k; c++) {
        distances[d][c] = Math.hypot(
          ...Object.keys(data[0]).map(key => data[d][key] - centroids[c][key])
        );
      }
      const m = distances[d].indexOf(Math.min(...distances[d]));
      if (classes[d] !== m) itr = true;
      classes[d] = m;
    }

    for (let c = 0; c < k; c++) {
      centroids[c] = Array.from({ length: data[0].length }, () => 0);
      const size = data.reduce((acc, _, d) => {
        if (classes[d] === c) {
          acc++;
          for (let i in data[0]) centroids[c][i] += data[d][i];
        }
        return acc;
      }, 0);
      for (let i in data[0]) {
        centroids[c][i] = parseFloat(Number(centroids[c][i] / size).toFixed(2));
      }
    }
  }

  return classes;
};
kMeans([[0, 0], [0, 1], [1, 3], [2, 0]], 2); // [0, 1, 1, 0]

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • JavaScript Arrays

    Master array manipulation in JavaScript with this ES6 snippet collection.

    Collection · 207 snippets

  • K-nearest neighbors

    Classifies a data point relative to a labelled data set, using the k-nearest neighbors algorithm.

    JavaScript, Algorithm · Oct 13, 2021

  • Binary search

    Finds the index of a given element in a sorted array using the binary search algorithm.

    JavaScript, Algorithm · Dec 29, 2020

  • Linear search

    Finds the first index of a given element in an array using the linear search algorithm.

    JavaScript, Algorithm · Dec 28, 2020