K-Means Clustering and PCA: Unsupervised ML Essentials

In real-world data science, the vast majority of collected data arrives without neat ground-truth labels. Manually annotating millions of records is expensive, slow, and often impossible.

To extract actionable intelligence from unlabeled data, machine learning relies on Unsupervised Learning. Instead of learning from predefined target labels, unsupervised algorithms discover hidden patterns, structures, and relationships within datasets.

Two foundational techniques in this domain are:

  • K-Means Clustering: Discovers natural, discrete groupings and segments across unlabeled data points.
  • Principal Component Analysis (PCA): Compresses high-dimensional feature spaces into compact representations while retaining as much informative variance as possible.

Although these algorithms solve different problems, they complement each other in exploratory data analysis, customer segmentation, data compression, visualization, and machine learning pipelines.

Understanding both techniques—and how they work together—is essential for anyone learning machine learning and data science.


1. Understanding Unsupervised Learning

Unsupervised learning is a machine learning approach in which algorithms analyze data without predefined target labels.

Unlike supervised learning, where a model learns from input-output pairs, unsupervised learning attempts to discover patterns directly from the input features.

For example, consider an e-commerce company with thousands of customers.

Its dataset might contain:

  • Customer age.
  • Annual income.
  • Purchase frequency.
  • Average order value.
  • Website visit frequency.
  • Product preferences.

The company may not know which customer belongs to which behavioral group.

An unsupervised algorithm can analyze these features and identify groups such as:

  • High-value customers.
  • Frequent buyers.
  • Occasional shoppers.
  • Discount-oriented customers.

This is an example of Customer Segmentation.

Common Types of Unsupervised Learning

TechniquePurposeExample Algorithms
ClusteringGroups similar observationsK-Means, DBSCAN, Hierarchical Clustering
Dimensionality ReductionReduces the number of featuresPCA, t-SNE, UMAP
Association Rule LearningFinds relationships between itemsApriori, FP-Growth
Anomaly DetectionIdentifies unusual observationsIsolation Forest, One-Class SVM

K-Means belongs to clustering, while PCA belongs to dimensionality reduction.


2. K-Means Clustering: Finding Natural Clusters

K-Means is a centroid-based, iterative partitioning algorithm.

It groups \(N\) observations into \(K\) distinct, non-overlapping clusters, where each observation is assigned to the cluster with the nearest mean (centroid).

The central idea is:

Observations that are similar to each other should belong to the same cluster.

For example, a retail company can use K-Means to group customers based on income and purchasing behavior.

