Python/Python기초

Python 53_ 선형 회귀

Codezoy 2020. 2. 3. 18:44






선형 회귀(Linear Regression)
모델 y = ax + b에서, 기울기(slope) a와 y절편 b를 찾는 문제.

(a, b)를 특정 값으로 가정했을 때의 예상값과 실제값 사이의 오차들의
제곱의 합을 최소로 하는 파라미터 a와 b를 찾는 문제임.

실제값: (x, y)
예상값: y_hat = theta1 * x + theta2
오차: e = y_hat - y = theta1 * x + theta2 - y
오차 제곱: f = e**2 = (theta1 * x + theta2 - y)**2
기울기 theta1에 대한 편미분: df/dt1 ~ e * x
y절편 theta2에 대한 편미분: df/dt2 ~ e

1) 확률적 경사 하강법(Stochastic Gradient Descent)
2) 배치 경사 하강법(Batch GD)
3) 미니 배치 경사 하강법(Mini-batch GD)

def linear_gradient(x, y, theta):
     """
     특정 데이터 (x, y)에서 기울기와 y절편에 대한 편미분 벡터 리턴
     :param x: 실제 데이터
     :param y: 실제 데이터
     :param theta: [theta1, theta2] 벡터(리스트). [기울기, y절편]
     :return:
     """
     slope, intersect = theta
     y_hat = slope * x + intersect # 예상 값
     error = y_hat - y # 오차
     # error**2을 최소화하는 slope(기울기), intersect(절편) 찾기
     # 점(x,y)에서 [기울기에 대한 편미분, 절편에 대한 편미분]
     gradient = [error * x, error]
     return gradient