import matplotlib.pyplot as plt
import numpy as np
def fx(x):
return x**2
def gradient_descent():
times = 10
alpha = 0.1
x =12
x_axis = np.linspace(-12, 12)
fig = plt.figure(1,figsize=(6,6))
ax = fig.add_subplot(1,1,1)
ax.set_xlabel(‘X’, fontsize=14)
ax.set_ylabel(‘Y’, fontsize=14)
ax.plot(x_axis,fx(x_axis))
for i in range(times):
x1 = x
y1= fx(x)
print("第%d次迭代:x=%f,y=%f" % (i + 1, x, y1))
x = x - alpha * 2 * x
y = fx(x)
ax.plot([x1,x], [y1,y], 'ko', lw=1, ls='-', color='red')
plt.show()
if name == “main”:
gradient_descent()