Hello,我是kk~
今儿说说随机梯度下降!
随机梯度下降全称是:Stochastic Gradient Descent,简称SGD。
SGD 特别适用于大规模数据集和高维参数空间。它在每个训练样本上计算梯度并更新参数,以最小化损失函数。相比于批量梯度下降(Batch Gradient Descent),SGD更为高效,但也带来了一定的不稳定性。
SGD 计算流程:
初始化参数:选择初始参数值
。
随机选择一个样本
。
计算损失函数关于参数
的梯度
。
在参数空间中更新参数:
,其中
是学习率。
重复步骤 2-4 直到满足停止条件(例如达到最大迭代次数或损失函数收敛)。
下面咱们画一个三维图像,说明SGD的过程:
import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3D# 定义函数def f(x, y): return x**2 + y**2# 随机梯度下降def stochastic_gradient_descent(learning_rate=0.1, num_iterations=100): # 初始化参数 x = 2 * (np.random.random() - 0.5) y = 2 * (np.random.random() - 0.5) # 保存历史数据 history = [(x, y, f(x, y))] # 迭代更新 for _ in range(num_iterations): # 计算梯度 gradient_x = 2 * x gradient_y = 2 * y # 更新参数 x -= learning_rate * gradient_x y -= learning_rate * gradient_y # 保存历史数据 history.append((x, y, f(x, y))) return history# 执行随机梯度下降history = stochastic_gradient_descent()# 提取数据x = [point[0] for point in history]y = [point[1] for point in history]z = [point[2] for point in history]# 创建图形和坐标轴fig = plt.figure()ax = fig.add_subplot(111, projection='3d')# 绘制曲面X = np.linspace(-2, 2, 50)Y = np.linspace(-2, 2, 50)X, Y = np.meshgrid(X, Y)Z = f(X, Y)ax.plot_surface(X, Y, Z, cmap='viridis', alpha=0.5)# 绘制随机梯度下降路径ax.plot(x, y, z, marker='o', color='red')# 设置坐标轴标签ax.set_xlabel('X')ax.set_ylabel('Y')ax.set_zlabel('f(X, Y)')# 显示图像plt.show()
运行上述代码,将会绘制一个三维图像。其中,曲面表示函数f(x, y) = x^2 + y^2,红色的点表示随机梯度下降路径。
好了,感觉有用的朋友,点赞、转发给你身边需要的那个人!