线性回归和局部加权线性回归(转载)

转自:https://www.cnblogs.com/MrLJC/p/4147697.html

线性回归

算法优缺点:

  • 优点:结果易于理解,计算不复杂
  • 缺点:对非线性数据拟合不好
  • 适用数据类型:数值型和标称型

算法思想:

 

这里是采用了最小二乘法计算(证明比较冗长略去)。这种方式的优点是计算简单,但是要求数据矩阵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.  

  2. from numpy import *
    def loadDataSet(fileName):
        numFeat = len(open(fileName).readline().split('\t')) - 1 
        dataMat = []; labelMat = []
        fr = open(fileName)
        for line in fr.readlines():
            lineArr =[]
            curLine = line.strip().split('\t')
            for i in range(numFeat):
                lineArr.append(float(curLine[i]))
            dataMat.append(lineArr)
            labelMat.append(float(curLine[-1]))
        return dataMat,labelMat
    def standRegres(xArr,yArr):
        xMat = mat(xArr)
        yMat = mat(yArr).T
        xTx = xMat.T * xMat
        if linalg.det(xTx) == 0.0:
            print 'This matrix is singular, cannot do inverse'
            return
        ws = xTx.I * (xMat.T * yMat)
        return ws
    def plotStandRegres(xArr,yArr,ws):
        import matplotlib.pyplot as plt 
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot([i[1] for i in xArr],yArr,'ro')
        xCopy = xArr
        print type(xCopy)
        xCopy.sort()
        yHat = xCopy*ws
        ax.plot([i[1] for i in xCopy],yHat)
        plt.show()
    def calcCorrcoef(xArr,yArr,ws):
        xMat = mat(xArr)
        yMat = mat(yArr)
        yHat = xMat*ws
        return corrcoef(yHat.T, yMat)
    def lwlr(testPoint,xArr,yArr,k=1.0):
        xMat = mat(xArr); yMat = mat(yArr).T
        m = shape(xMat)[0]
        weights = mat(eye((m)))
        for j in range(m):
            diffMat = testPoint - xMat[j,:]
            weights[j,j] = exp(diffMat*diffMat.T/(-2.0*k**2))
        xTx = xMat.T * (weights * xMat)
        if linalg.det(xTx) == 0.0:
            print "This matrix is singular, cannot do inverse"
            return
        ws = xTx.I * (xMat.T * (weights * yMat))
        return testPoint * ws
    def lwlrTest(testArr,xArr,yArr,k=1.0):
        m = shape(testArr)[0]
        yHat = zeros(m)
        for i in range(m):
            yHat[i] = lwlr(testArr[i],xArr,yArr,k)
        return yHat
    def lwlrTestPlot(xArr,yArr,k=1.0):
        import matplotlib.pyplot as plt
        yHat = zeros(shape(yArr))
        xCopy = mat(xArr)
        xCopy.sort(0)
        for i in range(shape(xArr)[0]):
            yHat[i] = lwlr(xCopy[i],xArr,yArr,k)
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot([i[1] for i in xArr],yArr,'ro')
        ax.plot(xCopy,yHat)
        plt.show()
        #return yHat,xCopy
    def rssError(yArr,yHatArr): #yArr and yHatArr both need to be arrays
        return ((yArr-yHatArr)**2).sum()
    def main():
        #regression
        xArr,yArr = loadDataSet('ex0.txt')
        ws = standRegres(xArr,yArr)
        print ws
        #plotStandRegres(xArr,yArr,ws)
        print calcCorrcoef(xArr,yArr,ws)
        #lwlr
        lwlrTestPlot(xArr,yArr,k=1)
    if __name__ == '__main__':
        main()
     

Guess you like

Origin blog.csdn.net/bodybo/article/details/87876646