梯度下降代表函数值减少速度最快的方向。当设定目标函数最小值时,只要朝着梯度下降的方向前进,就可以不断的逼近最优值
#encoding=utf-8 """ created on 2018-08-12 @author wt """ """ 利用随机梯度法,首先需要有一个函数,随便找一个函数f(x) = x^2-4*x+4,则f'(x)=2*x-4 """ import numpy as np import matplotlib.pyplot as plt def f(x): return x*x-4*x+4 def f1(x): return 2*x-4 def Grandient_Descent(start_x,learning_rate,f): x = start_x for i in range(20): grad = f(x) x -= grad*learning_rate print(i,grad,x) if abs(grad) < 1e-10: break return x Grandient_Descent(5,0.1,f) x = np.linspace(-10,13,1000) y = f(x) plt.plot(x,y) plt.show() 可以看出x不断的随着梯度值再下降注意:随机梯度下降法中,步长设定值要小于安全步长,否则不论初始值等于多少,问题都会收敛不到最优值或者原地打转例如:根据上面的公式:x=5,f1(x)=6 -> x' = 5-6*step ,f1(x')=2*(5-6*step)-4 -> x'-f1(x')*step = x=5 求解y=1 安全步长为1