선형회귀는 feature와 target 사이의 관계를 coefficient의 선형 결합으로 표현한다. 단순히 직선을 그리는 방법을 넘어, loss를 어떻게 정의하고 regularization과 validation을 어떻게 분리하는지까지 연결해야 model 평가가 흔들리지 않는다.

model과 용어부터 구분한다
feature가 여러 개인 linear model은 다음과 같이 쓸 수 있다.
y_hat = beta_0 + beta_1*x_1 + ... + beta_p*x_p
y_hat: model의 predictionx_j: feature·설명변수·독립변수beta_j: 각 feature의 coefficient·weightbeta_0: intercept, machine learning 문맥에서 bias term이라고도 부름y: target·목적변수·종속변수
여기서 intercept인 bias term과 bias-variance trade-off의 statistical bias는 같은 표현을 쓰지만 다른 개념이다. 또 “bias는 prediction과 actual의 차이”가 아니다. 한 sample의 차이는 residual로 구분한다.
residual_i = y_i - y_hat_i
ordinary least squares가 최소화하는 것
Ordinary Least Squares(OLS)는 residual sum of squares를 최소화하는 coefficient를 찾는다.
RSS(beta) = sum_i (y_i - y_hat_i)^2
MSE는 squared residual 합을 sample 수로 나눈 metric이다.
MSE = (1 / n) * sum_i (y_i - y_hat_i)^2
outlier의 큰 residual이 제곱되므로 영향이 커질 수 있다. coefficient를 인과효과로 해석하려면 linearity뿐 아니라 confounding, sampling, error structure 같은 추가 가정이 필요하다. prediction model의 coefficient만 보고 “이 feature가 가격을 올린다”고 결론 내리지 않는다.
L1·L2는 loss에 penalty를 더한다
feature가 많거나 서로 강하게 correlated하면 OLS coefficient가 불안정할 수 있다. regularized linear model은 data fit과 coefficient 크기의 균형을 조정한다.
| model | objective에 더하는 항 | 일반적인 효과 |
|---|---|---|
| Ridge | alpha * sum(beta_j^2) |
coefficient를 부드럽게 shrink |
| Lasso | alpha * sum(abs(beta_j)) |
일부 coefficient가 0이 될 수 있음 |
| Elastic Net | L1과 L2의 가중 결합 | sparsity와 correlated feature 안정성 절충 |
Lasso가 언제나 올바른 feature를 골라 주거나 Ridge가 overfitting을 막아 준다는 보장은 없다. alpha가 너무 크면 underfitting이 생길 수 있다. penalty는 feature scale의 영향을 받으므로 일반적으로 scaling을 pipeline 안에서 함께 처리하고 alpha는 training data의 cross-validation으로 고른다.
test set은 마지막 평가에 남겨 둔다
training data와 test data를 나누는 이유는 unseen data에 대한 generalization을 추정하기 위해서다. test score를 보며 feature와 alpha를 계속 바꾸면 test set도 사실상 training decision에 사용된다.
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = fetch_california_housing(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
이 코드는 API 흐름을 보여 주는 최소 예시이며 특정 성능을 보장하지 않는다. 실제 housing data는 지역·시간적 상관이 있을 수 있어 random split이 배포 상황을 과대평가할 수 있다. 미래 지역이나 시점을 예측한다면 group·time-aware split을 설계한다.
MSE와 R²를 함께 읽는다
- MSE: target 단위의 제곱이므로 큰 error에 민감하고 model 간 비교에 사용
- RMSE: MSE의 square root로 target과 같은 단위
- R²: constant baseline 대비 설명력. 1에 가까울수록 높지만 test에서 음수가 될 수도 있음
R² 하나가 높다고 calibration, fairness, causal validity가 보장되는 것은 아니다. residual plot과 error distribution, segment별 error도 함께 본다.
Boston Housing dataset은 현재 기본 예제로 쓰지 않는다
원문 학습 목록에는 Boston Housing Dataset이 있었지만 scikit-learn의 load_boston은 1.0에서 deprecated되고 1.2에서 제거됐다. maintainer는 특정 variable의 인종차별적 가정과 연구 목적의 문제를 설명하며, ethical issue 교육이 아니라면 사용을 강하게 권하지 않는다.
회귀 API를 학습하려면 California Housing이나 Ames Housing 같은 대안을 사용할 수 있다. dataset을 바꾸는 것만으로 윤리·leakage 문제가 사라지는 것은 아니므로 feature provenance와 수집 맥락을 먼저 읽는다.
선형회귀의 기초가 되는 vector·matrix는 인공지능을 위한 선형대수, 확률·통계 용어는 인공지능을 위한 확률과 통계, 이후 application은 인공지능을 위한 자연어 처리로 연결된다.
참고 자료
'배움과 성장 > AI·자동화' 카테고리의 다른 글
| AI 입문 용어 지도: 데이터·학습·모델·RAG·MLOps 연결하기 (6) | 2025.06.22 |
|---|---|
| 자연어 처리로 문서 분류하기: TF-IDF·로지스틱 회귀 기준선 만들기 (8) | 2025.06.12 |
| 인공지능을 위한 수학 4: 평균·분산부터 MLE·Bayes 추정까지 (0) | 2025.06.06 |
| AI를 위한 확률과 통계: 확률변수·분포·기댓값의 연결 (0) | 2025.05.19 |
| AI를 위한 선형대수: 내적·outer product·선형변환 구분하기 (2) | 2025.05.14 |
댓글