파이썬에서 매우 순진한 그라디언트 디센트를 구현하려고합니다. 그러나 무한 루프가되는 것처럼 보입니다. 디버깅을 도와 주시겠습니까?Python에서 순진한 그라디언트 디센트 구현하기
y = lambda x : x**2
dy_dx = lambda x : 2*x
def gradient_descent(function,derivative,initial_guess):
optimum = initial_guess
while derivative(optimum) != 0:
optimum = optimum - derivative(optimum)
else:
return optimum
gradient_descent(y,dy_dx,5)
편집 :
지금이 코드를 가지고, 난 정말 출력을 이해할 수 없다. 추신. CPU가 정지 될 수 있습니다.
Output of gradient descent code below
import matplotlib.pyplot as plt
def stepGradient(x,y, step):
b_current = 0
m_current = 0
b_gradient = 0
m_gradient = 0
N = int(len(x))
for i in range(0, N):
b_gradient += -(1/N) * (y[i] - ((m_current*x[i]) + b_current))
m_gradient += -(1/N) * x[i] * (y[i] - ((m_current * x[i]) + b_current))
while abs(b_gradient) > 0.01 and abs(m_gradient) > 0.01:
b_current = b_current - (step * b_gradient)
m_current = m_current - (step * m_gradient)
for i in range(0, N):
b_gradient += -(1/N) * (y[i] - ((m_current*x[i]) + b_current))
m_gradient += -(1/N) * x[i] * (y[i] - ((m_current * x[i]) + b_current))
return [b_current, m_current]
x = [1,2, 2,3,4,5,7,8]
y = [1.5,3,1,3,2,5,6,7]
step = 0.00001
(b,m) = stepGradient(x,y,step)
plt.scatter(x,y)
abline_values = [m * i + b for i in x]
plt.plot(x, abline_values, 'b')
plt.show()
고정 :
y = lambda x : x**2
dy_dx = lambda x : 2*x
def gradient_descent(function,derivative,initial_guess):
optimum = initial_guess
while abs(derivative(optimum)) > 0.01:
optimum = optimum - 2*derivative(optimum)
print((optimum,derivative(optimum)))
else:
return optimum
gradient_descent(y,dy_dx,5)
는 지금은 아래 출력과 같이 그러나 출력이 올바른 것으로 표시되지 않습니다, 회귀 문제에 적용하기 위해 노력하고있어 : D
import matplotlib.pyplot as plt
def stepGradient(x,y):
step = 0.001
b_current = 0
m_current = 0
b_gradient = 0
m_gradient = 0
N = int(len(x))
for i in range(0, N):
b_gradient += -(1/N) * (y[i] - ((m_current*x[i]) + b_current))
m_gradient += -(1/N) * x[i] * (y[i] - ((m_current * x[i]) + b_current))
while abs(b_gradient) > 0.01 or abs(m_gradient) > 0.01:
b_current = b_current - (step * b_gradient)
m_current = m_current - (step * m_gradient)
b_gradient= 0
m_gradient = 0
for i in range(0, N):
b_gradient += -(1/N) * (y[i] - ((m_current*x[i]) + b_current))
m_gradient += -(1/N) * x[i] * (y[i] - ((m_current * x[i]) + b_current))
return [b_current, m_current]
x = [1,2, 2,3,4,5,7,8,10]
y = [1.5,3,1,3,2,5,6,7,20]
(b,m) = stepGradient(x,y)
plt.scatter(x,y)
abline_values = [m * i + b for i in x]
plt.plot(x, abline_values, 'b')
plt.show()
그라데이션 하강이있는 것은 매우 거의 0의 파생에 도달 없다는 것입니다.그라디언트가 높을 때 프로세스가 잘 작동하지만 미세한 변화에 도달하면 프로세스가 최적의 지점을 돌고 있음을 알 수 있습니다. while 루프에 한계를 쓰거나 파생 값을 0.0001과 같은 작은 엡실론 값보다 크게 만드십시오. –
"출력이 올바르지 않습니다"라는 것은 무엇을 의미합니까? 예상 출력과 실제로 얻은 출력 (콘솔 출력, 역 추적, 그래프 플롯 등)을 표시하십시오. 귀하가 제공하는 상세 정보가 많을수록 귀하가받을 확률이 높습니다. [FAQ] (http://stackoverflow.com/tour) 및 [How to Ask] (http://stackoverflow.com/help/how-to-ask)를 확인하십시오. –