梯度下降实际就是导数值下降 。
梯度下降算法是一个方法,是帮助我们找极值点的方法cost
接下来用Python实现最土的梯度下降算法,
#首先引入numpy模块和图形界面模块
import matplotlib.pyplot as plt
import numpy as np
#定义三个函数 一个数目标函数 一个是对目标函数x1求一次导数和x2求一次导数
def targetFunc(x1, x2):
return (x1+x2)**2
pass
def gradientFunc(x1, x2):
a = 2 * x1 + 2*x2 + x2**2,
return a
pass
def gradientFunc2(x1,x2):
b = 2*x2 + 2*x1 + x1**2
return b
pass
listx = []
#猜测的过程 猜的值 目标函数 梯度函数 步进系数 收敛条件
def gradientCal(initX1, initX2, targetFunc, gradientFunc, rating=0.01, tolent=0.000001, times = 500000):
result = targetFunc(initX1,initX2) #计算出initX1,initX2这个点的实际值
listx.append((initX1, initX2))
newX1 = initX1 - rating * gradientFunc(initX1,initX2)
newX2 = initX2 - rating * gradientFunc2(initX1,initX2)
newResult = targetFunc(newX1, newX2)
reResult = np.abs(result - newResult)
t = 0
while reResult > tolent and t < times:
t += 1
initX1 = newX1
initX2 = newX2
result = newResult
listx.append((initX1,initX2))
newX1 = newX1 - rating*gradientFunc(newX1,newX2) #不断更新新的点根据步进系数
newX2 = newX2 - rating*gradientFunc2(newX2,newX1)
newResult1 = targetFunc(newX1,newX2)
reResult = np.abs(result - newResult)
pass
return initX1, initX2
pass
if __name__ == '__main__':
print(gradientCal(10, 10, targetFunc, gradientFunc2))
x1 = np.arange(-10, 10+1, 1)
x2 = np.arange(-10, 10+1, 1)
y = (x1+x2)**2
plt.plot(x1, y)
plt.plot(x2, y)
plt.grid(linestyle='--')
plt.scatter(np.array(listx), (np.array(listx)**2), s=20)
plt.show()
print(listx)
pass