@leona1992
2022-07-31T14:44:34.000000Z
字数 479
阅读 244
python 梯度下降法

import numpy as npimport matplotlib.pyplot as pltplot_x = np.linspace(-1, 6, 141)plot_y = (plot_x - 2.5)**2 - 1def dJ(theta):return 2 * (theta - 2.5)def J(theta):return (theta - 2.5)**2 - 1eta = 0.1epsilon = 1e-8theta = 0theta_history = [theta]while True:gradient = dJ(theta)last_theta = thetatheta = theta - eta * gradienttheta_history.append(theta)if (abs(J(theta) - J(last_theta))) < epsilon:breakplt.plot(plot_x, plot_y)plt.plot(np.array(theta_history),J(np.array(theta_history)),color='r',marker='+')plt.show()