【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 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章