typestar

KMeans clustering in Python

Unsupervised: no labels, just centroids and the points nearest each one.

import numpy as np
from sklearn.cluster import KMeans

points = np.array([[1.0, 1.0], [1.4, 0.8], [5.0, 5.2],
                   [5.4, 4.8], [9.0, 9.1], [8.6, 9.4]])

model = KMeans(n_clusters=3, n_init=10, random_state=0)
model.fit(points)

print(model.labels_)
print(model.cluster_centers_.round(2))
print(f"inertia {model.inertia_:.3f}")
print(model.predict([[5.2, 5.0]]))

How it works

  1. n_clusters is the choice you have to justify.
  2. inertia_ is the within-cluster sum of squares, lower is tighter.
  3. labels_ assigns every training row to a cluster.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
356
Tokens
122
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 67 seconds.

Type this snippet

Step 1 of 2 in Unsupervised, step 20 of 25 in Machine learning with scikit-learn.

← Previous Next →