1.梯度下降法
首先梯度下降法不是一个机器学习算法,而是一种基于搜索的最优化方法。它的作用是最小化一个损失函数。梯度上升法则是最大化一个效用函数。
导数可以代表J 增大的方向,如上图一点导数为负值,说明J增大的方向是沿着X轴负方向。
代表移动的步长,一直移动到导数为0.
模拟梯度下降法:
"""模拟梯度下降法"""
import numpy as np
import matplotlib.pyplot as plt
plot_x = np.linspace(-1, 6, 141)
plot_y = (plot_x - 2.5) ** 2 - 1
plt.plot(plot_x, plot_y)
plt.show()
def dJ(theta):
"""计算导数值"""
return 2 * (theta - 2.5)
def J(theta):
"""计算损失函数的值"""
return (theta - 2.5) ** 2 - 1
theta = 0.0
theta_history = [theta]
def gradient_descent(initial_theta,eta,epsilon=1e-8):
"""模拟梯度下降法"""
theta=initial_theta
theta_history.append(i