python实现随机梯度下降法

Isabella ·
更新时间:2024-09-21
· 914 次阅读

看这篇文章前强烈建议你看看上一篇python实现梯度下降法:

一、为什么要提出随机梯度下降算法

注意看梯度下降法权值的更新方式(推导过程在上一篇文章中有)

 也就是说每次更新权值都需要遍历整个数据集(注意那个求和符号),当数据量小的时候,我们还能够接受这种算法,一旦数据量过大,那么使用该方法会使得收敛过程极度缓慢,并且当存在多个局部极小值时,无法保证搜索到全局最优解。为了解决这样的问题,引入了梯度下降法的进阶形式:随机梯度下降法。

二、核心思想

对于权值的更新不再通过遍历全部的数据集,而是选择其中的一个样本即可(对于程序员来说你的第一反应一定是:在这里需要一个随机函数来选择一个样本,不是吗?),一般来说其步长的选择比梯度下降法的步长要小一点,因为梯度下降法使用的是准确梯度,所以它可以朝着全局最优解(当问题为凸问题时)较大幅度的迭代下去,但是随机梯度法不行,因为它使用的是近似梯度,或者对于全局来说有时候它走的也许根本不是梯度下降的方向,故而它走的比较缓,同样这样带来的好处就是相比于梯度下降法,它不是那么容易陷入到局部最优解中去。

三、权值更新方式

(i表示样本标号下标,j表示样本维数下标)

四、代码实现(大体与梯度下降法相同,不同在于while循环中的内容)

import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d from matplotlib import style #构造数据 def get_data(sample_num=1000): """ 拟合函数为 y = 5*x1 + 7*x2 :return: """ x1 = np.linspace(0, 9, sample_num) x2 = np.linspace(4, 13, sample_num) x = np.concatenate(([x1], [x2]), axis=0).T y = np.dot(x, np.array([5, 7]).T) return x, y #梯度下降法 def SGD(samples, y, step_size=2, max_iter_count=1000): """ :param samples: 样本 :param y: 结果value :param step_size: 每一接迭代的步长 :param max_iter_count: 最大的迭代次数 :param batch_size: 随机选取的相对于总样本的大小 :return: """ #确定样本数量以及变量的个数初始化theta值 m, var = samples.shape theta = np.zeros(2) y = y.flatten() #进入循环内 loss = 1 iter_count = 0 iter_list=[] loss_list=[] theta1=[] theta2=[] #当损失精度大于0.01且迭代此时小于最大迭代次数时,进行 while loss > 0.01 and iter_count < max_iter_count: loss = 0 #梯度计算 theta1.append(theta[0]) theta2.append(theta[1]) #样本维数下标 rand1 = np.random.randint(0,m,1) h = np.dot(theta,samples[rand1].T) #关键点,只需要一个样本点来更新权值 for i in range(len(theta)): theta[i] =theta[i] - step_size*(1/m)*(h - y[rand1])*samples[rand1,i] #计算总体的损失精度,等于各个样本损失精度之和 for i in range(m): h = np.dot(theta.T, samples[i]) #每组样本点损失的精度 every_loss = (1/(var*m))*np.power((h - y[i]), 2) loss = loss + every_loss print("iter_count: ", iter_count, "the loss:", loss) iter_list.append(iter_count) loss_list.append(loss) iter_count += 1 plt.plot(iter_list,loss_list) plt.xlabel("iter") plt.ylabel("loss") plt.show() return theta1,theta2,theta,loss_list def painter3D(theta1,theta2,loss): style.use('ggplot') fig = plt.figure() ax1 = fig.add_subplot(111, projection='3d') x,y,z = theta1,theta2,loss ax1.plot_wireframe(x,y,z, rstride=5, cstride=5) ax1.set_xlabel("theta1") ax1.set_ylabel("theta2") ax1.set_zlabel("loss") plt.show() if __name__ == '__main__': samples, y = get_data() theta1,theta2,theta,loss_list = SGD(samples, y) print(theta) # 会很接近[5, 7] painter3D(theta1,theta2,loss_list) 您可能感兴趣的文章:python 梯度法求解函数极值的实例python实现共轭梯度法python梯度下降法的简单示例基于随机梯度下降的矩阵分解推荐算法(python)python实现梯度下降算法Python Sympy计算梯度、散度和旋度的实例



随机梯度下降 梯度下降 梯度 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号