[딥러닝] 02. Logistic regression : boolean operators

하늘·2024년 9월 30일

로지스틱 선형회귀

w : 가중치
x : 입력벡터
b : 편향
예측값을 시그모이드 함수에 입력하여 예측확률을 구한다.

경사하강법

비용함수를 최소화하기 위하여 경사하강법을 통해 w, b를 업데이트하고, 다시 비용함수를 구하는 과정을 반복하여 오차를 줄인다.

or 연산자

data preparation

import random
from math import exp, log 
X = [(0,0),(1,0),(0,1),(1,1)]
Y = [0,1,1,1]

model

class logistic_regression_model():
    def __init__(self): //생성자
        self.w = [random.random(), random.random()]
        self.b = random.random()
    def sigmoid(self,z): //sigmoid 메서드
        return 1/(1 + exp(-z))
    def predict(self,x): //predict 메서드
        z = self.w[0] * x[0] + self.w[1] * x[1] + self.b
        a = self.sigmoid(z)
        return a
model = logistic_regression_model()

training

def train(X, Y, model, lr = 0.01):
    dw0 = 0.0
    dw1 = 0.0
    db = 0.0
    m = len(X)
    cost = 0.0
    for x, y in zip(X, Y):
        a = model.predict(x)
        if y == 1:
            cost -= log(a)
        else:
            cost -= log(1-a)
        dw0 += (a-y)*x[0]
        dw1 += (a-y)*x[1]
        db += (a-y)
    cost /= m
    model.w[0] -= lr * dw0/m
    model.w[1] -= lr * dw1/m
    model.b -= lr*db/m

    return cost
for epoch in range(10000):
    cost = train(X,Y, model, 0.01)
    if epoch % 100==0:
        print(epoch, cost)

testing

model.predict((0,0))
model.predict((0,1))
model.predict((1,0))
model.predict((1,1))

and 연산자 또한 data preparation만 바꾸면 된다. 다만 xor 연산자의 경우 선형 회귀로 구현이 불가능하다. 비선형인 시그모이드 함수를 활성화 함수로 이용하여 다층퍼셉트론으로 해결할 수 있다.

0개의 댓글