2019-01-23
阅读量:
850
岭回归python代码怎么实现?
岭回归就是在矩阵xTx上增加一项使得矩阵非奇异,从而能够对其求逆。在之前对xTx求逆时都需要先判断xTx是否可以求逆,而岭回归就是解决这个问题的。
实现代码如下:
import numpy as np
import matplotlib.pyplot as plt
def ridgeRegres(xMat,yMat,lam=0.2):
xTx = xMat.T*xMat
denom = xTx + np.eye(np.shape(xMat)[1])*lam
if np.linalg.det(denom) == 0.0:
print("This matrix is singular, cannot do inverse")
return
ws = denom.I * (xMat.T*yMat)
return ws
def ridgeTest(xArr,yArr):
xMat = np.mat(xArr); yMat=np.mat(yArr).T
yMean = np.mean(yMat) # 数据标准化
# print(yMean)
yMat = yMat - yMean
# print(xMat)
#regularize X's
xMeans = np.mean(xMat,0)
xVar = np.var(xMat,0)
xMat = (xMat - xMeans) / xVar #(特征-均值)/方差
numTestPts = 30
wMat = np.zeros((numTestPts,np.shape(xMat)[1]))
for i in range(numTestPts): # 测试不同的lambda取值,获得系数
ws = ridgeRegres(xMat,yMat,np.exp(i-10))
wMat[i,:]=ws.T
return wMat
# import data
ex0 = np.loadtxt('abalone.txt',delimiter='\t')
xArr = ex0[:,0:-1]
yArr = ex0[:,-1]
# print(xArr,yArr)
ridgeWeights = ridgeTest(xArr,yArr)
# print(ridgeWeights)
plt.plot(ridgeWeights)
plt.show()

纵坐标为回归系数,横坐标为log(lambda),在最左边,回归系数与线性回归一致,最右边系数全部缩减为0.
其中间某部分可以得到最好的预测结果,为了定量进行寻找最佳参数,还需要进行交叉验证。
以上代码python环境均为python3.6






评论(0)


暂无数据
推荐帖子
0条评论
0条评论
0条评论