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
n_clustersis the choice you have to justify.inertia_is the within-cluster sum of squares, lower is tighter.labels_assigns every training row to a cluster.
Keywords and builtins used here
asprint
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.
Step 1 of 2 in Unsupervised, step 20 of 25 in Machine learning with scikit-learn.