梯度下降算法
一个变量如下:
# 梯度下降 == 导数值下降
import matplotlib.pyplot as plt
import numpy as np
#f(x) = x^2 #目标函数
#f`(x) = 2*x #梯度函数:一阶导数函数
# 梯度下降算法使一个方法,是帮助我们找到极值点的方法cost
def targetFunc(x):
return x ** 2
pass
def gradientFunc(x):
return 2 * x
# 猜测的过程
listx = []
def gradientCal(initX, targetFunc, gradientFunc, rating = 0.1, tolent=0.000001):
'''
:param initX: 猜测的点
:param targetFunc: 目标函数
:param gradientFunc: 梯度函数
:param rating: 步进系数
:param tolent: 收敛条件
:return: 返回极值点的x值
'''
result = targetFunc(initX) # 计算出initX这个点的实际值
gradientResult = gradientFunc(initX) # 计算出initX这个点的导数,也是斜率,梯度
listx.append(initX)
newX = initX - rating * gradientFunc(initX)
newResult = targetFunc(newX)
reResult = np.abs(result - newResult)
while reResult > tolent:
initX = newX
result = newResult
listx.append(initX)
newX = newX - rating * gradientFunc(newX)
newResult = targetFunc(newX)
reResult = np.abs(result - newResult)
return initX
pass
if __name__ == "__main__":
print(gradientCal(10, targetFunc, gradientFunc))
x = np.arange(-10, 10+1, 1)
y = x**2
plot = plt.figure()
plt.plot(x,y)
plt.grid(linestyle = '--')
plt.scatter(np.array(listx), np.array(listx)**2, s=20)
plt.show()
print(listx)
pass
运行结果如下:
两个变量
# 梯度下降 == 导数值下降
import matplotlib.pyplot as plt
import numpy as np
def targetFunc(x1, x2):
return (x1+x2)**2
pass
def gradientFunc1(x1, x2):
return 4*x1**2 + 4*x2**2
def gradientFunc2(x1, x2):
return 4*x2**2 + 4*x1**2
# 猜测的过程
listx = []
def gradientCal(x1, x2, target_Func, gradientFunc1, gradientFunc2, rating = 0.01, tolent=0.000001, times = 500):
target = target_Func(x1, x2)
listx.append((x1, x2))
new_x1 = x1 - rating * gradientFunc1(x1, x2)
new_x2 = x2 - rating * gradientFunc2(x1, x2)
new_Func = targetFunc(new_x1, new_x2)
re_target = np.abs(target - new_Func)
t = 0
while re_target > tolent and t < times:
t += 1
x1 = new_x1
x2 = new_x2
target = new_Func
listx.append((x1, x2))
new_x1 = new_x1 - rating * gradientFunc1(new_x1, new_x2)
new_x2 = new_x2 - rating * gradientFunc2(new_x2, new_x1)
new_Func = target_Func(new_x1, new_x2)
re_target = np.abs(target - new_Func)
pass
return new_x1, new_x2
pass
if __name__ == "__main__":
print(gradientCal(10, 10, targetFunc, gradientFunc1, gradientFunc2))
x1 = np.arange(-10, 101, 1)
x2 = np.arange(-10, 101, 1)
y = 2*(x1+x2)**2
plot = plt.figure()
plt.plot(x1,x2,y)
plt.grid(linestyle = '--')
plt.scatter(np.array(listx), np.array(listx)**2, s=20)
plt.show()
print(listx)
pass
运行结果如下: