机器学习-梯度下降法

来源:互联网 发布:powell算法 编辑:程序博客网 时间:2024/04/28 14:51

梯度下降法,一般用来求解线性回归方程,我的理解是根据一组形如(特征1,特征2...-结果)的数据来找到这些对应的特征和结果之间的联系

例如,我们利用一组价格-销量的数据判断一个物品的销量和价格之间的关系

我们要求的线性回归方程可以表示为:

销量 = 价格 * 价格参数

实质上其实就是找到对应的价格参数

而当影响一个结果的特征不只有一个的时候(例如影响物品销量的不只有价格,还有广告投放数量等),我们需要求的回归方程可以表示为


其中θ表示各个特征的参数

假设我们已经找到了对应的参数,我们用参数求得的结果与实际结果之间的距离可以用实际结果-求得结果的平方来衡量,即


换而言之,只要我们找到的参数能让J(θ)的值最小,即表示我们找到了最能表示特征与结果之间关系的参数,而找到这个函数最小值对应的θ的方法包括梯度下降法

梯度下降法是只每次朝梯度的方向移动一个步长,以此达到函数的最小值

梯度可以理解为一个向量,它指向了函数增长最快的方向,不懂的可以去看看网易公开课的多变量微积分

假设只有一组变量,求得J(θ)的梯度为



用梯度乘一个步长即是每次θ要移动的距离


有了这些,就可以写代码了

import numpy as npimport randomdef gettheta2(x,y,times,step):    '''    随机梯度下降算法    '''    a, b = np.shape(x)
    train = np.ones((a, b + 1))    m, n = np.shape(train)    train[:, 1:] = x    theta = np.zeros(n)    for i in range(times):        a = random.randint(0,m-1)        randm_train = train[a]        randm_label = y[a]        hp = np.dot(randm_train,theta.transpose())        error = randm_label - hp        grand = np.dot(randm_train.transpose(),error)        theta = theta+grand*step    return thetadef gettheta1(x,y,times,step):    '''    批量梯度下降算法    '''    a,b = np.shape(x)    train = np.ones((a,b+1))    m, n = np.shape(train)    train[:,1:] = x    theta = np.zeros(n)    for i in range(times):        hp = np.dot(train,theta.transpose())        error = hp - y        grand = np.dot(train.transpose(),error)/m        theta = theta- step*grand    return train,thetadef liner(x,labe,times,step,input):    theta = gettheta2(x,labe,times,step)    result = np.dot(input,theta)    if __name__ == "__main__":    input = np.array([1,3.1,5.5])    liner(x,y,1000,0.01,input)
只需要记住还有个θ0,就不难理解上面的代码


原创粉丝点击