2024. 7. 1. 00:05ㆍDATA/BIGDATA
선형 회귀 모델
선형 회귀 모델은 입력 변수 \( x \)와 출력 변수 \( y \) 사이의 선형 관계를 모델링한다.
\[ f(x) = \mathbf{w}^\top \mathbf{x} + b \]
- \( f(x) \)는 예측값이다.
- \( \mathbf{w} \)는 가중치 벡터이다.
- \( \mathbf{x} \)는 입력 변수 벡터이다.
- \( b \)는 편향(bias)이다.
손실 함수
선형 회귀에서 자주 사용하는 손실 함수는 평균 제곱 오차(MSE, Mean Squared Error)이다. MSE는 다음과 같이 정의된다:
\[ \text{MSE} = \frac{1}{N} \sum_{i=1}^{N} (y_i - f(x_i))^2 \]
- \( N \)은 데이터 포인트의 수이다.
- \( y_i \)는 실제 값이다.
- \( f(x_i) \)는 예측값이다.
경사 하강법 (Gradient Descent)
모델의 가중치와 편향을 최적화하기 위해 경사 하강법을 사용하며 손실 함수를 최소화하는 가중치와 편향을 찾기 위해 반복적으로 업데이트한다.
가중치 업데이트:
\[ \mathbf{w} \leftarrow \mathbf{w} - \eta \frac{\partial \text{MSE}}{\partial \mathbf{w}} \]
편향 업데이트:
\[ b \leftarrow b - \eta \frac{\partial \text{MSE}}{\partial b} \]
- \( \eta \)는 학습률(learning rate)이다.
- \(\frac{\partial \text{MSE}}{\partial \mathbf{w}}\)와 \(\frac{\partial \text{MSE}}{\partial b}\)는 MSE의 가중치와 편향에 대한 기울기이다.
가중치에 대한 기울기:
\[ \frac{\partial \text{MSE}}{\partial \mathbf{w}} = -\frac{2}{N} \sum_{i=1}^{N} (y_i - f(x_i)) \mathbf{x_i} \]
편향에 대한 기울기:
\[ \frac{\partial \text{MSE}}{\partial b} = -\frac{2}{N} \sum_{i=1}^{N} (y_i - f(x_i)) \]
선형 회귀의 공식 정리
\[ f(x) = \mathbf{w}^\top \mathbf{x} + b \]
입력 변수 \( x \)와 출력 변수 \( y \) 사이의 관계를 모델링하고, 경사 하강법을 사용하여 가중치와 편향을 최적화할 수 있다.
선형 회귀에서 가중치 \( \mathbf{w} \)와 편향 \( b \)를 구하는 일반적인 방법은 보통 최소자승법(Least Squares Method)을 사용하여 손실 함수(주로 평균 제곱 오차, MSE)를 최소화하는 것이다.
손실 함수 (MSE)
평균 제곱 오차(MSE) 손실 함수는
\[ \text{MSE} = \frac{1}{N} \sum_{i=1}^{N} (y_i - (\mathbf{w}^\top \mathbf{x}_i + b))^2 \]
- \( N \)은 데이터 포인트의 수이다.
- \( y_i \)는 실제 값이다.
- \( \mathbf{x}_i \)는 \( i \)번째 데이터 포인트이다.
Normal Equation
가중치 \( \mathbf{w} \)와 편향 \( b \)를 구하기 위해, 미분을 통해 손실 함수를 최소화한다.
a. 입력 행렬과 출력 벡터 정의
입력 행렬 \( \mathbf{X} \)는 각 행이 하나의 데이터 포인트 \(\mathbf{x}_i\)인 행렬로 정의된다. \( \mathbf{y} \)는 출력 벡터이다.
\[ \mathbf{X} = \begin{bmatrix} \mathbf{x}_1^\top \\ \mathbf{x}_2^\top \\ \vdots \\ \mathbf{x}_N^\top \end{bmatrix}, \quad \mathbf{y} = \begin{bmatrix} y_1 \\ y_2 \\ \vdots \\ y_N \end{bmatrix} \]
b. 편향을 포함한 행렬 확장
편향 \( b \)를 포함시키기 위해 입력 행렬 \( \mathbf{X} \)에 편향 항을 추가한다.
\[ \mathbf{X}' = \begin{bmatrix} 1 & \mathbf{x}_1^\top \\ 1 & \mathbf{x}_2^\top \\ \vdots \\ 1 & \mathbf{x}_N^\top \end{bmatrix}, \quad \mathbf{w}' = \begin{bmatrix} b \\ \mathbf{w} \end{bmatrix} \]
Normal Equation
\[ \mathbf{w}' = (\mathbf{X}'^\top \mathbf{X}')^{-1} \mathbf{X}'^\top \mathbf{y} \]
Normal Equation 을 사용하여 가중치와 편향을 계산
1. \( \mathbf{X}' \)와 \( \mathbf{y} \)를 정의한다.
2. \( \mathbf{X}'^\top \mathbf{X}' \)를 계산한다.
3. \( (\mathbf{X}'^\top \mathbf{X}')^{-1} \)를 계산한다.
4. \( \mathbf{X}'^\top \mathbf{y} \)를 계산한다.
5. 최종적으로 \( \mathbf{w}' \)를 구한다.
import numpy as np
def loss_func(x,t):
y =np.dot(x,W)+b
return(np.sum((t-y)2))/(len(x)) #MSE
def numerical_derivative(f,x):
delta_x=1e-4 #0.0001
grad=np.zeros_like(x)
it= np.nditer(x,flags=['multi_index'], op_flags=['readwrite']) #읽기 쓰기 용도
while not it.finished:
idx=it.multi_index
tmp_val=x[idx]
x[idx] =float(tmp_val)+delta_x
fx1=f(x)
x[idx] =float(tmp_val)-delta_x
fx2=f(x)
grad[idx]=(fx1-fx2)/(2delta_x)
x[idx] =tmp_val
it.iternext()
return grad #수정 된 가중치를 return
x_data = np. array([1, 2, 3, 4, 5]).reshape(5,1)
t_data = np. array([2, 3, 4, 5, 6]).reshape(5,1)
W=np.random.rand(1,1)
b =np.random.rand(1)
learning_rate=1e-2
f=lambda x : loss_func(x_data,t_data)
print("intital loss value=" , loss_func(x_data,t_data),"Initial W=",W,"\n",",b=",b)
for step in range(6001): #학습 횟수
W -=learning_rate numerical_derivative(f,W) #수정된 가중치를 받아서 업데이트
b -=learning_rate numerical_derivative(f,b) #
if (step % 300 ==0): #300이 될 때 가중치 편향 출력
print("step =",step,"loss value ",loss_func(x_data,t_data),"W =",W,"b =",b)
손실함수는 점점 줄어들고 w b는 업데이트되며 변화가 없을 때 학습은 끝이 난 것이다.
선형 회귀 모델의 \( f(x) = \mathbf{w}^\top \mathbf{x} + b \)를 미분하는 공식과 관련된 \(\frac{f(x + \Delta x) - f(x - \Delta x)}{2 \Delta x}\)는 수치 미분의 중심 차분 방법을 나타낸다.
수치 미분 (중심 차분)
\[ f'(x) \approx \frac{f(x + \Delta x) - f(x - \Delta x)}{2 \Delta x} \]
이 방법을 선형 회귀 모델에 적용하면
중심 차분을 선형 회귀 모델에 적용
선형 회귀 모델에서 \( f(x) \)는 다음과 같다:
\[ f(x) = \mathbf{w}^\top \mathbf{x} + b \]
따라서, \( f(x + \Delta x) \)와 \( f(x - \Delta x) \)를 계산하면:
\[ f(x + \Delta x) = \mathbf{w}^\top (\mathbf{x} + \Delta \mathbf{x}) + b = \mathbf{w}^\top \mathbf{x} + \mathbf{w}^\top \Delta \mathbf{x} + b \]
\[ f(x - \Delta x) = \mathbf{w}^\top (\mathbf{x} - \Delta \mathbf{x}) + b = \mathbf{w}^\top \mathbf{x} - \mathbf{w}^\top \Delta \mathbf{x} + b \]
중심 차분을 사용하여 미분하면:
\[ f'(x) \approx \frac{f(x + \Delta x) - f(x - \Delta x)}{2 \Delta x} \]
\[ f'(x) \approx \frac{(\mathbf{w}^\top \mathbf{x} + \mathbf{w}^\top \Delta \mathbf{x} + b) - (\mathbf{w}^\top \mathbf{x} - \mathbf{w}^\top \Delta \mathbf{x} + b)}{2 \Delta x} \]
\[ f'(x) \approx \frac{\mathbf{w}^\top \mathbf{x} + \mathbf{w}^\top \Delta \mathbf{x} - \mathbf{w}^\top \mathbf{x} + \mathbf{w}^\top \Delta \mathbf{x}}{2 \Delta x} \]
\[ f'(x) \approx \frac{2 \mathbf{w}^\top \Delta \mathbf{x}}{2 \Delta x} \]
\[ f'(x) \approx \mathbf{w}^\top \]
따라서, 선형 회귀 모델의 미분 결과는 단순히 가중치 벡터 \( \mathbf{w} \)가 된다. 이는 선형 회귀 모델이 선형 함수이기 때문이다.
선형 회귀 모델 \( f(x) = \mathbf{w}^\top \mathbf{x} + b \)에서 중심 차분 방법을 사용한 미분은 가중치 벡터 \( \mathbf{w} \)가 된다:
\[ f'(x) \approx \mathbf{w} \]
선형 회귀 모델의 기울기를 나타내며 모델의 가중치를 나타내는 벡터와 같다.
'DATA > BIGDATA' 카테고리의 다른 글
NORM.INV (0) | 2024.07.02 |
---|---|
혼동행렬 관련 분류 성능 값 (0) | 2024.07.02 |
파이썬 데이터 라이브러리 관련 (0) | 2024.06.27 |
SSR SSE (0) | 2024.06.14 |
epsilon (0) | 2024.06.12 |