How the Algorithm Works (Lloyd's Algorithm)

K-Means follows an iterative process consisting of initialization, assignment, and centroid updates.

Step 1: Initialization

Choose \(K\), the desired number of clusters.

Initialize \(K\) cluster centroids:

\[ \mu_1,\mu_2,\ldots,\mu_K \]

These centroids represent the initial centers of the clusters.

K-Means++ is a commonly used initialization strategy.

Step 2: Assignment Step

Calculate the distance between each observation and every centroid.

Assign each observation to the nearest centroid using squared Euclidean distance:

\[ c^{(i)}=\arg\min_j\|x_i-\mu_j\|^2 \]

Where:

  • \(x_i\) = Data point.
  • \(\mu_j\) = Centroid of cluster \(j\).
  • \(c^{(i)}\) = Assigned cluster.

Step 3: Update Step

Recalculate each centroid by computing the arithmetic mean of all observations assigned to that cluster.

\[ \mu_j= \frac{1}{|S_j|} \sum_{i\in S_j}x_i \]

Where:

  • \(S_j\) = Set of observations assigned to cluster \(j\).
  • \(|S_j|\) = Number of observations in that cluster.

Step 4: Convergence

Repeat the assignment and update steps until:

  • Centroids stop moving significantly.
  • Cluster assignments stop changing.
  • The algorithm reaches a specified maximum iteration count.

The process is repeated until a stopping condition is satisfied.

Visual Understanding of K-Means

<AsyncImage query="K means clustering algorithm three colored clusters with centroid markers before after iteration educational machine learning diagram" aspectRatio="16:9" width="100%" />

The visualization illustrates how K-Means assigns observations to nearby centroids and gradually updates the centroid positions.

Example: Customer Segmentation

Suppose a shopping company collects customer information using two features:

  • Annual income.
  • Spending score.

The company wants to divide its customers into three groups.

CustomerAnnual IncomeSpending Score
A2580
B3075
C2885
D7520
E8025
F8518
G5050
H5555
I4845

For this simplified illustration, assume income is expressed in thousands of currency units.

With \(K=3\), K-Means may discover three customer groups:

  • High spending, lower income.
  • Low spending, higher income.
  • Medium spending, medium income.

These groups can help the company design targeted marketing campaigns.

The actual cluster assignments depend on initialization, feature scaling, and the optimization process.


3. The Objective Function: Inertia and WCSS

K-Means attempts to minimize the distance between observations and their assigned cluster centroids.

This objective is known as Within-Cluster Sum of Squares (WCSS), also called Inertia.

\[ WCSS= \sum_{j=1}^{K} \sum_{x_i\in S_j} \|x_i-\mu_j\|^2 \]

Where:

  • \(K\) = Number of clusters.
  • \(S_j\) = Observations assigned to cluster \(j\).
  • \(x_i\) = Individual observation.
  • \(\mu_j\) = Cluster centroid.

A lower WCSS indicates that observations are closer to their assigned centroids.

However, increasing the number of clusters generally reduces WCSS.

At the extreme, assigning each observation to its own cluster gives zero within-cluster error.

Therefore, simply minimizing WCSS is not enough. We need a suitable method to choose \(K\).


4. Selecting the Optimal Number of Clusters

Choosing the number of clusters is one of the most important decisions when using K-Means.

Two commonly used methods are the Elbow Method and Silhouette Analysis.

1. The Elbow Method

The Elbow Method evaluates how WCSS changes as the number of clusters increases.

The procedure is:

  1. Train K-Means using different values of \(K\).
  2. Calculate the WCSS for each value.
  3. Plot the number of clusters against WCSS.
  4. Identify the point where the reduction in WCSS begins to slow down.

This point resembles an elbow.

<AsyncImage query="K means elbow method WCSS inertia number of clusters graph clear elbow point machine learning" aspectRatio="16:9" width="100%" />

For example:

Number of Clusters (K)WCSS
11200
2720
3390
4250
5210
6185
7165

The reduction becomes smaller after \(K=4\).

Therefore, four clusters may be a reasonable candidate.

However, the elbow is sometimes ambiguous. It should be treated as a practical heuristic rather than a mathematically guaranteed optimal solution.

2. Silhouette Analysis

The Silhouette Score evaluates how well an observation fits within its assigned cluster compared with neighboring clusters.

For an observation \(i\):

\[ s(i)=\frac{b(i)-a(i)} {\max(a(i),b(i))} \]

Where:

  • \(a(i)\) = Average distance from observation \(i\) to other observations in its own cluster.
  • \(b(i)\) = Lowest average distance from observation \(i\) to observations in another cluster.

The score ranges from -1 to +1.

Silhouette ScoreInterpretation
Close to +1Observation is well matched to its cluster
Around 0Observation is near a cluster boundary
Below 0Observation may be assigned to the wrong cluster

<AsyncImage query="silhouette analysis clustering visualization positive negative silhouette coefficient plot machine learning" aspectRatio="16:9" width="100%" />

A higher average Silhouette Score generally indicates better-defined clusters.

However, it should not be used in isolation. A clustering with a high score may still be unsuitable for the business objective.


5. Crucial Caveats with K-Means

K-Means is computationally efficient and easy to implement, but it has important assumptions and limitations.

1. K-Means++ Initialization

Standard random initialization can produce poor initial centroids and lead to suboptimal local solutions.

K-Means++ improves initialization by choosing initial centroids with a preference for points that are far from existing centroids.

Its basic process is:

  1. Select an initial centroid randomly.
  2. Calculate the squared distance of each observation from its nearest selected centroid.
  3. Select the next centroid with probability proportional to that squared distance.
  4. Repeat until \(K\) centroids have been selected.

This often improves convergence and clustering quality.

It does not guarantee a globally optimal solution.

In Scikit-learn, K-Means++ is the default initialization strategy.

Using multiple initializations (n_init) also helps reduce sensitivity to a single initialization.

2. Cluster Shape and Density Assumptions

K-Means works best when clusters are relatively compact and approximately spherical in the selected feature space.

It can struggle with:

  • Elongated clusters.
  • Concentric circular clusters.
  • Irregularly shaped clusters.
  • Clusters with substantially different densities.
  • Clusters with very different sizes.

For these cases, density-based methods such as DBSCAN or hierarchical methods may be more suitable.

<AsyncImage query="K means clustering fails on concentric circles and moons compared to DBSCAN clustering educational comparison" aspectRatio="16:9" width="100%" />

3. Feature Scaling

K-Means uses distance calculations.

Suppose a dataset contains:

  • Annual income: 100,000–1,000,000.
  • Spending score: 0–100.

Without scaling, income may dominate the distance calculation.

A common solution is Standardization:

\[ z=\frac{x-\mu}{\sigma} \]

Where:

  • \(x\) = Original feature value.
  • \(\mu\) = Feature mean.
  • \(\sigma\) = Feature standard deviation.

This transforms features to approximately zero mean and unit variance.

Feature scaling is especially important when features have different units or ranges.

4. Sensitivity to Outliers

Centroids are calculated using arithmetic means.

Therefore, extreme observations can pull cluster centers away from the main concentration of data.

Possible solutions include:

  • Investigating and treating outliers.
  • Applying robust preprocessing.
  • Using K-Medoids.
  • Comparing with density-based clustering.

5. Hard Cluster Assignments

Each observation belongs to exactly one cluster.

K-Means does not naturally provide probabilistic membership in multiple clusters.

When observations overlap between groups, fuzzy clustering may be more suitable.

Advantages of K-Means

  • Simple to understand and implement.
  • Computationally efficient for many numerical datasets.
  • Scales reasonably well to large datasets.
  • Produces interpretable cluster centroids.
  • Useful for exploratory data analysis and segmentation.

Limitations of K-Means

  • Requires choosing \(K\) in advance.
  • Sensitive to initialization.
  • Sensitive to feature scaling and outliers.
  • Works best with compact, approximately spherical clusters.
  • Does not naturally handle categorical features using ordinary Euclidean distance.
  • Can converge to a local optimum rather than the global optimum.

6. Principal Component Analysis (PCA): Dimensionality Reduction

As datasets expand to hundreds or thousands of features, models may encounter the Curse of Dimensionality.

As the number of dimensions increases:

  • Feature space expands rapidly.
  • Data points become increasingly sparse.
  • Distance-based similarity can become less informative.
  • Models may become harder to train and interpret.
  • Redundant features can increase computational requirements.

Principal Component Analysis (PCA) is an unsupervised linear dimensionality-reduction technique that transforms correlated features into a smaller set of uncorrelated variables called principal components.

Its objective is to preserve as much total variance as possible using fewer dimensions.

Understanding Dimensionality Reduction

Suppose a dataset contains 100 features.

Some features may contain overlapping information.

For example:

  • Height in centimeters.
  • Height in meters.
  • Body length.
  • Related physical measurements.

PCA identifies directions that capture the largest variation in the data.

Instead of keeping all 100 original features, we may retain 10 principal components that preserve a large proportion of the original variance.

The transformed dataset becomes smaller and potentially easier to visualize and process.

Mathematical Objective

PCA constructs new uncorrelated variables called Principal Components (PCs).

Each principal component is a linear combination of the original features.

First Principal Component (PC1)

PC1 is the direction along which the data exhibits maximum variance.

Second Principal Component (PC2)

PC2 is orthogonal to PC1 and captures the highest remaining variance.

Subsequent Components

Each subsequent component is orthogonal to the preceding components and captures as much remaining variance as possible.

<AsyncImage query="principal component analysis PCA two dimensional data PC1 PC2 orthogonal directions variance educational diagram" aspectRatio="16:9" width="100%" />

The first principal component captures the largest possible variance, while the second captures the largest remaining variance under the orthogonality constraint.


7. How PCA Is Computed

PCA is commonly calculated using covariance matrix eigendecomposition or Singular Value Decomposition (SVD).

The main steps are:

Step 1: Center or Standardize the Data

First, subtract the mean of each feature.

\[ X_{\text{centered}}=X-\mu \]

If features have substantially different scales, standardize them as well:

\[ z=\frac{x-\mu}{\sigma} \]

Standardization is commonly used when the original features have different measurement units.

However, if the feature scales already have meaningful and comparable units, centering without standardizing may be more appropriate.

Step 2: Compute the Covariance Matrix

The covariance matrix measures how features vary together.

\[ \Sigma=\frac{1}{n-1}X^TX \]

Here, \(X\) represents the centered data matrix.

For \(p\) features, the covariance matrix has dimensions:

\[ p\times p \]

The covariance between two features indicates whether they tend to increase or decrease together.

  • Positive covariance: Features tend to increase together.
  • Negative covariance: One feature tends to increase as the other decreases.
  • Near-zero covariance: Little linear association is observed.

Step 3: Calculate Eigenvectors and Eigenvalues

Perform eigendecomposition on the covariance matrix.

\[ \Sigma v_i=\lambda_i v_i \]

Where:

  • \(v_i\) = Eigenvector representing a principal direction.
  • \(\lambda_i\) = Eigenvalue representing variance along that direction.

The eigenvectors define the principal component directions.

The eigenvalues determine how much variance each component explains.

Sort the eigenvalues in descending order:

\[ \lambda_1\geq\lambda_2\geq\cdots\geq\lambda_p \]

The corresponding eigenvectors are ordered in the same way.

Step 4: Select the Top k Components

Select the first \(k\) eigenvectors to construct the projection matrix.

\[ W_k=[v_1,v_2,\ldots,v_k] \]

Step 5: Project the Original Data

Transform the centered observations into the reduced feature space:

\[ Z=X_{\text{centered}}W_k \]

Where:

  • \(Z\) = Reduced-dimensional representation.
  • \(X_{\text{centered}}\) = Centered original data.
  • \(W_k\) = Selected principal component directions.

The transformed dataset contains \(k\) components instead of the original \(p\) features.

Understanding SVD

In practice, PCA is often implemented using Singular Value Decomposition (SVD).

SVD decomposes a centered data matrix as:

\[ X=U S V^T \]

Where:

  • \(U\) = Left singular vectors.
  • \(S\) = Diagonal matrix of singular values.
  • \(V\) = Right singular vectors.

The columns of \(V\) represent principal component directions.

SVD is numerically useful and avoids explicitly constructing the full covariance matrix in many implementations.


8. Explained Variance Ratio

One of the most important decisions in PCA is determining how many principal components to retain.

The Explained Variance Ratio measures the proportion of total variance captured by each component.

\[ EVR_j= \frac{\lambda_j} {\sum_{i=1}^{p}\lambda_i} \]

Where:

  • \(\lambda_j\) = Eigenvalue of component \(j\).
  • Total variance = Sum of all eigenvalues.

Example: Explained Variance

Suppose PCA produces the following results:

ComponentExplained Variance
PC145%
PC225%
PC315%
PC48%
PC57%

The cumulative explained variance becomes:

ComponentsCumulative Variance
PC145%
PC1 + PC270%
PC1 + PC2 + PC385%
First 4 PCs93%
First 5 PCs100%

If the objective is to preserve at least 90% of the variance, the first four components would be sufficient in this example.

Explained Variance Visualization

<AsyncImage query="PCA explained variance ratio cumulative explained variance scree plot elbow chart machine learning" aspectRatio="16:9" width="100%" />

A scree plot helps identify where additional components contribute relatively little variance.

A common guideline is to retain 90–95% of total variance, but this is not a universal rule.

The appropriate number of components depends on:

  • The purpose of dimensionality reduction.
  • The amount of information needed.
  • Computational constraints.
  • Downstream model performance.
  • Interpretability requirements.

High explained variance does not automatically mean better predictive performance, because PCA does not use target labels.


9. Important Limitations of PCA

PCA is powerful, but it has several limitations.

1. Linear Transformation

PCA captures linear relationships.

It may fail to represent complex nonlinear structures effectively.

Alternatives include:

  • Kernel PCA.
  • UMAP.
  • t-SNE.

These techniques serve different purposes and have their own limitations.

2. Loss of Interpretability

Original features may have understandable meanings, such as income, age, and purchase frequency.

Principal components combine multiple original features.

As a result, interpreting PC1 or PC2 may be more difficult.

3. Sensitivity to Feature Scaling

PCA identifies directions of maximum variance.

Features with larger numerical ranges may dominate the covariance matrix.

Standardization is often appropriate when feature scales differ substantially.

4. Sensitivity to Outliers

Extreme observations can influence the covariance structure and shift principal component directions.

Robust preprocessing or robust PCA approaches may be appropriate for datasets with substantial outlier contamination.

5. Information Loss

Reducing dimensions necessarily discards some information unless all components are retained.

A low-variance feature can still contain useful information for a particular prediction task.

Therefore, component selection should be evaluated according to the intended application.

Advantages of PCA

  • Reduces feature dimensionality.
  • Removes linear correlation between transformed components.
  • Can reduce computational requirements.
  • Helps visualize high-dimensional data.
  • Can reduce noise when discarded components mostly contain noise.
  • Useful as preprocessing for other algorithms.

Limitations of PCA

  • Components can be difficult to interpret.
  • Captures linear rather than arbitrary nonlinear relationships.
  • Sensitive to feature scales and outliers.
  • May discard information useful for downstream prediction.
  • Requires fitting on training data only when used in a supervised learning pipeline.

10. K-Means vs. PCA: Head-to-Head Comparison

Although both are unsupervised learning techniques, their objectives are fundamentally different.

AttributeK-Means ClusteringPrincipal Component Analysis
Primary goalGroup similar observationsReduce feature dimensions
Learning approachClusteringDimensionality reduction
OutputCluster assignments and centroidsContinuous principal component scores
Main mathematical conceptEuclidean distance and centroidsCovariance, eigenvectors, SVD
Data reduction axisGroups observations (rows)Compresses feature representation (columns)
Number of parametersNumber of clusters \(K\)Number of components \(k\)
Feature scalingUsually importantOften important
Target labels requiredNoNo
InterpretabilityCluster profilesComponent loadings
Main limitationAssumptions about cluster shapeLinear transformation and information loss

Key distinction:

  • K-Means answers: Which observations belong together?
  • PCA answers: Which smaller set of directions preserves the most variance?

PCA does not create customer groups, and K-Means does not automatically reduce the number of features.


11. Combining PCA and K-Means in Practice

PCA and K-Means can be combined in a two-stage machine learning pipeline.

This is particularly useful when the original dataset contains many numerical features.

The general workflow is:

High-Dimensional Dataset
       (200 Features)
             |
             v
    [ Feature Preprocessing ]
             |
             v
       [ Standardization ]
             |
             v
      [ PCA Transformation ]
        (200 -> 10 PCs)
             |
             v
       [ K-Means Clustering ]
             |
             v
      [ Cluster Assignments ]
             |
             v
   [ Customer Segment Analysis ]

Why Combine PCA and K-Means?

1. Reduce Dimensionality

PCA can compress the original feature space into fewer dimensions.

2. Reduce Redundant Information

PCA creates orthogonal components, removing linear correlation between transformed components.

3. Improve Computational Efficiency

K-Means performs distance calculations.

Reducing the number of features can lower the computational cost of these calculations.

4. Support Visualization

PCA can project high-dimensional data into two or three dimensions, making it easier to visualize cluster structures.

However, a two-dimensional visualization may not represent all the information available in the original feature space.

Important Consideration

PCA does not guarantee better clustering.

A low-variance component may contain information that separates meaningful clusters. Removing it can reduce clustering quality.

Always compare K-Means performance with and without PCA using suitable validation measures and domain knowledge.


12. Python Implementation: K-Means Clustering

Let's implement K-Means using Scikit-learn.

We will generate a synthetic dataset containing three natural clusters.

Step 1: Install Required Libraries

pip install numpy pandas matplotlib scikit-learn

Step 2: Import Libraries and Generate Data

import matplotlib.pyplot as plt

from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans

# Generate synthetic data
X, y = make_blobs(
    n_samples=300,
    centers=3,
    n_features=2,
    cluster_std=1.0,
    random_state=42
)

# Visualize original data
plt.scatter(X[:, 0], X[:, 1])

plt.title("Original Unlabeled Dataset")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.show()

The variable y contains the generated ground-truth cluster labels for illustration. We will not use these labels when fitting K-Means.

Step 3: Train K-Means

kmeans = KMeans(
    n_clusters=3,
    init="k-means++",
    n_init=10,
    random_state=42
)

# Train the model without labels
kmeans.fit(X)

# Get cluster assignments
labels = kmeans.labels_

# Get centroids
centroids = kmeans.cluster_centers_

print("Cluster Assignments:")
print(labels)

print("Centroids:")
print(centroids)

Step 4: Visualize Clusters

plt.scatter(
    X[:, 0],
    X[:, 1],
    c=labels,
    cmap="viridis"
)

plt.scatter(
    centroids[:, 0],
    centroids[:, 1],
    color="red",
    marker="X",
    s=200,
    label="Centroids"
)

plt.title("K-Means Clustering")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.legend()
plt.show()

The visualization displays the observations grouped into three clusters, along with their centroids.

Step 5: Evaluate Clustering

from sklearn.metrics import silhouette_score

print("Inertia:", kmeans.inertia_)

score = silhouette_score(X, labels)

print("Silhouette Score:", score)

A higher Silhouette Score generally indicates better separation and cohesion, but the score should be interpreted alongside the dataset's structure and intended use.


13. Python Implementation: Elbow Method

The Elbow Method helps compare different values of \(K\).

import matplotlib.pyplot as plt

from sklearn.cluster import KMeans

wcss = []

for k in range(1, 11):

    model = KMeans(
        n_clusters=k,
        init="k-means++",
        n_init=10,
        random_state=42
    )

    model.fit(X)

    wcss.append(model.inertia_)

plt.plot(
    range(1, 11),
    wcss,
    marker="o"
)

plt.title("Elbow Method")
plt.xlabel("Number of Clusters (K)")
plt.ylabel("WCSS / Inertia")
plt.xticks(range(1, 11))
plt.show()

Observe where the WCSS reduction starts slowing down.

That point can be used as a candidate number of clusters.


14. Python Implementation: Principal Component Analysis

Now let's use PCA to reduce the dimensionality of a dataset.

We will use the Wine dataset, which contains 13 numerical features.

Step 1: Import and Load the Dataset

import pandas as pd

from sklearn.datasets import load_wine
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

# Load dataset
data = load_wine()

X = pd.DataFrame(
    data.data,
    columns=data.feature_names
)

y = data.target

print("Original Shape:", X.shape)

The dataset initially contains 13 features.

Step 2: Standardize the Features

scaler = StandardScaler()

X_scaled = scaler.fit_transform(X)

Standardization prevents features with large numerical magnitudes from dominating PCA.

Step 3: Apply PCA

pca = PCA(n_components=2)

X_pca = pca.fit_transform(X_scaled)

print("Reduced Shape:", X_pca.shape)

print("Explained Variance Ratio:")
print(pca.explained_variance_ratio_)

print(
    "Total Explained Variance:",
    pca.explained_variance_ratio_.sum()
)

The original 13 features are now represented using two principal components.

Step 4: Visualize PCA Results

import matplotlib.pyplot as plt

plt.scatter(
    X_pca[:, 0],
    X_pca[:, 1],
    c=y,
    cmap="viridis"
)

plt.title("PCA: Wine Dataset")
plt.xlabel("Principal Component 1")
plt.ylabel("Principal Component 2")
plt.colorbar(label="Original Class")
plt.show()

The original labels are used only for coloring the visualization. PCA itself does not use them during fitting.


15. Python Implementation: Combining PCA and K-Means

Let's combine both techniques using the Wine dataset.

The workflow is:

  1. Standardize the features.
  2. Reduce the dimensions using PCA.
  3. Apply K-Means to the reduced representation.
  4. Visualize the cluster assignments.
from sklearn.datasets import load_wine

from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans

from sklearn.pipeline import Pipeline
from sklearn.metrics import silhouette_score

import matplotlib.pyplot as plt

# Load data
data = load_wine()
X = data.data

# Create pipeline
pipeline = Pipeline([
    ("scaler", StandardScaler()),

    ("pca", PCA(
        n_components=2
    )),

    ("kmeans", KMeans(
        n_clusters=3,
        init="k-means++",
        n_init=10,
        random_state=42
    ))
])

# Fit pipeline
pipeline.fit(X)

# Extract transformed data
X_scaled = pipeline.named_steps["scaler"].transform(X)

X_pca = pipeline.named_steps["pca"].transform(X_scaled)

# Get cluster assignments
labels = pipeline.named_steps["kmeans"].labels_

# Evaluate
score = silhouette_score(X_pca, labels)

print("Silhouette Score:", score)

# Visualize
plt.scatter(
    X_pca[:, 0],
    X_pca[:, 1],
    c=labels,
    cmap="viridis"
)

plt.title("PCA + K-Means Clustering")
plt.xlabel("Principal Component 1")
plt.ylabel("Principal Component 2")
plt.show()

This example uses two principal components for easy visualization.

For a real application, two components may not preserve enough information. Compare different component counts and evaluate clustering quality in the representation used for the actual clustering task.

Also, the Wine dataset has original class labels, but this example does not use them for training. They can be used separately for external evaluation, such as Adjusted Rand Index, if desired.


16. Real-World Applications

K-Means and PCA are used across multiple industries.

IndustryK-Means ApplicationPCA Application
E-commerceCustomer segmentationCompressing product and customer features
BankingCustomer behavior groupingReducing correlated financial indicators
HealthcarePatient groupingReducing medical measurement dimensions
MarketingCampaign audience segmentationAnalyzing high-dimensional campaign data
ManufacturingMachine operating-state clusteringSensor-data compression
CybersecurityNetwork behavior groupingReducing traffic feature dimensions
RetailStore and product segmentationCompressing purchasing behavior data
Computer VisionImage groupingFeature compression

Example: Customer Segmentation

An e-commerce company can use K-Means to group customers based on:

  • Annual income.
  • Purchase frequency.
  • Average order value.
  • Website engagement.
  • Discount usage.

PCA can first reduce the number of correlated customer features.

K-Means can then identify customer segments in the reduced feature space.

The business can use the resulting groups to develop targeted campaigns, personalized recommendations, and retention strategies.


17. Common Mistakes to Avoid

1. Choosing K Arbitrarily

Do not select the number of clusters without evaluating the resulting grouping.

Use the Elbow Method, Silhouette Analysis, and domain knowledge.

2. Ignoring Feature Scaling

Features with large numerical ranges can dominate Euclidean distance and PCA variance.

Use suitable scaling where appropriate.

3. Assuming Every Dataset Contains Spherical Clusters

K-Means may perform poorly on irregularly shaped or strongly overlapping clusters.

Consider DBSCAN, Gaussian Mixture Models, or hierarchical clustering when appropriate.

4. Keeping Too Few PCA Components

Aggressive dimensionality reduction may remove useful information.

Evaluate cumulative explained variance and downstream task performance.

5. Assuming PCA Always Improves Model Performance

PCA can reduce computational requirements, but it may also remove information that a downstream model needs.

Compare results with and without PCA.

6. Using PCA Before the Train-Test Split

In supervised machine learning workflows, fitting PCA on the entire dataset before splitting can leak information from the test distribution into training.

Fit scaling and PCA inside a training pipeline, then transform validation and test data using the fitted transformations.

7. Treating Cluster Numbers as Meaningful Categories

Cluster labels such as 0, 1, and 2 are arbitrary identifiers.

Cluster 2 is not inherently better or more important than cluster 0.

Interpret clusters using their feature profiles and domain context.


18. Conclusion

K-Means Clustering and Principal Component Analysis are two foundational techniques in unsupervised machine learning.

K-Means discovers groups of similar observations by repeatedly assigning data points to nearby centroids and updating those centroids. It is widely used for customer segmentation, exploratory analysis, and grouping numerical datasets.

PCA reduces dimensionality by transforming correlated features into orthogonal principal components that preserve as much variance as possible. It is useful for data compression, visualization, and preprocessing.

Although they solve different problems, they can work together effectively:

  • PCA reduces the number of dimensions.
  • K-Means groups observations within the resulting feature space.
  • Together, they can support exploratory analysis and customer segmentation.

However, neither technique guarantees meaningful results on every dataset. Feature scaling, outliers, cluster geometry, component selection, and validation all influence performance.

The key takeaway: K-Means helps discover hidden groups in data, while PCA helps discover the most informative directions in the feature space.

Understanding both techniques provides an essential foundation for more advanced unsupervised learning methods and real-world data science applications.


Further Learning

Explore these related topics to strengthen your understanding of machine learning:

  • Supervised vs. Unsupervised vs. Reinforcement Learning.
  • Feature Scaling: Standardization vs. Normalization.
  • Decision Trees: Gini, Entropy, and Information Gain.
  • k-NN, SVMs, and Naive Bayes: Three Classical ML Pillars.
  • Random Forest vs. Gradient Boosting: XGBoost and LightGBM.
  • Dimensionality Reduction: PCA vs. t-SNE vs. UMAP.
  • DBSCAN Clustering and Hierarchical Clustering.
  • Bias-Variance Tradeoff in Machine Learning.