By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
(Python for Data Science – Production-Ready)
Unsupervised learning is like being handed a box of unlabeled Legos and told to "find patterns." You don’t know what the final structure should look like, but you can group similar pieces together (clustering) or simplify the pile by removing redundant parts (dimensionality reduction).
K-Means Clustering groups data into k clusters based on similarity (e.g., customer segments, anomaly detection).PCA (Principal Component Analysis) reduces data dimensions while preserving variance (e.g., speeding up models, visualizing high-dimensional data).
Real-World Scenario:You’re a data scientist at an e-commerce company. Your boss asks: "We have 1M users with 500 behavioral features. Can you group them into 5 segments for targeted ads—without any labels?" → K-Means clusters users.→ PCA reduces 500 features to 20 for faster clustering.
Ignore this, and you’ll either: - Waste compute resources training on noisy data.- Miss key customer segments (lost revenue).- Deploy a model that’s too slow for real-time predictions.
StandardScaler
n_clusters
init
'k-means++'
max_iter
n_components
0.95
whiten
[0.72, 0.18, 0.05]
init='k-means++'
scikit-learn
pandas
matplotlib
seaborn
pip install scikit-learn pandas matplotlib seaborn
Goal: Segment customers into 3 groups using K-Means, then reduce features with PCA for visualization.
import pandas as pd from sklearn.datasets import load_iris # Load data data = load_iris() df = pd.DataFrame(data.data, columns=data.feature_names) df["target"] = data.target # We'll ignore this for unsupervised learning print(df.head()) print("\nShape:", df.shape)
Output:
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target 0 5.1 3.5 1.4 0.2 0 1 4.9 3.0 1.4 0.2 0 2 4.7 3.2 1.3 0.2 0 3 4.6 3.1 1.5 0.2 0 4 5.0 3.6 1.4 0.2 0 Shape: (150, 5)
from sklearn.preprocessing import StandardScaler # Drop target (unsupervised) X = df.drop("target", axis=1) # Scale data scaler = StandardScaler() X_scaled = scaler.fit_transform(X)
from sklearn.cluster import KMeans import matplotlib.pyplot as plt # Calculate inertia for k=1 to 10 inertia = [] for k in range(1, 11): kmeans = KMeans(n_clusters=k, random_state=42) kmeans.fit(X_scaled) inertia.append(kmeans.inertia_) # Plot plt.plot(range(1, 11), inertia, marker="o") plt.xlabel("Number of clusters (k)") plt.ylabel("Inertia") plt.title("Elbow Method") plt.show()
Output: Pick k=3 (elbow point).
kmeans = KMeans(n_clusters=3, random_state=42) clusters = kmeans.fit_predict(X_scaled) # Add clusters to DataFrame df["cluster"] = clusters print(df.head())
sepal length (cm) ... target cluster 0 5.1 ... 0 0 1 4.9 ... 0 0 2 4.7 ... 0 0 3 4.6 ... 0 0 4 5.0 ... 0 1
from sklearn.metrics import silhouette_score score = silhouette_score(X_scaled, clusters) print(f"Silhouette Score: {score:.2f}") # Aim for > 0.5
Silhouette Score: 0.46
Not great, but acceptable for this dataset. Try different k or feature engineering.
from sklearn.decomposition import PCA # Fit PCA pca = PCA(n_components=2) X_pca = pca.fit_transform(X_scaled) # Explained variance print("Explained variance ratio:", pca.explained_variance_ratio_)
Explained variance ratio: [0.72962445 0.22850762]
First 2 components explain 95.8% of variance!
import seaborn as sns # Create DataFrame with PCA results pca_df = pd.DataFrame(X_pca, columns=["PC1", "PC2"]) pca_df["cluster"] = clusters # Plot sns.scatterplot(data=pca_df, x="PC1", y="PC2", hue="cluster", palette="viridis") plt.title("K-Means Clusters (PCA-Reduced)") plt.show()
Output: Clusters are well-separated in 2D!
k=10
k=100
random_state
random_state=42
python from sklearn.pipeline import Pipeline pipeline = Pipeline([ ("scaler", StandardScaler()), ("pca", PCA(n_components=0.95)), ("kmeans", KMeans(n_clusters=3)) ]) pipeline.fit(X)
MinMaxScaler
k-means++
SelectKBest
"You’re clustering 10,000 customers with 200 features. The model is slow. What’s the first step to optimize?" → Answer: Use PCA to reduce dimensions (e.g., keep 95% variance).
Challenge:You have a dataset of 1000 products with 50 features (e.g., price, weight, ratings). Cluster them into 4 groups using K-Means, then reduce to 2D with PCA for visualization. Bonus: Calculate the silhouette score.
Solution:
import numpy as np from sklearn.datasets import make_blobs # Generate synthetic data (1000 samples, 50 features, 4 clusters) X, _ = make_blobs(n_samples=1000, n_features=50, centers=4, random_state=42) # Scale data X_scaled = StandardScaler().fit_transform(X) # K-Means kmeans = KMeans(n_clusters=4, random_state=42) clusters = kmeans.fit_predict(X_scaled) # PCA pca = PCA(n_components=2) X_pca = pca.fit_transform(X_scaled) # Silhouette score score = silhouette_score(X_scaled, clusters) print(f"Silhouette Score: {score:.2f}") # Should be ~0.6-0.8
Why It Works:- make_blobs generates synthetic clusters.- Scaling ensures features contribute equally.- PCA reduces to 2D for visualization while preserving structure.
make_blobs
KMeans(n_clusters=3, init='k-means++', random_state=42)
silhouette_score(X, clusters)
PCA(n_components=0.95)
pca.explained_variance_ratio_
StandardScaler()
MinMaxScaler()
sns.scatterplot(x="PC1", y="PC2", hue="cluster")
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.