Unsupervised Learning
Unsupervised Learning
A machine learning technique that learns hidden patterns and structure in data without labels. Used for clustering, dimensionality reduction, and anomaly detection.
Unsupervised Learning
A machine learning technique that learns hidden patterns and structure in data without labels. Used for clustering, dimensionality reduction, and anomaly detection.
Unsupervised Learning is a machine learning technique that automatically discovers hidden patterns, structures, and relationships in data without answer labels. Whereas Supervised Learning learns from being given explicit answers such as "this image is a cat," unsupervised learning is given only the data and finds structures on its own, such as "these data points share similar characteristics." It is especially useful for real-world industrial data where labeling is costly or impossible.
The main types of unsupervised learning include Clustering, Dimensionality Reduction, Density Estimation, and Anomaly Detection. Clustering groups similar data using algorithms such as K-Means, DBSCAN, and hierarchical clustering. Dimensionality reduction compresses high-dimensional data into lower dimensions while preserving key information, using methods such as PCA, t-SNE, and UMAP. Anomaly detection identifies data that deviates from normal patterns.
In practice, unsupervised learning is applied in a variety of fields, including customer segmentation, item grouping in recommendation systems, genomic data analysis, fraud detection, and network intrusion detection. For example, an e-commerce company automatically classifies customers based on purchase patterns to build customized marketing strategies. Financial institutions detect abnormal patterns in transaction data to prevent fraud.
The development of unsupervised learning led to Self-Supervised Learning and Contrastive Learning. The pre-training of large language models such as BERT and GPT also falls under unsupervised learning in a broad sense, because they learn the structure and meaning of language from large-scale text without labels. In a reality where data is plentiful but labels are scarce, unsupervised learning is one of the core learning paradigms of AI systems.
An example of unsupervised learning using K-Means clustering and PCA:
# λΉμ§λ νμ΅: ν΄λ¬μ€ν°λ§κ³Ό μ°¨μ μΆμ μμ
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs, load_iris
from sklearn.cluster import KMeans, DBSCAN
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.metrics import silhouette_score
from sklearn.manifold import TSNE
# ========================
# 1. K-Means ν΄λ¬μ€ν°λ§
# ========================
print("=== K-Means Clustering ===")
# μν λ°μ΄ν° μμ± (λ μ΄λΈ μμ΄ μ¬μ©)
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=42)
# μ€μΌμΌλ§
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# μ΅μ μ k μ°ΎκΈ° (Elbow Method)
inertias = []
silhouettes = []
k_range = range(2, 10)
for k in k_range:
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
kmeans.fit(X_scaled)
inertias.append(kmeans.inertia_)
silhouettes.append(silhouette_score(X_scaled, kmeans.labels_))
# μ΅μ μ k μ ν (Silhouette κΈ°μ€)
optimal_k = k_range[np.argmax(silhouettes)]
print(f"Optimal k (by silhouette): {optimal_k}")
print(f"Best silhouette score: {max(silhouettes):.3f}")
# μ΅μ kλ‘ ν΄λ¬μ€ν°λ§ μν
kmeans_final = KMeans(n_clusters=optimal_k, random_state=42, n_init=10)
clusters = kmeans_final.fit_predict(X_scaled)
print(f"Cluster sizes: {np.bincount(clusters)}")
# ========================
# 2. DBSCAN ν΄λ¬μ€ν°λ§
# ========================
print("\n=== DBSCAN Clustering ===")
# DBSCANμ ν΄λ¬μ€ν° μλ₯Ό μλμΌλ‘ κ²°μ
dbscan = DBSCAN(eps=0.5, min_samples=5)
dbscan_clusters = dbscan.fit_predict(X_scaled)
n_clusters_dbscan = len(set(dbscan_clusters)) - (1 if -1 in dbscan_clusters else 0)
n_noise = list(dbscan_clusters).count(-1)
print(f"DBSCAN clusters found: {n_clusters_dbscan}")
print(f"Noise points: {n_noise}")
# ========================
# 3. PCA μ°¨μ μΆμ
# ========================
print("\n=== PCA Dimensionality Reduction ===")
# Iris λ°μ΄ν° (4D -> 2D)
iris = load_iris()
X_iris = iris.data # λ μ΄λΈ μμ΄ νΉμ±λ§ μ¬μ©
# PCA μ μ©
pca = PCA(n_components=2)
X_pca = pca.fit_transform(StandardScaler().fit_transform(X_iris))
print(f"Original dimensions: {X_iris.shape[1]}")
print(f"Reduced dimensions: {X_pca.shape[1]}")
print(f"Explained variance ratio: {pca.explained_variance_ratio_}")
print(f"Total variance explained: {sum(pca.explained_variance_ratio_):.3f}")
# ========================
# 4. ν΄λ¬μ€ν°λ§ + μκ°ν
# ========================
class UnsupervisedAnalyzer:
"""λΉμ§λ νμ΅ λΆμ ν΄λμ€"""
def __init__(self, random_state=42):
self.random_state = random_state
self.scaler = StandardScaler()
def cluster_analysis(self, X, max_k=10):
"""μ΅μ ν΄λ¬μ€ν° μ λΆμ"""
X_scaled = self.scaler.fit_transform(X)
results = {
'k': [],
'inertia': [],
'silhouette': []
}
for k in range(2, max_k + 1):
kmeans = KMeans(n_clusters=k, random_state=self.random_state, n_init=10)
labels = kmeans.fit_predict(X_scaled)
results['k'].append(k)
results['inertia'].append(kmeans.inertia_)
results['silhouette'].append(silhouette_score(X_scaled, labels))
return results
def reduce_and_cluster(self, X, n_clusters=3, reduction='pca'):
"""μ°¨μ μΆμ ν ν΄λ¬μ€ν°λ§"""
X_scaled = self.scaler.fit_transform(X)
# μ°¨μ μΆμ
if reduction == 'pca':
reducer = PCA(n_components=2, random_state=self.random_state)
else: # t-SNE
reducer = TSNE(n_components=2, random_state=self.random_state,
perplexity=30, n_iter=300)
X_reduced = reducer.fit_transform(X_scaled)
# ν΄λ¬μ€ν°λ§
kmeans = KMeans(n_clusters=n_clusters, random_state=self.random_state, n_init=10)
labels = kmeans.fit_predict(X_scaled)
return X_reduced, labels
def anomaly_detection(self, X, contamination=0.1):
"""μ΄μμΉ νμ§ (Isolation Forest)"""
from sklearn.ensemble import IsolationForest
X_scaled = self.scaler.fit_transform(X)
iso_forest = IsolationForest(
contamination=contamination,
random_state=self.random_state
)
# -1: anomaly, 1: normal
predictions = iso_forest.fit_predict(X_scaled)
anomalies = X[predictions == -1]
return predictions, anomalies
# μ¬μ© μμ
analyzer = UnsupervisedAnalyzer()
# ν΄λ¬μ€ν° λΆμ
print("\n=== Cluster Analysis ===")
results = analyzer.cluster_analysis(X)
best_k = results['k'][np.argmax(results['silhouette'])]
print(f"Best k: {best_k}, Silhouette: {max(results['silhouette']):.3f}")
# μ°¨μ μΆμ + ν΄λ¬μ€ν°λ§
X_2d, labels = analyzer.reduce_and_cluster(X_iris, n_clusters=3)
print(f"\nIris data clustered into {len(set(labels))} groups")
print(f"2D representation shape: {X_2d.shape}")
# μ΄μμΉ νμ§
predictions, anomalies = analyzer.anomaly_detection(X)
print(f"\nDetected {len(anomalies)} anomalies out of {len(X)} samples")