[关闭]
@leona1992 2022-07-31T14:44:34.000000Z 字数 479 阅读 105

梯度下降法1

python 梯度下降法


6.png-19.5kB

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. plot_x = np.linspace(-1, 6, 141)
  4. plot_y = (plot_x - 2.5)**2 - 1
  5. def dJ(theta):
  6. return 2 * (theta - 2.5)
  7. def J(theta):
  8. return (theta - 2.5)**2 - 1
  9. eta = 0.1
  10. epsilon = 1e-8
  11. theta = 0
  12. theta_history = [theta]
  13. while True:
  14. gradient = dJ(theta)
  15. last_theta = theta
  16. theta = theta - eta * gradient
  17. theta_history.append(theta)
  18. if (abs(J(theta) - J(last_theta))) < epsilon:
  19. break
  20. plt.plot(plot_x, plot_y)
  21. plt.plot(np.array(theta_history),
  22. J(np.array(theta_history)),
  23. color='r',
  24. marker='+')
  25. plt.show()
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注