ML Notes
Comprehensive guide to unsupervised learning including clustering, dimensionality reduction, anomaly detection, and association rules with Python examples.
Unsupervised learning is the art of finding hidden patterns in data without any labels or guidance. The algorithm must discover structure on its own — like organizing a messy closet without anyone telling you the categories.
Core Concept
Types of Unsupervised Learning
Clustering: Grouping Similar Data
from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering
from sklearn.datasets import make_blobs, make_moons
from sklearn.metrics import silhouette_score
import numpy as np
# Create sample data
X_blobs, _ = make_blobs(n_samples=300, centers=4, random_state=42)
# K-Means Clustering
kmeans = KMeans(n_clusters=4, random_state=42, n_init=10)
kmeans_labels = kmeans.fit_predict(X_blobs)
kmeans_score = silhouette_score(X_blobs, kmeans_labels)
# DBSCAN Clustering
dbscan = DBSCAN(eps=0.8, min_samples=5)
dbscan_labels = dbscan.fit_predict(X_blobs)
dbscan_score = silhouette_score(X_blobs, dbscan_labels)
# Hierarchical Clustering
hier = AgglomerativeClustering(n_clusters=4)
hier_labels = hier.fit_predict(X_blobs)
hier_score = silhouette_score(X_blobs, hier_labels)
print("Clustering Comparison (Silhouette Score - higher is better):")
print(f" K-Means: {kmeans_score:.4f}")
print(f" DBSCAN: {dbscan_score:.4f}")
print(f" Hierarchical: {hier_score:.4f}")Dimensionality Reduction
from sklearn.decomposition import PCA
from sklearn.datasets import load_digits
import numpy as np
# Load high-dimensional data (64 features)
digits = load_digits()
X = digits.data
print(f"Original shape: {X.shape}") # (1797, 64)
# Reduce to 2D for visualization
pca = PCA(n_components=2)
X_2d = pca.fit_transform(X)
print(f"Reduced shape: {X_2d.shape}") # (1797, 2)
print(f"Variance explained: {pca.explained_variance_ratio_.sum():.2%}")
# Find optimal number of components
pca_full = PCA().fit(X)
cumulative_variance = np.cumsum(pca_full.explained_variance_ratio_)
n_components_95 = np.argmax(cumulative_variance >= 0.95) + 1
print(f"Components needed for 95% variance: {n_components_95}")Anomaly Detection
Real-World Applications
| Application | Technique | Business Value |
|---|---|---|
| Customer segmentation | K-Means, GMM | Targeted marketing campaigns |
| Fraud detection | Isolation Forest | Catch unusual transactions |
| Document organization | Topic modeling | Auto-categorize content |
| Image compression | PCA, Autoencoders | Reduce storage costs |
| Social network analysis | Community detection | Identify user groups |
| Market basket analysis | Apriori | Cross-selling recommendations |
Customer Segmentation Example
Evaluating Unsupervised Models
Unlike supervised learning, there's no "correct answer" to compare against:
Interview Questions
- How do you evaluate unsupervised learning models without labels?
Use internal metrics like silhouette score, elbow method for clustering, or reconstruction error for dimensionality reduction. Also validate with domain experts and business logic.
- When would you choose DBSCAN over K-Means?
When clusters have irregular shapes, when you don't know the number of clusters in advance, or when you need to identify noise points (outliers).
- What is the difference between PCA and t-SNE?
PCA is linear, preserves global structure, fast, and invertible. t-SNE is non-linear, preserves local structure, slower, and mainly used for visualization (not feature reduction).
- How do you determine the right number of clusters?
Use the elbow method (inertia plot), silhouette analysis, gap statistic, or domain knowledge. There's often no single "right" answer.
- Can unsupervised learning be used as a preprocessing step for supervised learning?
Yes! Clustering can create new features, PCA can reduce dimensionality before classification, and anomaly detection can clean data before training.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Unsupervised Learning.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Machine Learning topic.
Search Terms
machine-learning, machine learning, machine, learning, fundamentals, unsupervised, unsupervised learning
Related Machine Learning Topics