Created
March 11, 2017 05:02
-
-
Save oiehot/a930177cc51f202692fe0f9bb8f7d298 to your computer and use it in GitHub Desktop.
머신러닝, 수치미분, 편미분, 기울기, 경사하강법
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 머신러닝, 수치 미분, 편미분, 기울기gradient, 경사 하강법gradient descent | |
# 수치 미분numerical differentiation, 전방 차분 | |
def numerical_diff_bad(f, x): | |
h = 10e-50 # np.float32(1e-50) => 0.0, 반올림 오차 문제. | |
return (f(x+h) - f(x)) / h | |
# 수치 미분, 중심 차분 | |
def numerical_diff(f, x): | |
h = 1e-4 # 0.0001 | |
return (f(x+h) - f(x-h)) / (2*h) | |
# 기울기gradient | |
# 모든 변수의 편미분을 벡터로 정리한것. | |
# 편미분: 나머지 값들을 고정한 상태로 특정 축의 미분을 구함. | |
def numerical_gradient(f, x): | |
h = 1e-4 # 0.0001 | |
grad = np.zeros_like(x) # x와 같은 형태의 배열을 만든다. | |
# x0, x1, x2, ... | |
for i in range(x.size): | |
old = x[i] # 값 보존 | |
# x[i]의 편미분 구하기 | |
x[i] = old + h | |
r = f(x) | |
x[i] = old - h | |
l = f(x) | |
grad[i] = (r - l) / (2*h) | |
x[i] = old # 복원 | |
return grad | |
# 경사 하강법gradient descent | |
# 기울기gradient의 벡터를 따라 조금씩 이동하여 낮은 지점을 찾아가는 방법. | |
# 낮은 지점이란, 평가함수 결과값이 0에 가까운 곳으로, (머신 러닝의) 목표 지점이라고 볼 수 있다. | |
def gradient_descent(f, init_x, lr=0.01, step=100): | |
x = init_x | |
for i in range(step): | |
grad = numerical_gradient(f, x) | |
x -= lr * grad # lr: learning rate, 벡터의 이동 폭. | |
return x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment