KMeans

noun

say it: “KAY MEENZ” /ˈkeɪ ˈminz/

scikit-learn's tool for k-means clustering, which groups rows into a chosen number of clusters.

What is KMeans in scikit-learn?

KMeans is scikit-learn's k-means clustering. KMeans(n_clusters=3) learns the centers with fit(); labels_ holds each row's cluster number, cluster_centers_ the centers, and predict() puts new rows in the nearest cluster. Set random_state so the clusters come out the same every run.

from sklearn.cluster import KMeans
visits = [[1, 30], [2, 28], [1, 32], [6, 5], [7, 6], [6, 4]]   # visits a week, dollars a visit
km = KMeans(n_clusters=2, random_state=0).fit(visits)
print(km.labels_)   # [1 1 1 0 0 0]: the big spenders, then the frequent visitors

In a sentence

  • “She set random_state on KMeans so the groups came out the same every time.”
  • “KMeans with n_clusters=4 split the loyalty-card customers into four groups.”

Level: Journeyman · More Python terms at this level

Updated