Я пытаюсь реализовать градиентный спуск в python, и моя потеря/стоимость увеличивается с каждой итерацией.Python gradient descent - стоимость продолжает расти
Я видел несколько человека, пост об этом, и увидел ответ здесь: gradient descent using python and numpy
Я считаю, что моя реализация похожа, но не могу видеть, что я делаю неправильно, чтобы получить взрывающееся значение стоимости:
Iteration: 1 | Cost: 697361.660000
Iteration: 2 | Cost: 42325117406694536.000000
Iteration: 3 | Cost: 2582619233752172973298548736.000000
Iteration: 4 | Cost: 157587870187822131053636619678439702528.000000
Iteration: 5 | Cost: 9615794890267613993157742129590663647488278265856.000000
Я проверяю это на наборе данных я нашел в Интернете (LA Data Сердце): http://www.umass.edu/statdata/statdata/stat-corr.html
Импорт код:
dataset = np.genfromtxt('heart.csv', delimiter=",")
x = dataset[:]
x = np.insert(x,0,1,axis=1) # Add 1's for bias
y = dataset[:,6]
y = np.reshape(y, (y.shape[0],1))
Градиентный спуск: стоимость
def gradientDescent(weights, X, Y, iterations = 1000, alpha = 0.01):
theta = weights
m = Y.shape[0]
cost_history = []
for i in xrange(iterations):
residuals, cost = calculateCost(theta, X, Y)
gradient = (float(1)/m) * np.dot(residuals.T, X).T
theta = theta - (alpha * gradient)
# Store the cost for this iteration
cost_history.append(cost)
print "Iteration: %d | Cost: %f" % (i+1, cost)
Calculate:
def calculateCost(weights, X, Y):
m = Y.shape[0]
residuals = h(weights, X) - Y
squared_error = np.dot(residuals.T, residuals)
return residuals, float(1)/(2*m) * squared_error
Рассчитайте гипотеза:
def h(weights, X):
return np.dot(X, weights)
Чтобы реально запустить его:
gradientDescent(np.ones((x.shape[1],1)), x, y, 5)
Мое лучшее решение - тривиальные проблемы с подписанием, потому что кажется, что оно идет в неправильном направлении. –