경사 하강법(실습) :: 딥러닝 기초 - mindscale
Skip to content

경사 하강법(실습)

경사 하강법

%matplotlib inline

import numpy
import matplotlib.pyplot as plt

2차 함수에서 최소가 되는 점을 찾아보자

x = numpy.arange(-10, 10, 0.01)

def quad_f(x):
    return x ** 2

plt.plot(x, quad_f(x))
def d_f(x):
    return 2*x

precision = 0.01

temp_x = 8
old_x = 15
lr = 0.1

mins = [8]

while abs(temp_x - old_x) > precision:
    gradient = d_f(temp_x) 
    move = gradient * lr
    old_x = temp_x
    temp_x = temp_x - move
    mins.append(temp_x)

print("Local minimum occurs at {}.".format(round(temp_x,2)))

y가 최소가 되는 x(x = 0)에 근접했음을 알 수 있다 (Local minimum occurs at 0.04.)

plt.plot(x, quad_f(x), mins, quad_f(numpy.array(mins)), 'rs')