Python梯度下降 - 成本不断增加

时间:2016-09-29 13:00:52

标签: python numpy machine-learning regression gradient-descent

我正在尝试在python中实现梯度下降,并且每次迭代时我的损失/成本都会不断增加。

我见过一些人发布此事,并在此处看到了答案: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

我在网上找到的数据集(洛杉矶心脏数据)上对此进行了测试: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))

Gradient descent:

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)

计算成本:

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)

2 个答案:

答案 0 :(得分:3)

假设您的渐变推导是正确的,您使用的是:=-,您应该使用:-=。您需要将其重新分配给theta

,而不是更新- (alpha * gradient)

编辑(在代码中修复了上述问题后):

我运行了我认为是正确数据集的代码,并且能够通过设置alpha=1e-7来获得行为成本。如果你为1e6次迭代运行它,你应该看到它收敛。此数据集上的此方法似乎对学习率非常敏感。

答案 1 :(得分:2)

一般情况下,如果您的费用增加,那么您应该检查的第一件事是查看您的学习率是否过高。在这种情况下,速率导致成本函数跳过最佳值并向上增加到无穷大。尝试不同的小学习率。当我面对你描述的问题时,我通常会反复尝试学习率的1/10,直到找到J(w)减少的速率。

另一个问题可能是您的衍生实施中的错误。一种好的调试方法是进行梯度检查,以比较分析梯度和数值梯度。

相关问题