線性回歸和局部加權線性回歸


線性回歸

算法優缺點:

  • 優點:結果易於理解,計算不復雜
  • 缺點:對非線性數據擬合不好
  • 適用數據類型:數值型和標稱型

算法思想:

這里是采用了最小二乘法計算(證明比較冗長略去)。這種方式的優點是計算簡單,但是要求數據矩陣X滿秩,並且當數據維數較高時計算很慢;這時候我們應該考慮使用梯度下降法或者是隨機梯度下降(同Logistic回歸中的思想完全一樣,而且更簡單)等求解。這里對估計的好壞采用了相關系數進行度量。

數據說明:

這里的txt中包含了x0的值,也就是下圖中前面的一堆1,但是一般情況下我們是不給出的,也就是根據一個x預測y,這時候我們會考慮到計算的方便也會加上一個x0。

數據是這樣的

函數:

loadDataSet(fileName):
讀取數據。
standRegres(xArr,yArr)
普通的線性回歸,這里用的是最小二乘法


plotStandRegres(xArr,yArr,ws)
畫出擬合的效果
calcCorrcoef(xArr,yArr,ws)
計算相關度,用的是numpy內置的函數

結果:

局部加權線性回歸(Locally Weighted Linear Regression)

算法思想:

這里的想法是:我們賦予預測點附近每一個點以一定的權值,在這上面基於最小均方差來進行普通的線性回歸。這里面用“核”(與支持向量機相似)來對附近的點賦予最高的權重。這里用的是高斯核:

函數:

lwlr(testPoint,xArr,yArr,k=1.0)
根據計算公式計算出再testPoint處的估計值,這里要給出k作為參數,k為1的時候算法退化成普通的線性回歸。k越小越精確(太小可能會過擬合)求解用最小二乘法得到如下公式:


lwlrTest(testArr,xArr,yArr,k=1.0)
因為lwlr需要指定每一個點,這里把整個通過循環算出來了
lwlrTestPlot(xArr,yArr,k=1.0)
將結果繪制成圖像

結果:
 
 
  1.  1 from numpy import *
     2 def loadDataSet(fileName):
     3     numFeat = len(open(fileName).readline().split('\t')) - 1 
     4     dataMat = []; labelMat = []
     5     fr = open(fileName)
     6     for line in fr.readlines():
     7         lineArr =[]
     8         curLine = line.strip().split('\t')
     9         for i in range(numFeat):
    10             lineArr.append(float(curLine[i]))
    11         dataMat.append(lineArr)
    12         labelMat.append(float(curLine[-1]))
    13     return dataMat,labelMat
    14 def standRegres(xArr,yArr):
    15     xMat = mat(xArr)
    16     yMat = mat(yArr).T
    17     xTx = xMat.T * xMat
    18     if linalg.det(xTx) == 0.0:
    19         print 'This matrix is singular, cannot do inverse'
    20         return
    21     ws = xTx.I * (xMat.T * yMat)
    22     return ws
    23 def plotStandRegres(xArr,yArr,ws):
    24     import matplotlib.pyplot as plt 
    25     fig = plt.figure()
    26     ax = fig.add_subplot(111)
    27     ax.plot([i[1] for i in xArr],yArr,'ro')
    28     xCopy = xArr
    29     print type(xCopy)
    30     xCopy.sort()
    31     yHat = xCopy*ws
    32     ax.plot([i[1] for i in xCopy],yHat)
    33     plt.show()
    34 def calcCorrcoef(xArr,yArr,ws):
    35     xMat = mat(xArr)
    36     yMat = mat(yArr)
    37     yHat = xMat*ws
    38     return corrcoef(yHat.T, yMat)
    39 def lwlr(testPoint,xArr,yArr,k=1.0):
    40     xMat = mat(xArr); yMat = mat(yArr).T
    41     m = shape(xMat)[0]
    42     weights = mat(eye((m)))
    43     for j in range(m):
    44         diffMat = testPoint - xMat[j,:]
    45         weights[j,j] = exp(diffMat*diffMat.T/(-2.0*k**2))
    46     xTx = xMat.T * (weights * xMat)
    47     if linalg.det(xTx) == 0.0:
    48         print "This matrix is singular, cannot do inverse"
    49         return
    50     ws = xTx.I * (xMat.T * (weights * yMat))
    51     return testPoint * ws
    52 def lwlrTest(testArr,xArr,yArr,k=1.0):
    53     m = shape(testArr)[0]
    54     yHat = zeros(m)
    55     for i in range(m):
    56         yHat[i] = lwlr(testArr[i],xArr,yArr,k)
    57     return yHat
    58 def lwlrTestPlot(xArr,yArr,k=1.0):
    59     import matplotlib.pyplot as plt
    60     yHat = zeros(shape(yArr))
    61     xCopy = mat(xArr)
    62     xCopy.sort(0)
    63     for i in range(shape(xArr)[0]):
    64         yHat[i] = lwlr(xCopy[i],xArr,yArr,k)
    65     fig = plt.figure()
    66     ax = fig.add_subplot(111)
    67     ax.plot([i[1] for i in xArr],yArr,'ro')
    68     ax.plot(xCopy,yHat)
    69     plt.show()
    70     #return yHat,xCopy
    71 def rssError(yArr,yHatArr): #yArr and yHatArr both need to be arrays
    72     return ((yArr-yHatArr)**2).sum()
    73 def main():
    74     #regression
    75     xArr,yArr = loadDataSet('ex0.txt')
    76     ws = standRegres(xArr,yArr)
    77     print ws
    78     #plotStandRegres(xArr,yArr,ws)
    79     print calcCorrcoef(xArr,yArr,ws)
    80     #lwlr
    81     lwlrTestPlot(xArr,yArr,k=1)
    82 if __name__ == '__main__':
    83     main()

     


機器學習筆記索引






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM