# 梯度下降法演示

``````# (x-2)**2 = 0
from tqdm import trange

epoch = 1000
lr = 0.09
x = 5  # 初始值, 凯明初始化, # 何凯明
label = 0

for e in trange(epoch):

pre = (x - 2) ** 2
loss = (pre - label) ** 2

delta_x = 2*(pre - label) * (x - 2)
x = x - delta_x * lr

print(x)
``````
``````100%|███████████████████████████████████████████████████| 1000/1000 [00:00<00:00, 386821.36it/s]
1.9474942856120552
``````

``````import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from tqdm import trange
from matplotlib.animation import PillowWriter

epoch = 1000
lr = 0.09
x = 5
label = 0

fig, ax = plt.subplots()
ax.set_xlim(0, epoch)
ax.set_ylim(0, 10)

x_data = []
y_data = []

line, = ax.plot([], [])

def update(frame):
global x
global y_data
global x_data

pre = (x-2) ** 2
loss = (pre - label) ** 2

delta_x = 2*(pre - label) * (x-2)
x = x - delta_x * lr

x_data.append(frame)
y_data.append(x)

line.set_data(x_data, y_data)

return line,

ani = FuncAnimation(fig, update, frames=trange(epoch), blit=True)

ax.set_xlabel('Epoch')
ax.set_ylabel('X')

writer = PillowWriter(fps=150)
ani.save('animation.gif', writer=writer)
``````

THE END