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

Python,深度学习,梯度下降法示例,python,gradient,Python,Gradient,我正在学习梯度下降法方法,从零开始深入学习。在本书的示例中,有一些代码很难理解。这是代码 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)

我正在学习
梯度下降法
方法,从零开始深入学习。在本书的示例中,有一些代码很难理解。这是代码

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\u hist.append(x)
更改为
x\u hist.append(x.copy())
,则可以解决此问题。
不幸的是,我不知道为什么这是不同的。有人能告诉我这两个词的区别吗?(对不起,是英语)

您的列表x\u hist包含了对x的引用,而不是值。因此,通过x_hist.append(x.copy())更正它是一个好方法。

这将帮助您: