问题描述 : 求 y=(x+5)² 的最小值,x从3开始。
我们知道当x=-5时,y=0是最小值,现在我们通过梯度下降来实现这个过程。
步骤1:初始化时从x=3开始,求出导数函数,dy/dx = 2*(x+5).
步骤2:向梯度下降方向移动,考虑如何移动,比如下没有台阶的楼梯,楼梯的斜率(倾斜度)是多少?每一步的步长是多少?我们假设斜率即learning rate→ 0.01.
步骤3:开始执行步骤2的迭代过程:
初始化参数:
迭代1:
迭代2:
步骤4:我们可以获得x的值,越来越慢,直到x=-5.那么我们需要迭代多少次呢?
python实现:
步骤1:初始化
cur_x = 3 # The algorithm starts at x=3
rate = 0.01 # Learning rate
precision = 0.000001 #This tells us when to stop the algorithm
previous_step_size = 1 #
max_iters = 10000 # maximum number of iterations
iters = 0 #iteration counter
df = lambda x: 2*(x+5) #Gradient of our function
步骤2:执行梯度下降循环:
while previous_step_size > precision and iters < max_iters:
prev_x = cur_x #Store current x value in prev_x
cur_x = cur_x - rate * df(prev_x) #Grad descent
previous_step_size = abs(cur_x - prev_x) #Change in x
iters = iters+1 #iteration count
print("Iteration",iters,"\nX value is",cur_x) #Print iterations
print("The local minimum occurs at", cur_x)
步骤3:
最终执行的情况
Iteration 594
X value is -4.999950866358997
Iteration 595
X value is -4.9999518490318176
The local minimum occurs at -4.9999518490318176
Process finished with exit code 0