Supervised Learning
지도 학습
레이블된 데이터로 학습하는 머신러닝 방법. 분류(Classification)와 회귀(Regression) 문제를 해결하는 가장 기본적이고 널리 사용되는 ML 패러다임입니다.
지도 학습
레이블된 데이터로 학습하는 머신러닝 방법. 분류(Classification)와 회귀(Regression) 문제를 해결하는 가장 기본적이고 널리 사용되는 ML 패러다임입니다.
Supervised Learning(지도 학습)은 입력 데이터(X)와 정답 레이블(Y)이 쌍으로 주어진 데이터셋을 사용하여 모델을 학습시키는 머신러닝 방법론입니다. 마치 선생님이 학생에게 문제와 정답을 알려주며 가르치는 것처럼, 모델은 입력과 출력 사이의 관계를 학습합니다. 새로운 데이터가 들어오면 학습된 패턴을 기반으로 결과를 예측할 수 있습니다.
지도 학습의 역사는 1950년대 퍼셉트론(Perceptron)까지 거슬러 올라갑니다. 프랭크 로젠블랫이 개발한 퍼셉트론은 최초의 지도 학습 알고리즘 중 하나였습니다. 이후 결정 트리, SVM, 신경망 등 다양한 알고리즘이 발전하면서 지도 학습은 머신러닝의 핵심 분야로 자리잡았습니다.
지도 학습은 크게 분류(Classification)와 회귀(Regression) 두 가지 유형으로 나뉩니다. 분류는 이메일 스팸 여부, 이미지 내 객체 식별처럼 이산적인 카테고리를 예측합니다. 회귀는 주택 가격, 주가 예측처럼 연속적인 수치를 예측합니다. 학습 과정에서 모델은 손실 함수(Loss Function)를 최소화하는 방향으로 파라미터를 조정합니다.
실무에서 지도 학습은 가장 많이 사용되는 ML 패러다임입니다. 의료 진단, 신용 평가, 이미지 인식, 자연어 처리 등 대부분의 AI 응용 분야에서 지도 학습이 기반이 됩니다. 딥러닝도 본질적으로 지도 학습의 확장이며, GPT와 같은 LLM도 사전 학습 후 지도 학습 방식의 파인튜닝을 거칩니다.
scikit-learn을 사용한 분류와 회귀 예제입니다.
# Supervised Learning 기본 예제
from sklearn.datasets import load_iris, load_boston
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.metrics import accuracy_score, mean_squared_error, classification_report
import numpy as np
# ===== 1. 분류(Classification) 예제 =====
print("=" * 50)
print("분류(Classification) - Iris 데이터셋")
print("=" * 50)
# 데이터 로드
iris = load_iris()
X_cls, y_cls = iris.data, iris.target
# 학습/테스트 분할 (80% 학습, 20% 테스트)
X_train, X_test, y_train, y_test = train_test_split(
X_cls, y_cls, test_size=0.2, random_state=42
)
# 모델 학습
classifier = RandomForestClassifier(n_estimators=100, random_state=42)
classifier.fit(X_train, y_train) # 지도 학습: X와 y를 함께 전달
# 예측 및 평가
y_pred = classifier.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"정확도(Accuracy): {accuracy:.4f}")
print(f"테스트 샘플 수: {len(y_test)}")
print("\n분류 리포트:")
print(classification_report(y_test, y_pred, target_names=iris.target_names))
# ===== 2. 회귀(Regression) 예제 =====
print("\n" + "=" * 50)
print("회귀(Regression) - 합성 데이터")
print("=" * 50)
# 회귀용 합성 데이터 생성
np.random.seed(42)
X_reg = np.random.rand(200, 4) * 10 # 200개 샘플, 4개 특성
y_reg = 3*X_reg[:, 0] + 2*X_reg[:, 1] - X_reg[:, 2] + np.random.randn(200) * 2
# 학습/테스트 분할
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
)
# 회귀 모델 학습
regressor = RandomForestRegressor(n_estimators=100, random_state=42)
regressor.fit(X_train_r, y_train_r)
# 예측 및 평가
y_pred_r = regressor.predict(X_test_r)
mse = mean_squared_error(y_test_r, y_pred_r)
rmse = np.sqrt(mse)
print(f"평균 제곱 오차(MSE): {mse:.4f}")
print(f"평균 제곱근 오차(RMSE): {rmse:.4f}")
print(f"특성 중요도: {regressor.feature_importances_.round(3)}")
# ===== 3. 새로운 데이터 예측 =====
print("\n" + "=" * 50)
print("새로운 데이터 예측")
print("=" * 50)
# 새로운 붓꽃 데이터로 품종 예측
new_sample = [[5.1, 3.5, 1.4, 0.2]] # setosa 특성
prediction = classifier.predict(new_sample)
probability = classifier.predict_proba(new_sample)
print(f"입력 특성: {new_sample[0]}")
print(f"예측 품종: {iris.target_names[prediction[0]]}")
print(f"예측 확률: {dict(zip(iris.target_names, probability[0].round(3)))}")