import math
import matplotlib.pyplot as plt
import numpy
def dj(theta):
return 2*(theta-2.5)#这里返回theta对应的导数,而函数求导是手动进行的
def j(theta):
return (x-2.5)**2-1
def __name__=="__main__":#定义程序的入口
x=np.linspace(-1,6,141)
y=(x-2.5)**2-1#定义一个二次函数,然后用于梯度下降法求值
eta=0.1#这个是学习率
theta=0.0#第一个点
episilon=1e-8
while True:
gradient=dj(theta)
last_theta=theta
theta-=gradient*eta#对theta进行更新
if abs(j(theta)-j(last_theta)<episilon):#如果小于一个阈值,那么就退出
break
print(theta)
print(j(theta))
另外一个实现的方案,但是我并不知道对不对
def __name__="__main__":#这个实现效果和上面的几乎一样好
theta=0.0
learn_rate=0.1
for i in range(10000):
temp=math.sqrt(learn_rate**2/(dj(theta)**2+1))
if temp<0:
theta+=temp
else: theta-=temp
print(theta)