1. 단순 선형회귀 클래스로 구현하기
import torch
import torch.nn as nn
import torch.nn.functional as F
class LinearRegressionModel(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(1, 1)
def forward(self, x):
return self.linear(x)
torch.manual_seed(1)
<torch._C.Generator at 0x19efbde65d0>
x_train = torch.FloatTensor([[1], [2], [3]])
y_train = torch.FloatTensor([[2], [4], [6]])
model = LinearRegressionModel()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
nb_epochs = 2000
for epoch in range(nb_epochs+1):
prediction = model(x_train)
cost = F.mse_loss(prediction, y_train)
optimizer.zero_grad()
cost.backward()
optimizer.step()
if epoch % 200 == 0:
print('Epoch {:4d}/{} Cost: {:.6f}'.format(
epoch, nb_epochs, cost.item()
))
Epoch 0/2000 Cost: 13.103541
Epoch 200/2000 Cost: 0.001724
Epoch 400/2000 Cost: 0.000658
Epoch 600/2000 Cost: 0.000251
Epoch 800/2000 Cost: 0.000096
Epoch 1000/2000 Cost: 0.000037
Epoch 1200/2000 Cost: 0.000014
Epoch 1400/2000 Cost: 0.000005
Epoch 1600/2000 Cost: 0.000002
Epoch 1800/2000 Cost: 0.000001
Epoch 2000/2000 Cost: 0.000000
2. 다중 선형회귀 클래스로 구현하기
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(1)
<torch._C.Generator at 0x19efbde65d0>
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]])
class MultivariateLinearRegressionModel(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(3, 1)
def forward(self, x):
return self.linear(x)
model = MultivariateLinearRegressionModel()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-5)
nb_epochs = 2000
for epoch in range(nb_epochs+1):
prediction = model(x_train)
cost = F.mse_loss(prediction, y_train)
optimizer.zero_grad()
cost.backward()
optimizer.step()
if epoch % 200 == 0:
print('Epoch {:4d}/{} Cost: {:.6f}'.format(
epoch, nb_epochs, cost.item()
))
Epoch 0/2000 Cost: 31667.599609
Epoch 200/2000 Cost: 0.223911
Epoch 400/2000 Cost: 0.220059
Epoch 600/2000 Cost: 0.216575
Epoch 800/2000 Cost: 0.213413
Epoch 1000/2000 Cost: 0.210559
Epoch 1200/2000 Cost: 0.207967
Epoch 1400/2000 Cost: 0.205618
Epoch 1600/2000 Cost: 0.203481
Epoch 1800/2000 Cost: 0.201539
Epoch 2000/2000 Cost: 0.199770