pytorch 기반 논리 회귀 코드

from torch import nn
from torch import optim as optimizer
import torch
from torch.autograd import Variable

class LogisticRegression(nn.Module):
    def __init__(self):
        super(LogisticRegression, self).__init__()
        self.lr = nn.Linear(2, 1)
        self.sm = nn.Sigmoid()
    def forward(self, x):
        x = self.lr(x)
        x = self.sm(x)
        return x

model = LogisticRegression()

x = Variable(torch.Tensor([[1.2, 1.3], [1.1, 1.9], [2.1, 2.8], [1.0, 1.0], [1.0, 2.0], [2.0, 2.0], [4.1, 4.1], [4.2, 4.5], [5.1, 4.6], [4.0, 4.0], [4.0, 5.0], [5.0, 4.1]]))
y = Variable(torch.Tensor([[1.0], [1.0], [1.0], [1.0], [1.0], [1.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0]]))

criterion = nn.BCELoss()
optimizer = optimizer.SGD(model.parameters(), lr=1e-3, momentum=0.9)

for epoch in range(1000):
    out = model(x)
    loss = criterion(out, y)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    print(loss)

result = model(Variable(torch.Tensor([[4.0, 5.2], [1.0, 2.0]]))).data.numpy()

class_result = []
for i in range(0, len(result)):
    if result[i] >= 0.5:
        class_result.append(1)
    else:
        class_result.append(0)

print(class_result)



좋은 웹페이지 즐겨찾기