카테고리 없음

Hypothesis Function

기술1 2025. 7. 7. 10:08
x_train = torch.FloatTensor([[1], [2], [3]])
y_train = torch.FloatTensor([[1], [2], [3]])

 

H(x) = x가 정확한 모델입니다. W= 1 이 가장 좋은 숫자입니다. 

 

모델의 좋고 나쁨을 평가할 때는 Cost function을 봅니다. 잘 학습된 모델일수록 낮은 cost를 가집니다. W  = 1 일 때, COST = 0 1에서 멀어질수록 높아집니다. 

 

MSE

예측값과 실제값의 차이를 제곱한 평균으로 구해집니다. 

cost = torch.mean((hypothesis - y_train) ** 2)

 

Gradient Descent : Intution

 

  • 곡선을 내려가자
  • 기울기가 클수록 더 멀리
  • Gradient를 계산하자

Gradient에 따라서 cost를 줄이고 늘려야 합니다. 

gradient = 2 * torch.mean((W * x_train - y_train) * x_train)
lr = 0.1
W -= lr * gradient

 

#데이터
x_train = torch.FloatTensor([[1], [2], [3]])
y_train = torch.FloatTensor([[1], [2], [3]])

#모델 초기화
W = torch.zeros(1)

#learning rate 설정
lr = 0.1

nb_epochs = 10
for epoch in range(nb_epochs + 1):
	#H(x) 계산
    hypothesis = x_train * 
    
    #cost graedient 계산
    cost = torch.mean((hypothesis - y_train) ** 2)
    gradient = torch.suim((W * x_train - y_train) * x_train)
    
    print('Epoch (:4d)/{} W: {:.3f}, Cost: {:.6f}'.format(
    	epoch, nb_epochs, W.items(), cost.items()
    ))
    
    # cost gradient 로 H(x) 개선
    W -= lr * gradient

 

Gradient Descient with torch.optim

torch.optim 으로도 gradient descent를 가능

  • 시작할 때 optimizer 정의
  • optimizer.zero_grad()로 gradient를 0으로 초기화
  • cost.backward()로 gradient 계산
  • optimizer.step() 으로 gradient descent
#optimizer 설정
optimizer = optim.SGD([W], lr=0.15)

#cost로 H(x) 개선
optimizer.zero_grad()
cost.backward()
optimizer.step()

 

 

Data

복수의 정보가 존재할 때 어떻게 하나를 추출하는지 

 

Q1, Q2, Q3를 가지고 Y를 예측하는 것입니다. 

 

Hypothesis Function

이렇게 할 경우 젖멈 길어질 것이기에 matmul을 사용해서 한 번에 곗나합니다. 

 

matmul()

 

optimizer를 설정한 후 gradient descent를 합니다.

 

#데이터
x_train = torch.FloatTensor([[73, 80, 75],
							 [93, 88, 93],
                             [89, 91, 90],
                             [96, 98, 100],
                             [73, 66, 70]])
y_train = torch.FloatTensor([[152], [185], [180], [196], [142]])

#모델 초기화
W = torch.zeros((3, 1), requires_grad = True)
b = torch.zeros(1, requires_grad = True)

#optimizer 설정
optimizer = optim_SGD([W, b], lr = 1e-5)

nb_epochs =20

for epochs in range(nb_epochs + 1):
	#H(x) 계산
    hypothesis = x_train.matmul(W) + b #or .. or @
    
    #cost 계산
    cost = torch.mean((hypothesis - y_train) ** 2)
    
    #cost로 H(x) 개선
    optimizer.zero_grad()
    cost.backward()
    optimizer.step()
    
    print('Epoch {:4d}/{} hypothesis: {} Cost: {:.6f}'.format(
    	epoch, nb_epochs, hypothesis.squeeze().detach(),
        cost.item()
    ))

 

하지만 w와 b를 계속 쓰는 것은 번거롭기 때문에 nn.Module를 사용합니다. 

 

3개의 입력으로 하나의 출력을 만드는 것을 볼 때, 단순히 nn.linear에 입력과 출력을 알려주고 forward 함수에서 hypothesis를 어떻게 하는지 알려주면 됩니다.

 

 

import torch.nn as nn

class MultivariateLinearRegressionModel(nn.Module):
	def __init__(self):
    	super().__init__()
        self.linear = nn.Linear(3, 1)
    
    def forward(self, x):
    	return self.linear(x)

hypothesis = model(x_train)
  • nn.Module을 상속해서 모델 생성
  • nn.Linear(3, 1)
    • 입력 차원 : 3
    • 출력 차원 : 1
  • Hypothesis 계산은 forward() 에서!
  • Gradient 계산은 Pytorch가 알아서 해준다. backward()
#cost 계산 
cost = torch.mean((hypothesis - y_train) ** 2)

import torch.nn.functional as F

#cost 계산 
cost = F.mse_loss(prediction, y_train)

쉽게 다른 loss와 교체 가능(l1_loss 등)

 

#데이터
x_train = torch.FloatTensor([[73, 80, 75],
							 [93, 88, 93],
                             [89, 91, 90],
                             [96, 98, 100],
                             [73, 66, 70]])
y_train = torch.FloatTensor([[152], [185], [180], [196], [142]])

#모델 초기화
model = MultivariateLinearRegressionModel()

#optimizer 설정
optimizer = optim_SGD([W, b], lr = 1e-5)

nb_epochs =20

for epochs in range(nb_epochs + 1):
	#H(x) 계산
    hypothesis = model(x_train)
    
    #cost 계산
    cost = F.mse_loss(prediction, y_train)
    
    #cost로 H(x) 개선
    optimizer.zero_grad()
    cost.backward()
    optimizer.step()
    
    print('Epoch {:4d}/{} hypothesis: {} Cost: {:.6f}'.format(
    	epoch, nb_epochs, hypothesis.squeeze().detach(),
        cost.item()
    ))