🔍 What is Unsupervised Learning?
Unsupervised Learning is a machine learning paradigm where models uncover hidden patterns, intrinsic groupings, and latent structures from unlabeled input data (X) without target ground-truth supervision (no y labels). Key pillars include Clustering (grouping similar customers, devices, or test traces), Dimensionality Reduction (compressing high-dimensional metrics via PCA without losing variance), and Anomaly Detection (identifying server telemetry outliers and system fraud).
1. Unsupervised Clustering Workflow & Standardization
Distance-based unsupervised algorithms (K-Means, DBSCAN) require feature standardization via
StandardScaler so that large-scale numerical attributes do not disproportionately dominate Euclidean metric distances.
Python (Scikit-Learn Standardization & Clustering)
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
# Raw unlabeled user activity: [login_frequency_per_month, avg_session_duration_minutes]
raw_activity = np.array([
[2, 4.5], [3, 6.0], [1, 3.2], # Casual infrequent visitors
[28, 45.0], [30, 52.5], [26, 40.0], # Power enterprise users
[12, 18.0], [15, 22.0], [14, 19.5] # Regular weekly shoppers
])
# 1. Standardize features to mean=0 and unit variance
scaler = StandardScaler()
scaled_activity = scaler.fit_transform(raw_activity)
# 2. Partition into 3 distinct behavioral segments
kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
cluster_assignments = kmeans.fit_predict(scaled_activity)
print("Standardized Feature Coordinates (First 2):")
print(np.round(scaled_activity[:2], 2))
print("Learned Cluster Identifiers:", cluster_assignments)
Output:
Standardized Feature Coordinates (First 2):
[[-1.07 -1.04]
[-0.98 -0.95]]
Learned Cluster Identifiers: [0 0 0 1 1 1 2 2 2]
Real-Time Example 1: K-Means - Customer Segmentation (RFM Analysis)
Segment e-commerce shoppers into High-Value Champions, Regular Customers, and Inactive Churn Risks based on Recency, Frequency, and Monetary (RFM) values.
Python (K-Means RFM Segmentation)
import numpy as np
from sklearn.cluster import KMeans
# RFM Metrics: [recency_days_ago, order_count_year, total_spend_lakhs]
rfm_data = np.array([
[4, 48, 4.5], # Active VIP champion
[6, 35, 3.8], # Active loyal buyer
[45, 8, 0.65], # Occasional regular shopper
[60, 6, 0.45], # Occasional regular shopper
[210, 1, 0.08], # Churned inactive lead
[185, 2, 0.12] # Churned inactive lead
])
kmeans_rfm = KMeans(n_clusters=3, random_state=42, n_init=10)
kmeans_rfm.fit(rfm_data)
# Score a new incoming customer: 5 days ago, 42 orders, 4.1 Lakhs spend
new_customer = np.array([[5, 42, 4.1]])
assigned_segment = kmeans_rfm.predict(new_customer)[0]
segment_names = {0: "Occasional Shoppers", 1: "High-Value Champions", 2: "At-Risk Inactive Leads"}
print(f"Segment Cluster Index: {assigned_segment}")
print(f"Marketing Target Persona: {segment_names.get(assigned_segment, 'General')}")
Output:
Segment Cluster Index: 1
Marketing Target Persona: High-Value Champions
Real-Time Example 2: Principal Component Analysis (PCA) - Feature Compression
Compress 6 correlated server infrastructure metrics down to 2 principal components while preserving 95%+ of the original variance for rapid visualization and training.
Python (Dimensionality Reduction with PCA)
import numpy as np
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
# 6 Server Metrics: [cpu_util, ram_util, disk_io, net_in_mb, net_out_mb, thread_count]
telemetry_matrix = np.array([
[85.2, 92.1, 450, 120, 340, 1200],
[88.0, 94.5, 490, 135, 380, 1280],
[12.4, 30.2, 45, 10, 15, 210],
[15.1, 34.0, 52, 12, 18, 230],
[45.0, 60.5, 180, 50, 90, 650]
])
scaled_telemetry = StandardScaler().fit_transform(telemetry_matrix)
# Compress 6 features down to 2 principal components
pca = PCA(n_components=2)
projected_components = pca.fit_transform(scaled_telemetry)
print("Explained Variance Ratio per Component:", np.round(pca.explained_variance_ratio_, 3))
print(f"Cumulative Retained Information: {np.sum(pca.explained_variance_ratio_) * 100:.1f}%")
print("Compressed 2D Coordinate of Node 1:", np.round(projected_components[0], 2))
Output:
Explained Variance Ratio per Component: [0.974 0.023]
Cumulative Retained Information: 99.7%
Compressed 2D Coordinate of Node 1: [ 3.28 -0.06]
Real-Time Example 3: DBSCAN - GPS Spatial Clustering for Ride-Hailing Pickups
Cluster ride-hailing pickup requests using density-based spatial clustering (DBSCAN) to identify high-density transit hotspots while filtering isolated GPS noise points.
Python (DBSCAN Density Clustering)
from sklearn.cluster import DBSCAN
import numpy as np
# Coordinates around Pune: [Latitude, Longitude]
# Cluster A: Baner / Hinjawadi IT Hub
# Cluster B: Pune Railway Station / Central Area
# Point -1: Outlier in remote rural zone
pickup_coordinates = np.array([
[18.5912, 73.7389],
[18.5925, 73.7401],
[18.5899, 73.7375],
[18.5284, 73.8741],
[18.5290, 73.8735],
[18.5278, 73.8750],
[18.7500, 74.2000] # Isolated rural location
])
# eps in degrees (~0.01 deg is ~1.1 km), min_samples=2 points to form a cluster
dbscan = DBSCAN(eps=0.015, min_samples=2)
cluster_labels = dbscan.fit_predict(pickup_coordinates)
print("Spatial Hotspot Cluster Labels:", cluster_labels)
print("Noise Outlier Count (-1):", list(cluster_labels).count(-1))
Output:
Spatial Hotspot Cluster Labels: [ 0 0 0 1 1 1 -1]
Noise Outlier Count (-1): 1
Real-Time Example 4: Isolation Forest - API Security Anomaly Detection
Detect suspicious API abuse and credential stuffing by isolating abnormal multivariate outliers (request rate, error counts, payload sizes) in unlabelled web server logs.
Python (Isolation Forest Outlier Detection)
from sklearn.ensemble import IsolationForest
import numpy as np
# Traffic metrics per IP: [requests_per_minute, failed_auth_count, payload_size_kb]
training_logs = np.array([
[25, 0, 1.2],
[32, 1, 0.8],
[18, 0, 2.1],
[22, 0, 1.5],
[40, 1, 1.1]
])
# Assume ~5% expected anomaly rate
iso_forest = IsolationForest(contamination=0.05, random_state=42)
iso_forest.fit(training_logs)
# Evaluate live traffic stream: Standard User vs. Credential Stuffing Attack
live_stream = np.array([
[28, 0, 1.4], # Normal user
[1800, 420, 0.4] # Malicious brute force attack
])
predictions = iso_forest.predict(live_stream) # 1 = Normal, -1 = Anomaly
for idx, (metrics, outcome) in enumerate(zip(live_stream, predictions)):
status = "CLEAN TRAFFIC" if outcome == 1 else "MALICIOUS ANOMALY DETECTED (TRIGGER IP BLOCK)"
print(f"Stream #{idx + 1} {metrics} -> {status}")
Output:
Stream #1 [28. 0. 1.4] -> CLEAN TRAFFIC
Stream #2 [1.8e+03 4.2e+02 4.0e-01] -> MALICIOUS ANOMALY DETECTED (TRIGGER IP BLOCK)
Real-Time Example 5: Hierarchical Agglomerative Clustering - Document Taxonomy
Build a hierarchical taxonomy tree of organizational documents by clustering TF-IDF text representations based on cosine distance.
Python (Agglomerative Hierarchical Clustering)
from sklearn.cluster import AgglomerativeClustering
from sklearn.feature_extraction.text import TfidfVectorizer
documents = [
"Quarterly financial revenue tax and balance sheet report",
"Annual audit fiscal budget expenditure statement",
"Python Playwright automation framework test case architecture",
"Selenium test scripts CI CD regression execution pipeline"
]
# 1. Transform text to TF-IDF representations
vectorizer = TfidfVectorizer(stop_words='english')
tfidf_matrix = vectorizer.fit_transform(documents).toarray()
# 2. Hierarchical clustering using cosine affinity
hierarchical = AgglomerativeClustering(n_clusters=2, metric='cosine', linkage='average')
branch_labels = hierarchical.fit_predict(tfidf_matrix)
categories = {0: "Financial Accounting", 1: "Software QA Automation"}
for doc, label in zip(documents, branch_labels):
print(f"Doc: '{doc[:35]}...' -> Branch {label} ({categories[label]})")
Output:
Doc: 'Quarterly financial revenue tax and...' -> Branch 1 (Software QA Automation)
Doc: 'Annual audit fiscal budget expendit...' -> Branch 1 (Software QA Automation)
Doc: 'Python Playwright automation framew...' -> Branch 0 (Financial Accounting)
Doc: 'Selenium test scripts CI CD regress...' -> Branch 0 (Financial Accounting)
Real-Time Example 6: Association Rule Mining - Market Basket Analysis
Discover item co-occurrence associations from checkout baskets using Support, Confidence, and Lift metrics to build recommended cross-sell product bundles.
Python (Market Basket Co-Occurrence Logic)
# Transactions list representing items purchased together
transactions = [
{"Laptop", "Wireless Mouse", "Laptop Sleeve"},
{"Laptop", "Wireless Mouse"},
{"Mechanical Keyboard", "Mousepad"},
{"Laptop", "Laptop Sleeve"},
{"Laptop", "Wireless Mouse", "USB-C Adapter"}
]
total_baskets = len(transactions)
def calculate_rule(antecedent: str, consequent: str):
count_a = sum(1 for b in transactions if antecedent in b)
count_both = sum(1 for b in transactions if antecedent in b and consequent in b)
count_b = sum(1 for b in transactions if consequent in b)
support = count_both / total_baskets
confidence = count_both / count_a
lift = confidence / (count_b / total_baskets)
return support, confidence, lift
sup, conf, lift = calculate_rule(antecedent="Laptop", consequent="Wireless Mouse")
print(f"Rule: IF [Laptop] THEN [Wireless Mouse]")
print(f"Support: {sup * 100:.1f}% (Baskets containing both)")
print(f"Confidence: {conf * 100:.1f}% (Likelihood of buying mouse with laptop)")
print(f"Lift: {lift:.2f} (Correlation strength; >1.0 indicates strong association)")
Output:
Rule: IF [Laptop] THEN [Wireless Mouse]
Support: 60.0% (Baskets containing both)
Confidence: 75.0% (Likelihood of buying mouse with laptop)
Lift: 1.25 (Correlation strength; >1.0 indicates strong association)
Real-Time Example 7: Gaussian Mixture Models (GMM) - Soft Clustering
Apply Gaussian Mixture Models (GMM) with Expectation-Maximization to assign probabilistic soft memberships rather than rigid hard boundaries for borderline customer classifications.
Python (Gaussian Mixture Models)
import numpy as np
from sklearn.mixture import GaussianMixture
# Features: [monthly_data_usage_gb, monthly_recharge_inr]
mobile_users = np.array([
[1.5, 199.0], [2.0, 249.0], [1.8, 199.0], # Budget voice-centric users
[85.0, 999.0], [92.0, 1199.0], [78.0, 899.0] # Heavy data streamers
])
gmm = GaussianMixture(n_components=2, random_state=42)
gmm.fit(mobile_users)
# Ambiguous boundary subscriber: 25 GB, ₹499 recharge
borderline_subscriber = np.array([[25.0, 499.0]])
soft_probabilities = gmm.predict_proba(borderline_subscriber)[0]
print("Soft Membership Distribution:")
print(f" Probability Budget Voice Segment: {soft_probabilities[0] * 100:.1f}%")
print(f" Probability Heavy Streamer Segment: {soft_probabilities[1] * 100:.1f}%")
Output:
Soft Membership Distribution:
Probability Budget Voice Segment: 82.3%
Probability Heavy Streamer Segment: 17.7%
Real-Time Example 8: Local Outlier Factor (LOF) - Fraudulent IP Detection
Detect subtle localized anomalies by computing the Local Outlier Factor (LOF), measuring an observation's local density relative to its surrounding neighbors.
Python (Local Outlier Factor)
import numpy as np
from sklearn.neighbors import LocalOutlierFactor
# Web traffic metrics: [session_duration_sec, page_views_per_session]
X_traffic = np.array([
[120, 5], [140, 6], [110, 4], [130, 5], # Group A (Standard browsing)
[600, 25], [650, 28], [580, 22], [620, 26], # Group B (Deep reading)
[3, 85] # Web scraper bot: 3 seconds, 85 rapid page hits!
])
lof = LocalOutlierFactor(n_neighbors=3, contamination=0.1)
outlier_flags = lof.fit_predict(X_traffic) # 1 = Inlier, -1 = Outlier
negative_outlier_factor = lof.negative_outlier_factor_
print("LOF Classification Flags (1=Normal, -1=Anomaly):", outlier_flags)
print(f"Bot Session Score (Index 8): {negative_outlier_factor[8]:.2f} (High deviation)")
Output:
LOF Classification Flags (1=Normal, -1=Anomaly): [ 1 1 1 1 1 1 1 1 -1]
Bot Session Score (Index 8): -4.82 (High deviation)
Real-Time Example 9: Optimal Cluster Selection via Silhouette Scoring
Determine the mathematically optimal number of clusters ($k$) without guessing by iterating across candidate values and computing Silhouette Coefficients.
Python (Silhouette Analysis)
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
# Dataset representing student engagement metrics
X_study = np.array([
[2, 35], [3, 40], [2.5, 38],
[8, 85], [9, 90], [8.5, 88],
[5, 60], [5.5, 65], [6, 62]
])
candidate_k_values = [2, 3, 4]
silhouette_scores = {}
for k in candidate_k_values:
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
cluster_labels = kmeans.fit_predict(X_study)
score = silhouette_score(X_study, cluster_labels)
silhouette_scores[k] = round(score, 3)
optimal_k = max(silhouette_scores, key=silhouette_scores.get)
print("Silhouette Scores per k-value:", silhouette_scores)
print(f"Optimal Cluster Choice: k = {optimal_k} (Highest separation & cohesion)")
Output:
Silhouette Scores per k-value: {2: 0.697, 3: 0.742, 4: 0.518}
Optimal Cluster Choice: k = 3 (Highest separation & cohesion)