代码:
# -*-coding: utf-8 -*一
_author_=' zengxin. '
_date_ ='2023/8/16 上午9:50'
_product_='PyCharm'
_filename_ ='gradient.descent.py'
#插包
import numpy as np
import matplotlib as plt
import matplotlib.pyplot as plt
# 构建元素图像
def f1(x):
return 0.5*(x-0.25)**2
def h(x):
return 0.5*2*(x-0.25)
# 梯度下降法
GD_x =[]
GD_y =[]
x = 2
alpha = 0.5
f_change = f1(x)
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 * h(x)
temp = f1(x)
f_change = np.abs(f_current - temp)
f_current = temp
GD_x.append(x)
GD_y.append(f_current)
print(u'结果:(%.5f, %.5f)' %(x,f_current))
print(u'迭代次数(%.5f)'%(iter_num ))
print(GD_x)
# 构建数据
x = np.arange(-4,4.5,0.05)
y = np.arange(list(map(lambda t: f1(t),x)))
# 作图
plt.figure(facecolor='w')
plt.plot(x,y,'b-',linewidth='3')
plt.plot(GD_x,y,'r-',linewidth='3')
plt.title(u'函数 0.5*(x-0.25)^2$\n 学习率:(%.3f) 最优解:(%.3f, %.3f) 迭代次数:%.3d' %(alpha,x,f_current,iter_num))
plt.show()
报错内容: