0
点赞
收藏
分享

微信扫一扫

吴恩达机器学习-迭代法代码实现

工程与房产肖律师 2022-04-13 阅读 36
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.family']= 'sans-serif'
mpl.rcParams['font.sans-serif'] = 'SimHei'
mpl.rcParams['axes.unicode_minus'] = False
# 构建一维元素图像
def f1(x):
    return 0.5*(x-0.25)**2
# 一维导数
def h1(x):
    return 0.5*2*(x-0.25)
# 使用梯度下降进行解答
GD_X=[]
GD_Y=[]
# 初始值
x=4
# 超参
alpha=0.7
# 表示y的变化后
f_change=f1(x)
# 表示y现在的值
f_current=f_change
GD_X.append(x)
GD_Y.append(f_current)
# 迭代次数
iter_num=0
while f_change>1e-10 and iter_num<100:
    iter_num+=1
    x=x-alpha*h1(x)
    tmp=f1(x)
    # 判断y的变化 不能太小
    f_change=np.abs(f_current-tmp)
    f_current=tmp
    GD_X.append(x)
    GD_Y.append(f_current)
print('最终的结果是:(%.5f,%.5f)'%(x,f_current))
print('迭代次数是:%d'%iter_num)
print(GD_X)

# 构建数据
X=np.arange(-4,4.5,0.05)
Y=np.array(list(map(lambda t:f1(t),X)))
plt.figure(facecolor='w')
plt.plot(X,Y,'r-',linewidth=2)
plt.plot(GD_X,GD_Y,'bo--',linewidth=2)
plt.title('函数$y=0.5*(x-0.25)^2$;\n学习率:%.3f;最终解:(%.3f,%.3f);迭代次数:%d'%(alpha,x,f_current,iter_num))
plt.show()

结果展示:

 

 

举报

相关推荐

0 条评论