梯度下降法原理及实现

梯度下降代表函数值减少速度最快的方向。当设定目标函数最小值时,只要朝着梯度下降的方向前进,就可以不断的逼近最优值

  1. #encoding=utf-8  
  2.   
  3. """ 
  4.     created on 2018-08-12 
  5.     @author wt 
  6. """  
  7.   
  8. """ 
  9.     利用随机梯度法,首先需要有一个函数,随便找一个函数f(x) = x^2-4*x+4,则f'(x)=2*x-4 
  10. """  
  11. import numpy as np  
  12. import matplotlib.pyplot as plt  
  13.   
  14.   
  15. def f(x):  
  16.     return x*x-4*x+4  
  17.   
  18. def f1(x):  
  19.     return 2*x-4  
  20.   
  21. def Grandient_Descent(start_x,learning_rate,f):  
  22.     x = start_x  
  23.     for i in range(20):  
  24.         grad = f(x)  
  25.         x -= grad*learning_rate  
  26.         print(i,grad,x)  
  27.         if abs(grad) < 1e-10:  
  28.             break  
  29.     return x  
  30.   
  31. Grandient_Descent(5,0.1,f)  
  32.   
  33. x = np.linspace(-10,13,1000)  
  34. y = f(x)  
  35. plt.plot(x,y)  
  36. plt.show()  
  37. 可以看出x不断的随着梯度值再下降
  38. 注意:随机梯度下降法中,步长设定值要小于安全步长,否则不论初始值等于多少,问题都会收敛不到最优值或者原地打转
  39. 例如:根据上面的公式: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

猜你喜欢

转载自blog.csdn.net/weixin_41362649/article/details/81605645