Python,深度学习,梯度下降方法示例

时间:2018-10-03 07:34:02

标签: python gradient

我正在通过从头开始深度学习研究gradient descent方法。在本书的示例中,有些代码很难理解。这是代码。

def gradient_descent(f, init_x, lr = 0.01, step_num = 100):
    x = init_x
    x_hist = []
    for i in range(step_num):
        x_hist.append(x) # plot with x_hist
        grad = numerical_gradient(f, x)
        x -= lr * grad
    return x, x_hist

def function_2(x):
    return x[0]**2 + x[1]**2

init_x = np.array([-3.0, 4.0])
x, x_hist = gradient_descent(function_2, init_x, lr = 0.1, step_num = 100)

我尝试绘制x_hist以查看'x'的减少。但是当我打印x_hist时,它是这样的。

x_hist
[array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10]),
array([-6.11110793e-10,  8.14814391e-10])]

如果我将x_hist.append(x)更改为x_hist.append(x.copy()),则可以解决此问题。 不幸的是,我不知道为什么会有所不同。谁能告诉我两者之间的区别?(对不起,英语)

1 个答案:

答案 0 :(得分:1)

您的列表x_hist包含对x的引用,而不是值。因此,通过x_hist.append(x.copy())对其进行纠正是一种好方法。