视频讲解链接:3.1梯度下降法求最小值_哔哩哔哩_bilibili
# 利用梯度下降法求最小值
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
lr = 0.1 # 学习率
epoches = 20 # 迭代次数
x = 5 # 初始值
y = x**2 # 目标损失函数
x_list = [] # 记录每次迭代的x值, 放到list里面
y_list = [] # 记录每次迭代的y值, 放到list里面
x_list.append(x)
y_list.append(y)
print(f'第0次初始值, x = {x}, y=x**2={y}')
#梯度下降求解量小值
for i in range(epoches):
i = i + 1
x = x - lr * 2 * x
y = x**2
x_list.append(x)
y_list.append(y)
print(f'第{i}次迭代,x = x - lr * 2 * x={x:.4f},y=x**2={y:.4f}')
# 下面是动画展示
fig, ax = plt.subplots()
plt.xlabel('x轴', fontsize=10)
plt.ylabel('y轴', fontsize=10)
circle = plt.Circle((5, 25), 0.2, fc='r')
text = [f'第{i}次迭代x={x_list[i]:.4f},y={y_list[i]:.4f}' for i in range(21)]
def init():
ax.set_xlim(-5, 5)
ax.set_ylim(-0, 25)
ax.text(4.5, 25, "初始值x=5,y=25")
ax.add_artist(circle)
return circle,
def animate(i):
x = x_list[i]
y = y_list[i]
txt = ax.text(x-2, y+1, text[i])
circle.center = (x, y)
return circle,txt,
x1 = np.array([-5, -4.5, -4, -3.5, -3, -2.5, -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5])
y1 = np.array(x1**2)
plt.plot(x1, y1) # 画抛物线
animation = FuncAnimation(fig, animate, init_func=init, frames=21, interval=2000, blit=True, repeat=False) # 画动画
plt.show()