作用:最小化一个损失函数

  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. plt.plot(plot_x, plot_y)

image.png

  1. def Dj(theta):
  2. return 2 * (theta - 2.5)
  3. def J(theta):
  4. return (theta - 2.5) ** 2 - 1
  5. theta = 0.0
  6. eta = 0.1
  7. theta_history = []
  8. while True:
  9. gradient = Dj(theta)
  10. last_theat = theta
  11. theta = theta - eta * gradient
  12. theta_history.append(theta)
  13. if abs(J(theta) - J(last_theat)) < 1e-8:
  14. break
  15. print(theta)
  16. print(J(theta))
  17. plt.plot(plot_x, J(plot_x))
  18. plt.scatter(np.array(theta_history), J(np.array(theta_history)), color='r')

image.png