πŸ€– AI/ML

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.

πŸ“– Detailed Explanation

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.

πŸ’» Code Example

An example of unsupervised learning using K-Means clustering and PCA:

Python
# 비지도 ν•™μŠ΅: ν΄λŸ¬μŠ€ν„°λ§κ³Ό 차원 μΆ•μ†Œ 예제
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")

πŸ—£οΈ How It's Said in Practice

In a data analysis meeting
"Our customer data has no labels, so we tried segmenting it with unsupervised learning. K-Means gave us 5 groups, and the silhouette score is around 0.6."
In an anomaly detection system discussion
"Since we only have normal transaction patterns, I think we should apply unsupervised anomaly detection. Shall we try Isolation Forest or an Autoencoder?"
In the data preprocessing stage
"If we reduce dimensions with PCA before training the model to cut noise, and add the clustering results as features, performance should improve."
In an ML engineer conversation
"Label collection is too expensive, so it would be more efficient to cluster in an unsupervised way first and label only the representative samples."

⚠️ Common Mistakes & Cautions

Deciding the number of clusters arbitrarily
You should not just set k to 3 or 5 in K-Means. Use the Elbow Method, Silhouette Score, Gap Statistic, and similar methods to determine the number of clusters appropriate for your data.
Clustering without scaling
Distance-based algorithms (K-Means, DBSCAN) are sensitive to feature scale. If you do not normalize with StandardScaler or MinMaxScaler, certain features will dominate the results.
Expecting a correct answer from the results
Unsupervised learning is "discovery," not "prediction." Whether clustering results are meaningful from a business perspective requires interpretation by a domain expert, and there is no guarantee that useful groups will emerge.
Clustering directly on high-dimensional data
When dimensionality is high, the notion of distance becomes meaningless, causing the "curse of dimensionality." If you have hundreds of features or more, it is better to reduce dimensions with PCA or similar methods before clustering.

πŸ”— Related Terms

πŸ“š Learn More