Unsupervised learning is used when we have features () but no target (). The goal is to find inherent patterns or structures within the data.
1. Clustering: Grouping Similar Samples
Clustering algorithms attempt to partition the data into groups (clusters) where samples in the same group are more similar to each other than to those in other groups.
K-Means Clustering
The most popular clustering algorithm. it partitions data into clusters by minimizing the distance between points and their cluster centroids.
Interactive Lab
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
# Create 3 distinct blobs of data
X, _ = make_blobs(n_samples=300, centers=3, cluster_std=0.60, random_state=0)
# Instantiate and fit
kmeans = KMeans(n_clusters=3)
kmeans.fit(X)
# Predicted labels
y_kmeans = kmeans.predict(X)
print(f"Centroids:\n{kmeans.cluster_centers_}")
High-dimensional data (hundreds or thousands of features) is difficult to visualize and can lead to the “curse of dimensionality.” Dimensionality reduction seeks to represent data in a lower-dimensional space while preserving as much information as possible.
Principal Component Analysis (PCA)
PCA finds the “principal components”—the orthogonal axes along which the data varies the most.
Interactive Lab
from sklearn.decomposition import PCA
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data # 4 features
# Reduce from 4D to 2D
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X)
print(f"Original shape: {X.shape}")
print(f"Reduced shape: {X_reduced.shape}")
print(f"Explained variance ratio: {pca.explained_variance_ratio_}")