View

순전파와 역전파

🎯 순전파(Forward Propagation) vs. 역전파(Backpropagation)

1️⃣ 순전파 (Forward Propagation)

순전파는 입력 데이터를 받아 신경망을 통해 예측값 \( \hat{y} \) 를 계산하는 과정이다.

✅ 순전파 수식

\[ \hat{y} = f(WX + b) \]

  • \( X \): 입력 데이터 (Input)
  • \( W \): 가중치 (Weights)
  • \( b \): 편향 (Bias)
  • \( f \): 활성화 함수 (Activation Function)
  • \( \hat{y} \): 예측값 (Prediction)

✅ PyTorch 코드 예제 (순전파)

import torch
import torch.nn as nn

class SimpleNN(nn.Module):
    def __init__(self):
        super(SimpleNN, self).__init__()
        self.fc1 = nn.Linear(3, 2)

    def forward(self, x):
        return self.fc1(x) 

model = SimpleNN()
x = torch.tensor([[1.0, 2.0, 3.0]])
output = model(x)
print(output)  
    

2️⃣ 역전파 (Backpropagation)

역전파는 예측값과 실제값의 차이를 최소화하기 위해 가중치를 조정하는 과정이다.

✅ 손실(loss) 계산

\[ \text{Loss} = \frac{1}{n} \sum (y - \hat{y})^2 \]

✅ 기울기(Gradient) 계산

\[ \frac{\partial \text{Loss}}{\partial W} \]

✅ 가중치 업데이트 (Gradient Descent)

\[ W = W - \alpha \frac{\partial \text{Loss}}{\partial W} \]

  • \( \alpha \) (학습률, Learning Rate): 업데이트 크기 조절

✅ PyTorch 코드 예제 (역전파)

import torch
import torch.nn as nn
import torch.optim as optim

class SimpleNN(nn.Module):
    def __init__(self):
        super(SimpleNN, self).__init__()
        self.fc = nn.Linear(2, 1)

    def forward(self, x):
        return self.fc(x)  

model = SimpleNN()
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)

X = torch.tensor([[1.0, 2.0]], requires_grad=True)
y = torch.tensor([[3.0]])

y_hat = model(X)
loss = criterion(y_hat, y)

loss.backward() 
optimizer.step()
optimizer.zero_grad()
    

📊 순전파 vs. 역전파 비교

과정 설명 수식
순전파 (Forward Pass) 입력 → 네트워크 → 예측값 \( \hat{y} \) \( \hat{y} = W X + b \)
손실 계산 (Loss Computation) 예측값과 실제값 비교 \( \text{Loss} = (y - \hat{y})^2 \)
역전파 (Backward Pass) 손실을 미분하여 기울기 계산 \( \frac{\partial \text{Loss}}{\partial W} \)
가중치 업데이트 (Update Weights) 경사 하강법 적용 \( W = W - \alpha \frac{\partial \text{Loss}}{\partial W} \)

✅ 결론

  • 순전파(Forward Propagation): 입력을 받아 예측값(\( \hat{y} \))을 계산하는 과정
  • 역전파(Backpropagation): 손실을 줄이기 위해 기울기 계산 후 가중치를 업데이트하는 과정
  • 순전파는 "예측", 역전파는 "학습"
  • 이 두 과정이 반복되면서 신경망이 최적의 가중치를 학습하게 됨!

🔥 즉, 순전파는 데이터를 처리하는 과정, 역전파는 모델을 학습시키는 과정! 🚀😊

Share Link
reply
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28