110

梯度上升法

 5 years ago
source link: http://shujuren.org/article/749.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

梯度上升法的思想:解决目标函数的最大值的方法,具体操作就是沿着该函数的梯度方向探寻。

函数f(x, y)的梯度定义:

NBJVzuB.png!web

函数f(x, y)必须要在计算的点有定义且可微。

一个具体的函数例子如下图:

RR73qib.png!web

梯度上升算法到达每个点后都会重新估计移动的方向。从P0开始,计算完该点 的梯度,函数就根据梯度移动到下一点P1。在P1点,梯度再次被重新计算,并 沿新的梯度方向移动到P2。如此循环迭代,直到满足停止条件。迭代的过程中, 梯度算子总是保证我们能选取到最佳的移动方向

梯度算子总是指向函数值增长最快的方向。

梯度算法的迭代公式:

zINRzaY.png!web

算法一直被迭代执行,直到达到某个终止条件为止。

常用的终止条件:

  • 迭代次数达到某个指定的值
  • 算法收敛

说明: 梯度上升算法用来求解函数的最大值,梯度下降算法用来求解函数的最小值。

应用

利用梯度上升法找到逻辑回归分类器的最佳拟合参数集。

样例数据,如下图:

Jbeiyu3.png!web

Python版本参考代码:

"""
梯度上升最优化方法求解逻辑回归分类器的最佳拟合参数集
"""
import numpy as np

#  加载数据函数
def loadDataSet(data_file):
    dataMat = []
    labelMat = []
    fr = open(data_file)
    for line in fr.readlines():
        lineArr = line.strip().split()
        dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])
        labelMat.append(int(lineArr[2]))
    return dataMat,labelMat

# sigmoid函数
def sigmoid(inX):
    return 1.0/(1+ np.exp(-inX))

# 梯度上升函数
def gradAscent(dataMatIn, classLabels):
    dataMatrix = np.mat(dataMatIn)
    labelMat = np.mat(classLabels).transpose()
    m,n = np.shape(dataMatrix)
    alpha = 0.001
    maxCycles = 500
    weights = np.ones((n,1))
    for k in range(maxCycles):
        h = sigmoid(dataMatrix*weights)
        error = (labelMat - h)
        weights = weights + alpha * dataMatrix.transpose()* error
    return weights


if __name__ == "__main__":
    dataArr,labelMat = loadDataSet("LR_testSet.txt")
    LR_weights = gradAscent(dataArr,labelMat)
    print("逻辑回归分类器最佳拟合参数集:\n {}".format(LR_weights))

NJfA7zQ.png!web

版权声明:作者保留权利,严禁修改,转载请注明原文链接。

数据人网是数据人学习、交流和分享的平台http://shujuren.org 。专注于从数据中学习到有用知识。 平台的理念:人人投稿,知识共享;人人分析,洞见驱动;智慧聚合,普惠人人。 您在数据人网平台,可以1)学习数据知识;2)创建数据博客;3)认识数据朋友;4)寻找数据工作;5)找到其它与数据相关的干货。 我们努力坚持做原创,聚合和分享优质的省时的数据知识! 我们都是数据人,数据是有价值的,坚定不移地实现从数据到商业价值的转换!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK