【ML_Algorithm 3 】回归算法的实际应用(一)

        此实例便是在二维空间中给出了两类数据点,现在需要找出两类数据的分类函数模型。即若输入新数据,所训练模型应可判断该数据属于二维空间中两类数据中的哪一类!

在给出Python实现的示例代码展示之前,先介绍一下两种优化准则函数的方法: 
1、梯度上升算法 
2、随机梯度上升算法

梯度上升算法: 
梯度上升算法和我们平时用的梯度下降算法思想类似,梯度上升算法基于的思想是:要找到某个函数的最大值,最好的方法是沿着这个函数的梯度方向探寻!直到达到停止条件为止! 
梯度上升算法的伪代码: 

随机梯度上升算法: 
梯度上升算法在每次更新回归系数时都需要遍历整个数据集,该方法在处理小数据时还尚可,但如果有数十亿样本和成千上万的特征,那么该方法的计算复杂度太高了,改进方法便是一次仅用一个数据点来更新回归系数,此方法便称为随机梯度上升算法!由于可以在更新样本到来时对分类器进行增量式更新,因而随机梯度上升算法是一个“在线学习算法”。而梯度上升算法便是“批处理算法”!

改进的随机梯度上升算法: 
随机梯度上升算法虽然大大减少了计算复杂度,但是同时正确率也下降了!所以可以对随机梯度上升算法进行改进!改进分为两个方面: 
改进一、对于学习率alpha采用非线性下降的方式使得每次都不一样 
改进二:每次使用一个数据,但是每次随机的选取数据,选过的不再进行选择

from numpy import *
import matplotlib.pyplot as plt

#从文件中加载数据:特征X,标签Lable
def loadDataSet():
    dataMatrix = []
    dataLable = []
    #这里给出了Python 中读取文件的简便方式
    f = open('testSet.txt')
    for line in f.readlines():
        lineList = line.strip().split()
        dataMatrix.append([1,float(lineList[0]),float(lineList[1])])
        dataLable.append(int(lineList[2]))

    matLabel = mat(dataLable).transpose()
    return dataMatrix,matLabel



#logistic回归使用了 sigmoid 函数
def sigmoid(inX):
    return 1/(1+exp(-inX))


#函数中涉及如何讲list 转化成矩阵的操作:mat()
#同时还含有矩阵的转置操作:transpose()
#还有list和array的shape函数
#在处理矩阵乘法时,需要注意维度是否对应。

#graAscent函数实现了梯度上升法,隐含了复杂的函数推理。
#梯度上升算法,每次参数迭代时都需要便利整个数据集
def graAscent(dataMatrix,matLable1):
    m,n=shape(dataMatrix)
    matMatrix = mat(dataMatrix)

    w=ones((n,1))
    alpha = 0.01
    num = 500
    for i in range(num):
        error = sigmoid(matMatrix*w)-matLable1
        w=w-alpha*matMatrix.transpose()*error
    return w

#随机梯度上升算法的实现,对于数据量较多的情况下计算量小,但分类效果差
#每次参数迭代式通过一个数据进行运算
def stocGraAscent(dataMatrix,matLabel):
    m,n = shape(dataMatrix)
    matMatrix = mat(dataMatrix)

    w=ones((n,1))
    alpha = 0.001
    num = 20    #这里的迭代次数对于分类效果影响很大。但其若很小的时候分类效果就会很差。
    for i in range(num):
        for j in range(m):
            error = sigmoid(matMatrix[j]*w)-matLabel[j]
            w=w-alpha*matMatrix[j].transpose()*error

    return w


#改进后的随机梯度上升算法
#从两个方面对随机梯度上升算法进行了改进,正确率提高了许多
#改进一:对于学习率alpha采用非线性下降的方式,使得每次都不一样
#改进二:每次使用一个数据,但是每次随机的选取数据,选过的不再进行选择
def stocGraAscent1(dataMatrix,matLabel):
    m,n = shape(dataMatrix)
    matMatrix = mat(dataMatrix)

    w=ones((n,1))
    num = 200    #这里的迭代次数对于分类效果影响很大。但其若很小的时候分类效果就会很差。
    setIndex = set([])
    for i in range(num):
        for j in range(m):
            alpha = 4/(1+i+j)+0.01

            dataIndex = random.randint(0,100)
            while dataIndex in setIndex:
                setIndex.add(dataIndex)
                dataIndex = random.randint(0,100)
            error = sigmoid(matMatrix[dataIndex]*w) - matLabel[dataIndex]
            w=w-alpha*matMatrix[dataIndex].transpose()*error
    return w

#绘制图像
def draw(weight):
    x0List = [] ; y0List = [] ;
    x1List = [] ; y1List = [] ;
    f = open('testSet.txt','r')
    for line in f.readlines():
        lineList = line.strip().split()
        if lineList[2] == '0':
            x0List.append(float(lineList[0]))
            y0List.append(float(lineList[1]))
        else:
            x1List.append(float(lineList[0]))
            y1List.append(float(lineList[1]))

    fig = plt.figure()
    ax=fig.add_subplot(111)
    ax.scatter(x0List,y0List,s=10,c='red')
    ax.scatter(x1List,y1List,s=10,c='green')

    xList = [] ; yList = [] ;
    x=arange(-3,3,0.1)
    for i in arange(len(x)):
        xList.append(x[i])

    y = (-weight[0]-weight[1]*x)/weight[2]
    for j in arange(y.shape[1]):
        yList.append(y[0,j])

    ax.plot(xList,yList)
    plt.xlabel('x1'); plt.ylabel('x2')
    plt.show()

if __name__=='__main__':
    dataMatrix,matLabel = loadDataSet()
    #weight=graAscent(dataMatrix,matLabel)
    weight = stocGraAscent1(dataMatrix,matLabel)
    print(weight)
    draw(weight)

个人通过以上的算法,所实现的结果如下:

1. 上图是采用的是梯度上升算法(graAscent函数)。复杂度较高。

梯度上升算法:
def graAscent(dataMatrix,matLable1):
    m,n=shape(dataMatrix)
    matMatrix = mat(dataMatrix)
    w=ones((n,1))
    alpha = 0.01
    num = 500
    for i in range(num):
        error = sigmoid(matMatrix*w)-matLable1
        w=w-alpha*matMatrix.transpose()*error
    return w

此算法隐含了函数推理过程。。其每次参数迭代时都需要遍历整个数据集。

2. 上图采用随机梯度上升算法,分类效果略差吗,运算复杂度低。 

#随机梯度上升算法的实现,对于数据量较多的情况下计算量小,但分类效果差
#每次参数迭代式通过一个数据进行运算
def stocGraAscent(dataMatrix,matLabel):
    m,n = shape(dataMatrix)
    matMatrix = mat(dataMatrix)

    w=ones((n,1))
    alpha = 0.001
    num = 20    #这里的迭代次数对于分类效果影响很大。但其若很小的时候分类效果就会很差。
    for i in range(num):
        for j in range(m):
            error = sigmoid(matMatrix[j]*w)-matLabel[j]
            w=w-alpha*matMatrix[j].transpose()*error

    return w

3. 是使用改进后的随机梯度上升算法,分类效果好,运算复杂度低

#改进后的随机梯度上升算法
#从两个方面对随机梯度上升算法进行了改进,正确率提高了许多
#改进一:对于学习率alpha采用非线性下降的方式,使得每次都不一样
#改进二:每次使用一个数据,但是每次随机的选取数据,选过的不再进行选择
def stocGraAscent1(dataMatrix,matLabel):
    m,n = shape(dataMatrix)
    matMatrix = mat(dataMatrix)

    w=ones((n,1))
    num = 200    #这里的迭代次数对于分类效果影响很大。但其若很小的时候分类效果就会很差。
    setIndex = set([])
    for i in range(num):
        for j in range(m):
            alpha = 4/(1+i+j)+0.01

            dataIndex = random.randint(0,100)
            while dataIndex in setIndex:
                setIndex.add(dataIndex)
                dataIndex = random.randint(0,100)
            error = sigmoid(matMatrix[dataIndex]*w) - matLabel[dataIndex]
            w=w-alpha*matMatrix[dataIndex].transpose()*error
    return w

