← 计算机

线性回归

计算机

文章封面

最小二乘法

一般解参数

$$\hat{w}=(X^{T}X)^{-1}X^{T}y$$

特点

局部加权线性回归

$$\hat{w}=(X^{T}WX)^{-1}X^{T}Wy$$

def lwlr(testPoint,xArr,yArr,k=1.0):
    xMat = mat(xArr)
    yMat = mat(yArr).T
    m = shape(xMat)[0]
    wei = mat(eye(m))
    for j in range(m):
        diffMat = testPoint - xMat[j,:]
        wei[j,j] = exp(diffMat * diffMat.T/(-2.0 * k ** 2))
    xTx = xMat.T * (wei * xMat)
    ws = xTx.I * (xTx.T * (wei * 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

岭回归

$$\hat{w}=(X^{T}X+𝜆I)^{-1}X^{T}y$$

def ridgeRegree(xMat,yMat,lam=0.2):
    xTx = xMat.T * xMat
    denom = xTx + eye(shape(xMat)[1]) * lam
    ws = denom.I * (xMat.T * yMat)
    return ws

sklearn 代码示例

from numpy import *

x = array([[1],[1],[3],[4]])
y = array([1,2,3,5])

def standRegres(X,Y):
    X = mat(X)
    Y = mat(Y).T
    xTx = X.T * X
    ws = xTx.I * (X.T * Y)
    return ws

# ws = standRegres(x,y)
# py = mat(x) * ws
# print(ws)
# print(y)
# print(py)
#
import matplotlib.pyplot as plt
#
# fig = plt.figure()
# ax = fig.add_subplot(111)
# matx = mat(x)
# maty = mat(y)
# ax.scatter(matx[:,1].flatten().A[0],maty.T[:,0].flatten().A[0])
# xcopy = matx.copy()
# xcopy.sort(0)
# yhat = xcopy * ws
# ax.plot(xcopy[:,1],yhat)
# plt.show()

from sklearn.linear_model import LinearRegression

lr = LinearRegression()
lr.fit(x,y)
print(lr.predict([[7]]))
print(lr.coef_)

fig = plt.figure()
ax = fig.add_subplot(111)
k = arange(0,10)
v = [i* lr.coef_[0] + lr.intercept_ for i in k]
ax.scatter(x[:,0].flatten(),y)
ax.plot(k,v)
plt.show()
读到这里,感谢你的时间。继续阅读 →