ํ๊ท: ํ๋ ํน์ ์ฌ๋ฌ ๊ฐ์ ๋ ๋ฆฝ๋ณ์์ ํ ๊ฐ์ ์ข ์๋ณ์ ๊ฐ์ ์๊ด๊ด๊ณ๋ฅผ ๋ชจ๋ธ๋งํ๋ ๊ธฐ๋ฒ
์ ํํ๊ท: ํ์ต ๋ฐ์ดํฐ๋ฅผ ํตํด ์ด๋ค ์์์ ์ ์ด ํ๋ฉด ์์ ๊ทธ๋ ค์ก์ ๋ ์ต์ ์ ์ ํ ๋ชจ๋ธ์ ์ฐพ๋ ๊ฒ์ ๋ชฉํ๋ก ํจ.
๋จ์ ์ ํ ํ๊ท๋ถ์
๊ฒ์ ์ : ๋ชจ์ง๋จ์ ๋ชจ๋ ๋ฐ์ดํฐ / ๋นจ๊ฐ ์ : ํ์ต์งํฉ์ ๋ฐ์ดํฐ
(๋ชจ์ง๋จ์ ๋ชจ๋ ๋ฐ์ดํฐ ๋ถ์ ์ด๋ ค์, ํ์ต์งํฉ ๋ถ์ ํ ์์ฐจ๋ฅผ ํตํด ์ถ์ )
์ต์ ์ ํ๊ท ๋ชจ๋ธ: ์ ์ฒด ๋ฐ์ดํฐ์ ์์ฐจ(์ค๋ฅ๊ฐ)์ ํฉ์ด ์ต์๊ฐ ๋๋ ๋ชจ๋ธ
-> ์ค๋ฅ๊ฐ์ด ์ต์๊ฐ ๋๋ ํ๊ท๊ณ์(์ ํธ, ๊ธฐ์ธ๊ธฐ) ์ฐพ๊ธฐ
์์ฐจ์ ์ ๊ณฑํฉ(SSE; Error Sum of Squares)
์์ฐจ์ ์ ๊ณฑํฉ์ ์ต์ํํ๋ ์ด์ :
1) ์์ฐจ์ ํฉ์ด 0์ด ๋๋ ํด๋ ๋ฌด์ํ ๋ง์ (์ ์ผํ ํด X)
2) ์์ฐจ์ ์ ๋๊ฐ์ ํฉ์ ๋ฏธ๋ถ ๋ถ๊ฐ๋ฅ
3) ์์ฐจ์ ์ ๊ณฑํฉ -> ์ ์ผํ ํดO, ๋ฏธ๋ถ ๊ฐ๋ฅO
import numpy as np
import matplotlib.pyplot as plt
%matplotlib.inline
np.random.seed(0)
X = 2 * np.random.rand(100, 1)
y = 6 + 4 * X + np.random.randn(100,1) # ๋
ธ์ด์ฆ ์์ฑ์ ์ํด random๊ฐ ์ถ๊ฐ
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) # y=w0+w1X1(์ฆ, ๋ฒกํฐ์ ๊ธธ์ด)
# ๋จผ์ 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 # dot ์ฐ์ฐ ์, y = ax+b ax->np.dot(X,w1.T)
diff = y-y_pred # error function = (์ค์ ๊ฐ - ์์ธก๊ฐ)
# w0_update๋ฅผ 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)) # error ftn : mse(mean square error)
#/summation_i^n (y-y_hat)(-x_i)
w0_update = -(2/N)*learning_rate*(np.dot(w0_factors.T, diff)) # summation_i^n (y-y_hat)(-x_1)
return w1_update, w0_update #W_0,W_1 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 # new = old - update (update = 0->new =old )
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
print(cost) # root(์ค์ ๊ฐ-์์ธก๊ฐ) ํฉ์ฐํด์ ์ ์ฅ-> cost
return cost
w1, w0 = gradient_descent_steps(X, y, iters=1000) #1000๋ฒ ๋ฐ๋ณต
#์ต์ ์ ๊ฐ๊ณผ ๊ทธ๋์ cost๊ฐ ์ถ๋ ฅ
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)))
plt.scatter(X, y)
plt.plot(X,y_pred)