前面主要讲到了分类问题,从这节开始,进入到回归的学习。这节主要介绍几个常用的数值回归算法。
1、线性回归
数据的线性拟合
平方误差损失函数:
回归系数:
主要算法实现:
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
2、局部加权线性回归
由于线性回归可能的欠拟合,引入局部加权线性回归,根据距离训练样本和预测样本之间的距离不同,而给定不同的权值。
为了表示上面的权值,引入核,常用的核为高斯核:
k取不同值时,与权重w的关系
回归系数:
主要算法实现:
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): #next 2 lines create weights matrix
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"