通过梯度下降法求最小值

1.梯度下降是迭代法的一种,可以用于求解最小二乘问题(线性和非线性都可以)。在求解机器学习算法的模型参数,即无约束优化问题时,梯度下降(Gradient Descent)是最常采用的方法之一,另一种常用的方法是最小二乘法。在求解损失函数的最小值时,可以通过梯度下降法来一步步的迭代求解,得到最小化的损失函数和模型参数值。—来源于百度百科 2.给定初始值和步长,通过当前值与上一值的比较,不断进行迭代,直到符合设定的条件后停止。 3.下面是对f(x) = x * x,通过梯度下降法求最小值

import matplotlib.pyplot as plt

f = lambda x: x*x

fig, ax = plt.subplots()
def gradient_x(step,init_val):
    f_change, f_current = f(init_val), f(init_val)
    count = 0
    x = init_val
    while f_change > 0.0001:
        x = x - 2 * step * x
        f_change = f_current - f(x)
        f_current = f(x)
        count += 1
        plt.plot(x,f(x), "*-")
    print("after%diteration func found min value %d,x value is %d",count,f(x),x) 
    plt.show() 
if __name__ == '__main__':
    gradient_x(0.1, 2)

image