附:

本例数据如下,请自行保存并——命名为testSet.txt并与代码放在同一文件夹下,从而省的从代码中添加文件路径。

-0.017612    14.053064    0
-1.395634    4.662541    1
-0.752157    6.538620    0
-1.322371    7.152853    0
0.423363    11.054677    0
0.406704    7.067335    1
0.667394    12.741452    0
-2.460150    6.866805    1
0.569411    9.548755    0
-0.026632    10.427743    0
0.850433    6.920334    1
1.347183    13.175500    0
1.176813    3.167020    1
-1.781871    9.097953    0
-0.566606    5.749003    1
0.931635    1.589505    1
-0.024205    6.151823    1
-0.036453    2.690988    1
-0.196949    0.444165    1
1.014459    5.754399    1
1.985298    3.230619    1
-1.693453    -0.557540    1
-0.576525    11.778922    0
-0.346811    -1.678730    1
-2.124484    2.672471    1
1.217916    9.597015    0
-0.733928    9.098687    0
-3.642001    -1.618087    1
0.315985    3.523953    1
1.416614    9.619232    0
-0.386323    3.989286    1
0.556921    8.294984    1
1.224863    11.587360    0
-1.347803    -2.406051    1
1.196604    4.951851    1
0.275221    9.543647    0
0.470575    9.332488    0
-1.889567    9.542662    0
-1.527893    12.150579    0
-1.185247    11.309318    0
-0.445678    3.297303    1
1.042222    6.105155    1
-0.618787    10.320986    0
1.152083    0.548467    1
0.828534    2.676045    1
-1.237728    10.549033    0
-0.683565    -2.166125    1
0.229456    5.921938    1
-0.959885    11.555336    0
0.492911    10.993324    0
0.184992    8.721488    0
-0.355715    10.325976    0
-0.397822    8.058397    0
0.824839    13.730343    0
1.507278    5.027866    1
0.099671    6.835839    1
-0.344008    10.717485    0
1.785928    7.718645    1
-0.918801    11.560217    0
-0.364009    4.747300    1
-0.841722    4.119083    1
0.490426    1.960539    1
-0.007194    9.075792    0
0.356107    12.447863    0
0.342578    12.281162    0
-0.810823    -1.466018    1
2.530777    6.476801    1
1.296683    11.607559    0
0.475487    12.040035    0
-0.783277    11.009725    0
0.074798    11.023650    0
-1.337472    0.468339    1
-0.102781    13.763651    0
-0.147324    2.874846    1
0.518389    9.887035    0
1.015399    7.571882    0
-1.658086    -0.027255    1
1.319944    2.171228    1
2.056216    5.019981    1
-0.851633    4.375691    1
-1.510047    6.061992    0
-1.076637    -3.181888    1
1.821096    10.283990    0
3.010150    8.401766    1
-1.099458    1.688274    1
-0.834872    -1.733869    1
-0.846637    3.849075    1
1.400102    12.628781    0
1.752842    5.468166    1
0.078557    0.059736    1
0.089392    -0.715300    1
1.825662    12.693808    0
0.197445    9.744638    0
0.126117    0.922311    1
-0.679797    1.220530    1
0.677983    2.556666    1
0.761349    10.693862    0
-2.168791    0.143632    1
1.388610    9.341997    0
0.317029    14.739025    0


---------------------本算法代码来源如下,旨在自我实现已巩固已学--------------------- 
作者:feilong_csdn 
原文:https://blog.csdn.net/feilong_csdn/article/details/64128443 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值