🤖 AI/ML

Supervised Learning

Supervised Learning

An ML approach that learns from labeled data. Applied to classification and regression problems. The most common learning method.

📖 Detailed Explanation

Supervised Learning is a machine learning paradigm that uses a dataset in which input data (X) and ground-truth labels (Y) are given as pairs to learn a function that predicts outputs from inputs. The name "supervised" comes from the idea that the ground-truth labels guide (supervise) the learning.

Supervised learning is the oldest paradigm of machine learning and is the core learning method from the perceptron of the 1950s to modern deep learning. Historically, most traditional ML algorithms such as SVM, decision trees, and random forests are based on supervised learning, and ImageNet classification, which led the deep learning revolution, is also supervised learning. In the 2020s, RLHF (Reinforcement Learning from Human Feedback) for LLMs also includes a supervised learning stage (SFT).

The core principle of supervised learning is to minimize a loss function. Cross-Entropy Loss is mainly used for classification problems, and MSE (Mean Squared Error) for regression problems. The model updates its parameters in the direction that reduces the difference between predicted values and actual ground truth, and backpropagation and gradient descent are used in this process.

In practice, supervised learning is the most common and successful ML approach. Most industrial AI applications, such as image classification, spam filters, sentiment analysis, medical diagnosis, and credit scoring, are based on supervised learning. However, obtaining high-quality labeled data is a costly and time-consuming bottleneck, and alternative techniques such as semi-supervised learning, weak supervision, and self-supervised learning are being developed to address this.

💻 Code Example

Supervised learning examples for classification and regression using scikit-learn:

# 지도 학습 기본 예제 - 분류와 회귀
from sklearn.datasets import load_iris, load_boston
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.metrics import accuracy_score, classification_report
from sklearn.metrics import mean_squared_error, r2_score
import numpy as np

# ===== 1. 분류 (Classification) =====
print("=" * 50)
print("분류 예제: 붓꽃 품종 분류")
print("=" * 50)

# 데이터 로드
iris = load_iris()
X, y = iris.data, iris.target

# 학습/테스트 분할
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# 모델 학습
clf = RandomForestClassifier(n_estimators=100, random_state=42)
clf.fit(X_train, y_train)  # 지도 학습: X(입력), y(레이블) 쌍으로 학습

# 예측 및 평가
y_pred = clf.predict(X_test)
print(f"정확도: {accuracy_score(y_test, y_pred):.2%}")
print(f"\n분류 리포트:")
print(classification_report(y_test, y_pred, target_names=iris.target_names))

# 교차 검증
cv_scores = cross_val_score(clf, X, y, cv=5)
print(f"5-Fold CV 평균 정확도: {cv_scores.mean():.2%} (+/- {cv_scores.std()*2:.2%})")

# ===== 2. 회귀 (Regression) =====
print("\n" + "=" * 50)
print("회귀 예제: 주택 가격 예측")
print("=" * 50)

# 샘플 데이터 생성 (Boston 대신 synthetic)
np.random.seed(42)
X_reg = np.random.randn(500, 5)
y_reg = 3*X_reg[:,0] + 2*X_reg[:,1] - X_reg[:,2] + np.random.randn(500)*0.5

X_train_r, X_test_r, y_train_r, y_test_r = train_test_split(
    X_reg, y_reg, test_size=0.2, random_state=42
)

# 회귀 모델 학습
reg = RandomForestRegressor(n_estimators=100, random_state=42)
reg.fit(X_train_r, y_train_r)

# 예측 및 평가
y_pred_r = reg.predict(X_test_r)
print(f"MSE: {mean_squared_error(y_test_r, y_pred_r):.4f}")
print(f"RMSE: {np.sqrt(mean_squared_error(y_test_r, y_pred_r)):.4f}")
print(f"R² Score: {r2_score(y_test_r, y_pred_r):.4f}")

Deep learning supervised learning example using PyTorch:

# PyTorch 딥러닝 지도 학습
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset

# 신경망 정의
class SimpleClassifier(nn.Module):
    def __init__(self, input_dim, hidden_dim, num_classes):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Linear(input_dim, hidden_dim),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(hidden_dim, hidden_dim),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(hidden_dim, num_classes)
        )

    def forward(self, x):
        return self.layers(x)

# 학습 함수
def train_supervised(model, train_loader, criterion, optimizer, epochs=10):
    model.train()
    for epoch in range(epochs):
        total_loss = 0
        correct = 0
        total = 0

        for X_batch, y_batch in train_loader:
            optimizer.zero_grad()

            # Forward pass
            outputs = model(X_batch)
            loss = criterion(outputs, y_batch)

            # Backward pass (역전파)
            loss.backward()
            optimizer.step()

            total_loss += loss.item()
            _, predicted = outputs.max(1)
            total += y_batch.size(0)
            correct += predicted.eq(y_batch).sum().item()

        acc = 100 * correct / total
        print(f"Epoch {epoch+1}/{epochs} - Loss: {total_loss:.4f}, Acc: {acc:.2f}%")

# 사용 예시
model = SimpleClassifier(input_dim=4, hidden_dim=64, num_classes=3)
criterion = nn.CrossEntropyLoss()  # 분류용 손실 함수
optimizer = optim.Adam(model.parameters(), lr=0.001)

# 데이터 준비 (예: Iris)
X_tensor = torch.FloatTensor(X_train)
y_tensor = torch.LongTensor(y_train)
dataset = TensorDataset(X_tensor, y_tensor)
train_loader = DataLoader(dataset, batch_size=16, shuffle=True)

# 학습 실행
train_supervised(model, train_loader, criterion, optimizer, epochs=20)

📊 Learning Method Comparison

Comparison of machine learning paradigms:

Learning Method Data Requirements Representative Algorithms Application Areas
Supervised Learning Labeled data (X, Y) CNN, RNN, BERT, XGBoost Classification, regression, prediction
Unsupervised Learning Unlabeled data (X) K-Means, PCA, AutoEncoder Clustering, dimensionality reduction
Self-Supervised Learning Unlabeled data (X) GPT, BERT, SimCLR Pretraining, representation learning
Reinforcement Learning Environment feedback (reward) DQN, PPO, RLHF Games, robotics, LLM alignment
Semi-Supervised Learning Some labels + large amounts of unlabeled data Pseudo-labeling, MixMatch Situations with insufficient labels

🗣️ Say It Like This in Practice

💬 In a Meeting
"Supervised learning is the right approach for this problem. We have 10,000 labeled records, so let's build a quick baseline with XGBoost and move on to deep learning if performance falls short."
💬 In an Interview
"The biggest challenges of supervised learning are label quality and data distribution. Noisy labels degrade model performance, and differences in distribution between training and deployment environments (Data Shift) cause performance degradation in real services."
💬 In a Technical Discussion
"Even in the LLM era, supervised learning is still essential. GPT also goes through SFT (Supervised Fine-Tuning) after pretraining (self-supervised), and the reward model for RLHF is also trained with supervised learning on human preference data."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌

Training without verifying label quality

Noisy or inconsistent labels severely degrade model performance. Label quality review and checking Inter-annotator Agreement must come first.

❌

Ignoring Data Leakage

If test data information leaks into training, performance is overestimated. In particular, leaking future information in time-series data, or using statistics from the entire dataset during preprocessing, are common mistakes.

✅

The right approach

Perform the data split first, then fit preprocessing (scaling, encoding) on the training data only and transform the test data. Use chronological splits for time series and group-level splits for grouped data.

🔗 Related Terms

📚 Learn More