导包
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
构建数据集
# 定义函数
# f(x) = x**4 + x**3 + 5
f = lambda x:x**4 + x**3 + 5
x = np.linspace(-10,10,200)
y = f(x)
绘制图形
plt.plot(x,y)
对函数求导:
# 导数 :4*x**3 + 3*x**2
'''
4x**3 + 3x**2 = 0
x = 0 是一个解
4x + 3 = 0
x = -0.75
'''
d = lambda x :4*x**3 + 3*x**2
d(-7.5)
Out: -1518.75
定义精确度、步幅、训练次数:
# 精确度
precision = 0.0001
# 步幅
step = 0.005
# 训练次数
epoch = 1000
梯度下降法:
i = 0
# 起始值
start = 5
# 上一次迭代的旧值的记录
old = 0
while True:
if i > epoch:
break
old = start
start = start - d(start)*step
print('梯度下降多少次:%d,每次梯度下降求解的结果:%f'%(i,start))
if np.abs(start - old) < precision:
print(start - old)
break
i+=1
OUt:
梯度下降多少次:0,每次梯度下降求解的结果:2.125000
梯度下降多少次:1,每次梯度下降求解的结果:1.865352
梯度下降多少次:2,每次梯度下降求解的结果:1.683347
梯度下降多少次:3,每次梯度下降求解的结果:1.545442
梯度下降多少次:4,每次梯度下降求解的结果:1.435794
……
……
……
梯度下降多少次:638,每次梯度下降求解的结果:0.077820
梯度下降多少次:639,每次梯度下降求解的结果:0.077719
梯度下降多少次:640,每次梯度下降求解的结果:0.077619
-9.999334772965718e-05
法②
def gd(x_start,step,d,itera):
#x_start 起始点
#step 步长
#g 梯度
#itera 迭代次数
x = x_start
for i in range(itera):
grad = d(x)
x -= grad*step
print("Epoch{0}:grad={1},x={2}".format(i,grad,x))
if abs(grad)<1e-6:
break
return x
gd(5,0.005,d,1000)