代码不收敛香草梯度下降

Code Not Converging Vanilla Gradient Descent

我有一个特定的分析梯度用于计算成本 f(x,y),以及梯度 dx 和 dy。它运行,但我无法判断我的梯度下降是否被破坏。我应该绘制偏导数 x 和 y 吗?

import math

gamma = 0.00001 # learning rate
iterations = 10000 #steps
theta = np.array([0,5]) #starting value
thetas = []
costs = []

# calculate cost of any point
def cost(theta):
    x = theta[0]
    y = theta[1]
    return 100*x*math.exp(-0.5*x*x+0.5*x-0.5*y*y-y+math.pi)

def gradient(theta):
    x = theta[0]
    y = theta[1]
    dx = 100*math.exp(-0.5*x*x+0.5*x-0.0035*y*y-y+math.pi)*(1+x*(-x + 0.5))
    dy = 100*x*math.exp(-0.5*x*x+0.5*x-0.05*y*y-y+math.pi)*(-y-1)
    gradients = np.array([dx,dy])
    return gradients

#for 2 features
for step in range(iterations):
    theta = theta - gamma*gradient(theta)
    value = cost(theta)
    thetas.append(theta)
    costs.append(value)

thetas = np.array(thetas)
X = thetas[:,0]
Y = thetas[:,1]
Z = np.array(costs)

iterations = [num for num in range(iterations)]

plt.plot(Z)
plt.xlabel("num. iteration")
plt.ylabel("cost")

我强烈建议您首先根据数值梯度对其进行评估,以检查您的分析梯度是否正常工作。 即确保你的 f'(x) = (f(x+h) - f(x)) / h 对于一些小的 h.

之后,通过选择一个您知道 x 或 y 应该减小的点,然后检查梯度函数输出的符号,确保您的更新实际上是在正确的方向上。

当然要确保你的目标实际上是最小化与最大化。