파이썬 회귀분석

#실제값을 y = 4x + 6 시뮬레이션하는 데이터 값 생성
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

np.random.seed(0)
# y = 4x + 6 식을 근사(w1 = 4, w0= 6). random값은 noise를 위해 만듦
X = 2 * np.random.rand(100,1)
y = 6 + 4 * X + np.random.randn(100,1)

# x, y 데이터 셋 scatter plot으로 시각화
plt.scatter(X,y)

# w1과 w0를 업데이트 할 w1_update, w0_update를 반환
def get_weight_updates(w1, w0, X, y, learning_rate=0.01):
    N = len(y)
    #먼저 w1_update, w0_update를 각각 w1, w0의 shape와 동일한 크기를 가진 0값으로 초기화
    w1_update = np.zeros_like(w1);
    w0_update = np.zeros_like(w0);
    # 예측 배열 계산하고 예측과 실제값의 차이 계산
    y_pred = np.dot(X,w1.T) + w0
    diff = y-y_pred
    # w0_updte를 dot 행렬 연산으로 구하기 위해 모두 1값을 가진 행렬 생성
    w0_factors = np.ones((N,1))
    #w1과 w0를 업데이트 할 w1_update와 w0_update계산
    w1_update = -(2/N)*learning_rate*(np.dot(X.T, diff))
    w0_update = -(2/N)*learning_rate*(np.dot(w0_factors.T, diff))
    
    return w1_update, w0_update

# 입력 인자 iters로 주어진 횟수 만큼 반복적으로 w1과 w0를 업데이트 적용함
def gradient_descent_steps(X, y, iters=10000):
    #w0과 w1을 모두 0으로 초기화
    w0 = np.zeros((1,1))
    w1 = np.zeros((1,1))
    #인자로 주어진 iters만큼 반복적으로 get_weight_updates()로출하여 w1, w0 업데이트 수행
    for ind in range(iters):
        w1_update, w0_update = get_weight_updates(w1,w0, X, y, learning_rate=0.01)
        w1 = w1 - w1_update
        w0 = w0 - w0_update
    return w1, w0

def get_cost(y, y_pred):
    N = len(y)
    cost = np.sum(np.square(y - y_pred))/N
    return cost

w1, w0 = gradient_descent_steps(X, y, iters=1000)
print("w1:{0:.3f} w0:{1:.3f}".format(w1[0,0], w0[0,0]))
y_pred = w1[0,0] * X + w0
print('Gradient Descent Total Cost: {0:.4f}'.format(get_cost(y,y_pred)))

 

'빅데이터 & 인공지능' 카테고리의 다른 글

Apache Spark  (0) 2022.02.21
MPP(Massivly Parallel Processing Database)  (0) 2022.02.21
ADP는 무슨 약자일까?  (0) 2021.04.08
스태킹형 스위치(L2)  (0) 2020.05.27
VRRP(Virtual Router Redundancy Protocol)  (0) 2020.05.27