函数说明:岭回归测试 Parameters: xMat - x数据集 yMat - y数据集 Returns: wMat - 回归系数矩阵 Website: http://www.cuijiahua.com/ Modify: 2017-11-20
(xArr, yArr)
| 51 | return ws |
| 52 | |
| 53 | def ridgeTest(xArr, yArr): |
| 54 | """ |
| 55 | 函数说明:岭回归测试 |
| 56 | Parameters: |
| 57 | xMat - x数据集 |
| 58 | yMat - y数据集 |
| 59 | Returns: |
| 60 | wMat - 回归系数矩阵 |
| 61 | Website: |
| 62 | http://www.cuijiahua.com/ |
| 63 | Modify: |
| 64 | 2017-11-20 |
| 65 | """ |
| 66 | xMat = np.mat(xArr); yMat = np.mat(yArr).T |
| 67 | #数据标准化 |
| 68 | yMean = np.mean(yMat, axis = 0) #行与行操作,求均值 |
| 69 | yMat = yMat - yMean #数据减去均值 |
| 70 | xMeans = np.mean(xMat, axis = 0) #行与行操作,求均值 |
| 71 | xVar = np.var(xMat, axis = 0) #行与行操作,求方差 |
| 72 | xMat = (xMat - xMeans) / xVar #数据减去均值除以方差实现标准化 |
| 73 | numTestPts = 30 #30个不同的lambda测试 |
| 74 | wMat = np.zeros((numTestPts, np.shape(xMat)[1])) #初始回归系数矩阵 |
| 75 | for i in range(numTestPts): #改变lambda计算回归系数 |
| 76 | ws = ridgeRegres(xMat, yMat, np.exp(i - 10)) #lambda以e的指数变化,最初是一个非常小的数, |
| 77 | wMat[i, :] = ws.T #计算回归系数矩阵 |
| 78 | return wMat |
| 79 | |
| 80 | def plotwMat(): |
| 81 | """ |
no test coverage detected