作用:最小化一个损失函数
import numpy as npimport matplotlib.pyplot as pltplot_x = np.linspace(-1, 6, 141)plot_y = (plot_x - 2.5) ** 2 -1plt.plot(plot_x, plot_y)

def Dj(theta): return 2 * (theta - 2.5)def J(theta): return (theta - 2.5) ** 2 - 1theta = 0.0eta = 0.1theta_history = []while True: gradient = Dj(theta) last_theat = theta theta = theta - eta * gradient theta_history.append(theta) if abs(J(theta) - J(last_theat)) < 1e-8: breakprint(theta)print(J(theta))plt.plot(plot_x, J(plot_x))plt.scatter(np.array(theta_history), J(np.array(theta_history)), color='r')
