2019-01-23
阅读量:
1030
岭回归python代码怎么实现?
岭回归就是在矩阵xTx上增加一项使得矩阵非奇异,从而能够对其求逆。在之前对xTx求逆时都需要先判断xTx是否可以求逆,而岭回归就是解决这个问题的。
实现代码如下:
import numpy as npimport matplotlib.pyplot as pltdef ridgeRegres(xMat,yMat,lam=0.2):xTx = xMat.T*xMatdenom = xTx + np.eye(np.shape(xMat)[1])*lamif np.linalg.det(denom) == 0.0:print("This matrix is singular, cannot do inverse")returnws = denom.I * (xMat.T*yMat)return wsdef ridgeTest(xArr,yArr):xMat = np.mat(xArr); yMat=np.mat(yArr).TyMean = np.mean(yMat) # 数据标准化# print(yMean)yMat = yMat - yMean# print(xMat)#regularize X'sxMeans = np.mean(xMat,0)xVar = np.var(xMat,0)xMat = (xMat - xMeans) / xVar #(特征-均值)/方差numTestPts = 30wMat = np.zeros((numTestPts,np.shape(xMat)[1]))for i in range(numTestPts): # 测试不同的lambda取值,获得系数ws = ridgeRegres(xMat,yMat,np.exp(i-10))wMat[i,:]=ws.Treturn wMat# import dataex0 = 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.0000
0
3
关注作者
收藏
评论(0)
发表评论
暂无数据
推荐帖子
0条评论
0条评论
0条评论

