Groups and a two-dimensional view.
Scale numeric rows, fit clusters, then project them for interpretation without calling the picture ground truth.
Why this workflow exists.
Clustering gives labels without known target answers. PCA can then project the same scaled rows onto two axes for a compact view of variation. This recipe keeps these operations separate: scaling prepares geometry, KMeans assigns groups, and PCA describes a projection. A cluster label is not a known class, and a two-dimensional projection is not a complete picture of the original feature space.
The generated points deliberately form three clouds, so the grouping is easier than most real unsupervised tasks. The script reports cluster sizes and how much variance the two components retain. That makes the result readable without requiring a plotting library.
Code context. Python 3 with NumPy and scikit-learn installed. The point cloud is generated locally.
The whole example.
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
X, known_only_for_demo = make_blobs(
n_samples=150, n_features=3, centers=3,
cluster_std=0.6, random_state=5,
)
scaled = StandardScaler().fit_transform(X)
clusterer = KMeans(n_clusters=3, n_init=10, random_state=5)
cluster_ids = clusterer.fit_predict(scaled)
projection = PCA(n_components=2).fit(scaled)
points_2d = projection.transform(scaled)
print("cluster sizes:", np.bincount(cluster_ids))
print("variance retained:", projection.explained_variance_ratio_.sum())
print("first projected row:", points_2d[0])What each stage does.
make_blobs creates a three-feature point cloud and also returns generated group labels. The variable name known_only_for_demo emphasizes that KMeans never receives those labels. StandardScaler learns the feature means and spreads, and clusterer fits three centers in the scaled space. fit_predict assigns one arbitrary integer cluster ID per row. np.bincount counts how many rows received each ID.
PCA fits two directions of high variation in the scaled data, then transform gives two coordinates per row. explained_variance_ratio_ reports the share of total variation in those directions. A high number means the projection retains much variance; it does not prove the clusters are meaningful or that every important difference is visible.
What the output means.
Three cluster sizes, a retained-variance fraction, and one projected coordinate are printed. Cluster IDs may be permuted without changing the grouping.
Where the example stops.
For a real unlabeled dataset, choosing three clusters would need a domain question and stability analysis. Scaling and projection must be refitted carefully if used as part of a later predictive pipeline.