Ordinary Least Squares

Version 16 | Created: 2026-09-12 | Updated: 2026-11-07 13:46 UTC
- 1. Purpose
- 2. Summary
- 3. Design Matrix
- 4. Least Squares Criterion
- 5. Normal Equation
- 6. Fitting
- Appendix A. Terminology
- Appendix B. Computation
- Appendix C. Self Inner Product of a Vector
- Appendix D. Expanding the Residual Sum of Squares
- Appendix E. Vector Derivatives for the Gradient
- Problem Statement: 선형 회귀의 계수는 자료가 정하지만, 계수를 관측치마다 따로 맞추면 관측치 수만큼의 식이 남는다. 자료와 항을 하나의 행렬로 세워 최소화 문제를 한 번에 풀어야 계수가 유일하게 정해진다.
-
Goal: design matrix
$X$ 와 응답 벡터$y$ 에서 normal equation 을 유도하여 회귀계수 추정값$\hat{\beta}$ 를 닫힌 형태로 구하고, 그 계산을 NumPy 로 재현한다. -
Non-Goal:
$X^\top X$ 의 역행렬이 없거나 불안정할 때 쓰는 regularization 은 다루지 않는다.
회귀 model 을 적합 (fitting) 한다는 것은 design matrix
Design matrix
-
행 (Rows): 개별 관측치 (observation)
$n$ 개 -
열 (Columns): model 이 사용하는 각 항, 절편 및 특성 (feature)
$p + 1$ 개
첫 번째 열의 1 은 절편 (intercept,
선형 회귀 model 은 행렬식으로 표현된다.
Table 1. Symbols of the matrix form
| Symbol | Meaning | Shape |
|---|---|---|
| 응답 변수 벡터 | ||
| Design matrix | ||
| 회귀계수 벡터 | ||
| 잔차 (오차) 벡터 |
최소제곱법 (Ordinary Least Squares, OLS) 의 목적은 잔차 제곱합 (Residual Sum of Squares,
식 (3) 의 전개는 다음과 같으며, 그 과정은 Appendix D 에 있다.
식 (5) 를 정리한 것이 normal equation 이다.
이름의 normal 은 직교를 뜻하며, 식 (6) 은
이 조건을 그림으로 옮긴 것이 Fig 1 이다.
y
/|
/ |
/ |
/ | residual
/ | (perpendicular to the column space)
/ |
O -----------+------+---------------------- column space
X beta
(foot of the perpendicular)
Fig 1. The residual as the perpendicular from y to the column space
-
평면:
$X\beta$ 로 만들 수 있는 모든 벡터가 놓이는 자리인 열공간. -
수선 (perpendicular):
$y$ 에서 그 평면에 90° 로 내린 선분. 그 길이의 제곱이$RSS$ 이다. -
수선의 발: 평면 위에서
$y$ 에 가장 가까운 점$X\beta$ . 평면 위의 다른 점을 고르면 빗변이 되어$y$ 까지의 거리가 길어진다.
Model 을 적합 (fit) 한다는 것은 자료가 지시하는 최적의 계수 값
식 (7) 의 계산은 Appendix B 에 있다.
- column space: Design matrix 의 열들이 만드는 벡터 공간.
-
design matrix: 관측치를 행으로, model 의 항을 열로 놓은
$n \times (p+1)$ 행렬. - fitting: 자료가 지시하는 최적의 계수 값을 구하는 과정.
-
intercept: Design matrix 의 1 로 채워진 첫 열에 대응하는 계수
$\beta_0$ . - L2 norm: 벡터 원소의 제곱합의 제곱근.
-
linear form:
$\beta^\top a$ 처럼 계수의 1 차 항만으로 이루어진 스칼라 함수. -
normal equation:
$RSS$ 의 경사도를 0 으로 두어 얻은 연립방정식$X^\top X \beta = X^\top y$ . - orthogonal projection: 한 벡터에서 어떤 공간에 내린 수선의 발. 그 공간 안에서 원래 벡터에 가장 가까운 점이다.
- perpendicular: 한 점에서 직선이나 평면에 90° 로 내리그은 선분. 그것이 닿는 점이 수선의 발이다.
-
quadratic form:
$\beta^\top A \beta$ 처럼 계수의 2 차 항으로 이루어진 스칼라 함수. - residual: 관측값과 model 예측값의 차이.
- RSS: Residual Sum of Squares. 잔차의 제곱합.
- transpose: 행과 열을 맞바꾼 행렬. 합에서는 그대로, 곱에서는 차례가 뒤집힌다.
식 (7) 은 NumPy 의 행렬 연산으로 그대로 옮겨진다. 아래 code 는 계수를 알고 있는 가상 데이터를 만들고, design matrix 를 세우고, normal equation 으로 구한 LinearRegression 결과와 대조한다.
# Python
import numpy as np
from sklearn.linear_model import LinearRegression
# 1. Generate synthetic data (y = 3 + 2*x1 + 5*x2 + noise)
np.random.seed(42)
n_samples = 100
x1 = np.random.rand(n_samples, 1) * 10
x2 = np.random.rand(n_samples, 1) * 5
noise = np.random.randn(n_samples, 1)
# True coefficients: beta_0 = 3, beta_1 = 2, beta_2 = 5
y = 3 + 2 * x1 + 5 * x2 + noise
# 2. Build the design matrix X
# Prepend a column of ones for the intercept (bias) term
X_raw = np.hstack([x1, x2])
ones = np.ones((n_samples, 1))
X = np.hstack([ones, X_raw])
print(f"Shape of design matrix X: {X.shape}") # (100, 3)
print("First 3 rows of the design matrix:\n", X[:3])
print("-" * 50)
# 3. Solve for beta with the normal equation
# beta_hat = (X^T * X)^(-1) * X^T * y
# Method A: direct inverse with np.linalg.inv
X_transpose = X.T
beta_hat_inv = np.linalg.inv(X_transpose @ X) @ X_transpose @ y
# Method B: linear solve, preferred for numerical stability
# (X^T * X) * beta = X^T * y
beta_hat_solve = np.linalg.solve(X_transpose @ X, X_transpose @ y)
print("Normal equation (direct inverse):")
print(f" intercept (beta_0): {beta_hat_inv[0][0]:.4f}")
print(f" coefficient (beta_1): {beta_hat_inv[1][0]:.4f}")
print(f" coefficient (beta_2): {beta_hat_inv[2][0]:.4f}")
print("-" * 50)
# 4. Cross-check against scikit-learn LinearRegression
model = LinearRegression()
model.fit(X_raw, y)
print("scikit-learn fit:")
print(f" intercept: {model.intercept_[0]:.4f}")
print(f" coefficients: {model.coef_[0]}")NumPy 2.4.6 과 scikit-learn 1.9.1 에서 실행한 결과는 다음과 같다.
Shape of design matrix X: (100, 3)
First 3 rows of the design matrix:
[[1. 3.74540119 0.15714593]
[1. 9.50714306 3.18205206]
[1. 7.31993942 1.57177991]]
--------------------------------------------------
Normal equation (direct inverse):
intercept (beta_0): 2.9106
coefficient (beta_1): 1.9658
coefficient (beta_2): 5.1439
--------------------------------------------------
scikit-learn fit:
intercept: 2.9106
coefficients: [1.96582747 5.14386228]
정규방정식으로 구한 계수와 LinearRegression 이 적합한 계수는 소수 넷째 자리까지 같다. 둘 다 참값
Code 에서 짚을 곳은 세 군데다.
-
np.hstack([ones, X_raw]): 원본 특성 데이터 앞에 1 로 채워진 열을 붙여 만든 design matrix$X$ . 그 첫 번째 열이 절편$\beta_0$ 와 곱해지는 항. -
@연산자: NumPy 의 행렬 곱셈 (matrix multiplication).X.T @ X는$X^\top X$ . -
np.linalg.solve와np.linalg.inv: 연립방정식을 푸는 계산과$(X^\top X)^{-1}$ 역행렬을 직접 구하는 계산. Numerical 오차와 속도 측면에서np.linalg.solve(A, b)형태가 안정적.
열벡터
이 값은
식 (3) 의
식 (4) 는 식 (3) 의 곱을 풀어 쓴 것이며, 전치의 두 규칙과 스칼라의 성질 하나를 쓴다.
전치는 합을 그대로 따라가고 (
식 (9) 를 식 (3) 에 넣고 두 괄호를 분배하면 항이 넷 나온다.
가운데 두 항은 같은 값이다.
식 (11) 로 가운데 두 항을 합치면
식 (5) 는 세 가지 규칙에서 나온다. 상수항의 미분, 일차형 (linear form) 의 미분, 이차형 (quadratic form) 의 미분이며, 여기서 미분은
첫째, 상수의 미분은 0 이다.
둘째, 일차형
셋째, 이차형
식 (4) 의 세 항에 이 규칙을 차례로 넣은 것이 식 (5) 이다.
Table 2. The three terms of equation (4) under the rules
| Term of equation (4) | Rule | Derivative |
|---|---|---|
| 식 (13) | ||
| 식 (14), |
||
| 식 (15), |
