본문 바로가기
AI/Machine Learning

Bias-Variance Trade-off in python

by comflex 2025. 4. 7.
728x90
반응형

Bias-Variance Trade-off를 이해하는 파이썬 예제와 설명

머신러닝 모델의 성능을 결정짓는 중요한 이론 중 하나가 바로 Bias-Variance Trade-off입니다. 이번 글에서는 이 개념을 직접 코드로 구현해보며, 시각적으로 어떻게 작동하는지 확인해보겠습니다.


목표

  • 다양한 복잡도를 가진 모델이 편향과 분산에 어떤 영향을 미치는지 확인

파이썬 코드 예제

import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split

# 1. 데이터 생성
np.random.seed(42)
X = np.sort(5 * np.random.rand(80, 1), axis=0)
y = np.sin(X).ravel() + np.random.normal(0, 0.2, X.shape[0])

# 2. 학습/테스트 데이터 분할
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)

train_errors = []
test_errors = []
degrees = range(1, 15)

# 3. 다양한 복잡도의 모델 테스트
for d in degrees:
    poly = PolynomialFeatures(degree=d)
    X_train_poly = poly.fit_transform(X_train)
    X_test_poly = poly.transform(X_test)

    model = LinearRegression().fit(X_train_poly, y_train)

    y_train_pred = model.predict(X_train_poly)
    y_test_pred = model.predict(X_test_poly)

    train_errors.append(mean_squared_error(y_train, y_train_pred))
    test_errors.append(mean_squared_error(y_test, y_test_pred))

# 4. 결과 시각화
plt.figure(figsize=(10, 6))
plt.plot(degrees, train_errors, label="Training Error", marker='o')
plt.plot(degrees, test_errors, label="Test Error", marker='s')
plt.xlabel("Polynomial Degree")
plt.ylabel("Mean Squared Error")
plt.title("Bias-Variance Trade-off")
plt.legend()
plt.grid(True)
plt.show()
반응형
728x90

결과 해석

Bias-Variance Trade-off

  • 낮은 차수 (degree 1~2): 모델이 너무 단순하여 데이터의 패턴을 제대로 학습하지 못함 → 편향 높음
  • 적절한 차수 (degree 4~6): 편향과 분산의 균형이 맞음 → 일반화 성능 좋음
  • 높은 차수 (degree 10 이상): 훈련 데이터에 과하게 적합되어 새로운 데이터 성능이 떨어짐 → 분산 높음

결론

Bias-Variance Trade-off는 이론으로도 중요하지만,
실제로 시도해보고 눈으로 확인해보는 경험이 훨씬 강력합니다.

  • 모델이 너무 단순하면 → 과소적합
  • 모델이 너무 복잡하면 → 과적합
  • 우리는 그 사이의 균형점을 찾는 것이 핵심입니다.

 

[AI/Machine Learning] - Bias-Variance Trade-off

 

728x90
반응형